text:
Q: Using large set of strings in word tree visualization I can't copy and paste all the strings in my file and run the code using this example
https://developers.google.com/chart/interactive/docs/gallery/wordtree
https://jsfiddle.net/api/post/library/pure/
I modified the html and javascript code and replaced phrases with a small set of strings from my file and got everything to work. Now I want to do the same thing with my full file, but there are too many strings to copy and paste. How can I use javascript to import my large dataset and do I make each row formatted the same with "['some text here']," or does javascript insert the brackets when the file is uploaded?
The HTML File:

The JavaScript File:
 google.charts.load('current', {packages:['wordtree']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable(
          [ ['Phrases'],
                    ['return refund not received'],
                        ['hello, every time i try to print the invoice, nothing loads. i have tried different browsers and devices. can i get it emailed to me?'],
                        ['how long for delivery and do i need a prescription'],
                        ['i recently requested replacement lenses for some that were defective and received the wrong prescription'],
                        ['my order is pending verification of prescription.  however, my prescription hasn't changed and i ordered last month without any delays.'],
          ]
        );

        var options = {
          wordtree: {
            format: 'implicit',
            //alt is 'suffix', 'prefix'
            type: 'double',
            word: 'prescription'
          }
        };

        var chart = new google.visualization.WordTree(document.getElementById('wordtree_basic'));
        chart.draw(data, options);
      }

I would like to be able to upload the file (csv format) from my desktop (or other location) instead of copying and pasting small sections of my open ended feedback. Thanks.

A: You can use a Google sheet.
Snippet:
function drawVisualization() {
        var wrapper = new google.visualization.ChartWrapper({
          chartType: 'WordTree',
          dataSourceUrl: 'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7V',
          query: 'SELECT A',
          containerId: 'wordtree_basic'
        });
}

To Read:

*

*Google sheets Integration

*ChartWrapper

*Csv import


text:
Q: Give multiple tags on a button I'm using this code for giving at least one tag in my button.
 button1.Tag= "FirstTag";

 MessageBox.Show(button1.Tag.ToString());

How can i add at least one more tag in my button.I'm looking for something easy and quick

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA WorkSheetFunction.Mode of a Dynamic Populated Array I can't figure out how to find the mode of a dynamic array that I fill out. Here is the code:
Sub test_array()
Dim test() As Integer
Dim i As Integer

For i = 1 To 3
ReDim Preserve test(i)
test(i) = i
Mode = Application.WorksheetFunction.Mode(test(i), 1)
Next i

End Sub
I don't know how to tell the mode function to process the array value as a number. In this example the mode is forced to be 1 ''cause it would be like Mode(1,1,2,3)
P.S. The mode is a function that returns the most recurring number.

A: You are testing the mode of each number individually not the whole array.  Move the function after the loop.
But it will not like the use of an array and another number.  So add the 1 to the end of the array and then use the array in the mode
Sub foo()

Dim test() As Integer
Dim i As Integer
Dim md As Integer

ReDim test(1 To 3) As Integer

For i = 1 To 3
    test(i) = i
Next i

ReDim Preserve test(1 To UBound(test) + 1)
test(UBound(test)) = 1

md = Application.WorksheetFunction.Mode(test)

MsgBox md
End Sub

First we fill the standard array.  And to add the extra 1 into the array, because the MODE Function does not like an array and a single variable.
The ReDim Preserve test(1 To UBound(test) + 1) finds the upper bound of the test array.  In this case it would be 3.  It then add one more box into which we can add an integer.
So now the upper bound is 4 and we use test(UBound(test)) = 1 to put 1 in the last space.
This is a way to ensure that no matter how large or small the array is it will always add one more box into the array and in that box put the 1.


text:
Q: Matching parenthesis with recursion and stacks I am trying to figure out how to write this code using recursion. I have done it sing for loops but have absolutely no clue how to use recursion here. I am new to code.Thanks for stopping by and helping.
P.S.
Sorry if i didnt explain what this does. The objective is to find out how many matching pairs of parenthesis exist in a given string input. It should also return -1 if a set is unbalanced.
These are the instructions
Classes names.
MatchingBracesFirstNameLastName.java
Stack.java
Description.
Write a program to match parenthesis (), square braces [] and curly braces {}. Your program should use a recursive method that returns the number of pairs of each type of brace and return -1 if it is unbalanced for a particular pair. You should also create a Stack class that will be used by the method to match braces.
import java.util.*;

public class MatchingBraces
{
   public static void main(String []args)
   {
      Scanner input = new Scanner(System.in);
      String text = input.nextLine();
      System.out.println(match(text, '(', ')', 0));
      System.out.println(match(text, '[', ']', 0));
      System.out.println(match(text, '{', '}', 0));
   }

   public static int match(String text, char open, char close, int startIndex)
   {
      Stack<Character> stack = new Stack<Character>();
      int count = 0;
      char c;
      for(int i = 0; i < text.length(); i++)
      {
         c = text.charAt(i);
         if(c == open)
            stack.push(c);

         if(c == close)
         {
            if(stack.empty())
               return count;
            else if(stack.peek() == open)
            {
               stack.pop();
               count++;
            }
         }
      }
     return count;
   }
}

A: To start with, I would redefine the part of the problem that is recursive (or stack-oriented, they're isomorphic). You are scanning an input string and you want to count the number of balanced pairs of tokens.
So you can break this up into two sub-problems:

*

*Find every open character in the string, and check that it has a matching close character.

*Given the location of an open character, find the location of the matching close character.

Both problems could be implemented recursively, but problem #2 is more naturally a recursive problem. This is because the problem is naturally nested: while you're finding the matching close character for one pair, if you encounter a new open character, you need to first find the matching close character for it before going back to finding the current matching close character. This is a classic inductive or recursive way of formulating a problem.
If you're OK with a bit more complexity, you can solve both problems at once by formulating your sub-problem as:

*

*Given the location of an open character, return both the location of the corresponding closing character and the number of pairs of open/close contained within that pair, if any.

The reason I wouldn't jump to that second option right now is because returning two values opens up a number of other questions. You could use an external state variable, or introduce a new class to represent the two values. It adds complexity, but ultimately adding a new type here is probably the best overall solution.
I don't want to do your homework for you, but hopefully this helps you to see what your next steps need to be. Hopefully that helps!

A: Unfortunately the current method signature doesn't contain enough information for a straightforward recursive solution, so I would add a helper method that returns two pieces of information: 1. the stack count for the next open starting from startIndex, and 2. the position of the last char processed.
You need this second piece of information so that the caller can continue where the recursive call left off.
Helper Logic:
Beginning at startIndex, proceed to the right until you encounter either an open or a close or end of input.
If you encounter a close first, return -1 for count. If end of input, 0. If you encounter an open first, proceed.
If you encounter an open next, initiate a subcall. Check the subcall for -1 and abort if so. Otherwise, update a local variable which records the max stacks count returned by any subcall thus far. Proceed to the next unprocessed character location.
If you encounter end of input next, return -1 for count.
If you encounter a close next, return 1 + maxOfSubcalls.
Note: it may be necessary for the main routine to invoke the helper again if end of input was not reached. in that case maxOfHelper would be returned, assuming no -1's.


text:
Q: Deleting a commit in Between other commits I have a local and its corresponding github repo. I have some commits as
A <- B <- C <- D

A being the latest.
This is situation on both the repos. I want to delete commit C as if it never happened.
So it should be like on git log
A <- B <- D

on both repos.
I tried git reset --soft <sha-commit-C> and am now stuck. I can not see A, B. Before doing any further steps i want to be fully sure that i know what i am doing.
git reflog gives me :
git reflog
73ea54d HEAD@{0}: reset: moving to 73ea54d8
a594699 HEAD@{1}: rebase -i (finish): returning to refs/heads/unique_ptr_release
a594699 HEAD@{2}: checkout: moving from unique_ptr_release to a594699fb6f7d85bc8
a594699 HEAD@{3}: checkout: moving from unique_ptr_release to unique_ptr_release
a594699 HEAD@{4}: commit (merge): Merge branch 'master' into unique_ptr_release

HEAD@{4} is what my Head was before reset --soft command.
How do i get out of this situation ?

A: Git-rebase is what are you looking for.
in your case of commit A-B-C-D, and want to remove C, try:
git rebase -i HEAD~3

it will show the last 3 of your commits via editor (mine is vim),
just delete (in vim: dd) the line of commit you want to remove,
then save it (in vim: :wq).
Done, view the git log and you will see that the C commit is removed.
*don't forget to backup your code or .git folder.

A: *

*Ensure you back up your .git folder.

*Ensure commit D , don't rely upon the changes made in C.

*git rebase --onto D B~1 (as A is the latest commit)


text:
Q: Time Fields only in grails I have domain class that uses
  Date StartTime
  Date endTime

E.g 9:00:00 , 15:00:00
What do i use in grails for just timePicker and not have dates.
Thanks!

A: There's no such thing out of the box in Grails.
Instead you can use any JS-timepicker, like http://keith-wood.name/timeEntry.html . This one is really simple to use.
Of course you have to do date parsing and formatting on your own.

A: If you can use a plugin, have a look at the Joda-Time Plugin and its documentation.
In your domain class you can do
DateTime startTime
DateTime endTime

Then in your views use the joda:dateTimePicker or  joda:datePicker or joda:timePicker as guided in documentation.


text:
Q: Matching all files ending with a certain extension with a shell glob (say, all files ending with .sh) I desire to match all files ending with a certain extension with a shell glob.
In this case I desire to target all files ending with the .sh extension, which are bourne files I execute with the Bash shell after putting a "shebang" (like #!/bin/bash) at their first line.
This is, for example, a cron command I have:
0 0 * * * "$HOME"/public_html/cron_daily/myfile.sh 2>/dev/null

Instead myfile.sh I need to target all files in that dir, ending with a .sh extension.
Is the following code correct?
0 0 * * * "$HOME"/public_html/cron_daily/*$.sh 2>/dev/null

Update
I think this is good when using a glob:
*.{sh}

A: You'd just use *.sh to match all files with a .sh extension. (Adding the path as appropriate.)
However this won't have the result you're after. Look at run-parts to run multiple scripts from cron:
0 0 * * * /usr/bin/run-parts "$HOME"/public_html/cron_daily/ 2>/dev/null

(This will run all executables in .../public_html/cron_daily, not just .sh files. By the way, are you sure it's a good idea to keep cron scripts under public_html? Is that directory being served by your web server?)

A: You can't do it that way, since they will be combined into one command line.
for scr in "$HOME"/public_html/cron_daily/*.sh ; do "$scr" 2> /dev/null; done


text:
Q: "rmic" no se reconoce como un comando interno o externo, programa o archivo por lotes ejecutable He estado tratando de compilar algunos programas mediante javac, y por ese lado todo bien, pero al momento de querer generar los stubs y skeletons, y usar el rmic para ello, me arroja el siguiente error:
"rmic" no se reconoce como un comando interno o externo, programa o archivo por lotes ejecutable.

Cabe destacar que ya al buscar dentro de la carpeta bin de mi jdk, este no viene, traté de descargarlo a árte y posteriormente añadirlo, y tampoco funciono, también, ya he modificado algunos valores en las variables del entorno en los PATHS y esto tampoco ayudo mucho.
¿Qué más podría hacer o cómo podría solucionarlo?


text:
Q: how to upload a image to google cloud storage with GAE using php I am trying to upload an image to Google cloud storage using php code.
I tried to follow instructions available on Google documentation, but it's not working.
Here is my code:
<?php
use google\appengine\api\cloud_storage\CloudStorageTools;

$options = ['gs_bucket_name' => 'myappname-178614.appspot.com'];
$upload_url = CloudStorageTools::createUploadUrl('/upload/handler', $options);
$file_name = $_FILES['uploaded_files']['name'];
$temp_name = $_FILES['uploaded_files']['tmp_name'];
move_uploaded_file($temp_name, "gs://myappname-178614.appspot.com/$file_name.jpg");
?>
<form action="<?php echo $upload_url;?>" enctype="multipart/form-data" method="post">
    Files to upload:

   <input type="file" name="uploaded_files" size="40">
   <input type="submit" value="Send">
</form>

There is no error while running the code...can someone help?

A: Found a solution:
<?php

use google\appengine\api\cloud_storage\CloudStorageTools;

$bucket = 'myapp-178614.appspot.com';
$root_path = 'gs://' . $bucket . '/';

$_url = '';
if(isset($_POST['submit'])){
if(isset($_FILES['userfile'])){
            $name = $_FILES['userfile']['name'];
            $file_size =$_FILES['userfile']['size'];
            $file_tmp =$_FILES['userfile']['tmp_name'];
            $original = $root_path .$name;
            move_uploaded_file($file_tmp, $original);
            $_url=CloudStorageTools::getImageServingUrl($original);
}
}

?>

<form action="test.php" method="post" enctype="multipart/form-data">
  Send these files:

  <input name="userfile" type="file" />

  <input type="submit" name="submit" value="Send files" />
</form>

<?php

  echo  $_url;

?>


text:
Q: Aurelia - when are child compositions done? Using the Aurelia JS framework, I need to be able to detect when the results of a repeat.for over  elements have been loaded completely into the DOM by code in the parent VM. I know I can inject a listener into a @bindable and trigger the listener on attached(), but that seems very hokey to me.
Any ideas?

A: The problem is that you are pushing items inside the attached method and you are using dynamic composition, which usually is not a problem but your situation is a bit different. Queuing a micro-task doesn't help because it runs before your view (child.html) is loaded.
There are couple ways to solve the this problem:
1° Solution
Push your items inside bind():
bind() {
  this.items.push({
     view: 'child.html',
     viewModel: new Child('A')
  });

  this.items.push({
     view: 'child.html',
     viewModel: new Child('B')
   });
}

attached() {

  let container = document.getElementById('container');
  console.log('Height after adding items: ' + container.clientHeight);

  this._taskQueue.queueMicroTask(() => {
    console.log('Height after queued microtask: ' + container.clientHeight);
  });

  setTimeout(() => {
    console.log('Height after waiting a second: ' + container.clientHeight);
  }, 1000);

}

Fix the HTML:
<template>

      <compose view-model.bind="item.viewModel" view.bind="item.view"></compose>

      ${log}

</template>

Running example https://gist.run/?id=7f420ed45142908ca5713294836b2d5e
2º Solution
Do not use <compose>. Compose was made to be used when dynamic compositions are necessary. Are you sure you need to use <compose>?.
<template>
  <require from="./child"></require>

      <child>${item.data}</child>

</template>


text:
Q: How can MP3 files without a file extension play in the Android files app and is there any way I can play such files in my MP3 player Android app? I am creating an MP3 Player app. It's mostly working correctly but there is one edge case.
If a user has a file named "Bieber.mp3" but changes the name of the file to "Bieber" without the file extension in the files app (on Android), they will still be able to play the song properly from the files app depending on the device (older devices like Nexus running on marshmallow will do it while newer devices like the pixel on Android 12 will say it's an invalid file type).
However, when the MP3 file is emailed (or uploaded somewhere in the cloud like drive or Dropbox), the file will have an unknown file type when  attempting to from there
I want to know, how can MP3 files that are renamed to exclude the .mp3 extension still play in the android files app? Is there any way I can check to see if a file without the .mp3 extension is still an audio/mp3 file in Java for my mp3 player?
If mp3 files without the mp3 extension can play in the android files app, surely there should be some way to play/access them in the MP3 player I'm making, right?

A: Well, Android has this library/class called MediaPlayer:
https://developer.android.com/guide/topics/media/mediaplayer
The MediaPlayer is what you use when you play audio,
the MediaPlayer takes the input(the file) as long as it is still encoded as an audio file.
No matter what you do with the file extension, as long as it is still encoded as audio,
it will stay as an audio file.
That's why~


text:
Q: Ajax not working in drupal 6 in Form
$form['assignJob'] = array(
                    '#type' => 'checkbox',
                    '#title' => 'AssignJob',
                    '#default_value' => 1,
                    '#suffix'=>"<script>$js</script>"
            )

in $js i defined the JS.
                $js = <<<EOJS
Drupal.behaviors.checkboxrender = function(context) {
  $('#edit-assignJob', context).change(function(event, ui) {
     var method = $(this).val();
     if(method){
        $.get('/assignJob/',null,responseDetails);
     }

  });
  var responseDetails=function(response){
    alert(response);
  }

};
EOJS;

In hook_menu in defined the menu
$items['assignJob'] = array(
        'page callback' => 'assignee',
        'type' => MENU_CALLBACK,
        'access arguments' => array('access administration'),
    );
    return $items;

function assignee() {
    $output='xxxx';
    return drupal_json(array('status' => TRUE, 'data' => $output));
    drupal_exit();
}

So whenever i click on checkbox it return me the blank value. Can anybody help in this.?
When i render this i got warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'assignee' not found or invalid function name in C:\Server\www\drupal-final\includes\menu.inc on line 350.

A: I'll try to help you . But all i know that what's responsible for Ajax call or javascript is the ahah property . have a read on drupal api http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#ahah
Also read this http://drupal.org/node/348475
By the way i never saw suffix that takes Script . i always use ahah property .
You can download this example http://www.kristen.org/content/drupal-ahah-form-examples
and read this article http://fuseinteractive.ca/blog/how-create-custom-drupal-ajax-module-0


text:
Q: Eclipse doesn't show projects in package explorer I keep my workspace folder in the Dropbox folder so I can use it on different computers. Usually there isn't a problem. Today however I opened Eclipse and found it doesn't show the projects in the package explorer.
I checked and it's set to the correct workspace folder.
I tried to Import existing projects into workspace, but Eclipse doesn't allow importing the projects because 'they already exist in the workspace' - even though they don't appear.
Will appreciate your help.

A: Keep your project files in DropBox.  You shouldn't share a workspace like that -- it will inevitably lead to issues like the one you describe.
That is, keep the project folder, along with the .project, .classpath, and .settings/ in your shared Dropbox space.  Create a new workspace on each computer, then "Import existing project" into each workspace, selecting your project in Dropbox, being sure to unselect "copy projects into workspace".

A: I don't have idea about using dropBox-BUT-However
For your question::
I tried to Import existing projects into workspace, but Eclipse doesn't allow importing the projects because 'they already exist in the workspace' - even though they don't appear.

Possibility:: Projects are not in Eclipse explorer but a copy of it exists in the workspace folder so eclipse is not allowing you to add the projects with same name again.

Solution:: Create a new workspace and then use dropbox to import the projects.

A: What you can also try is do

*

*Create new General Project

*Select in current workspace

*Create project with name of an already existing project in your workspace

I seem to remember using this to "hydrate" already existing projects in my workspace into the eclipse package explorer.

A: This happened to me and it was because I inadvertently filtered out some of the files in the filters option in the Package Explorer.
Inside PackageExplorer -> Small drop down on top right side -> Filters
Un-select all and see if your files are now visible. Worked for me.


text:
Q: Variable string matching I have a program that accepts command line inputs. The input is similar to this:
ruby myprogram.rb --option1 --option2=foo

Right now, I split the command by spaces and keep an array of commands. For example, this would be the array for the example above:
['option1','option2=foo']

In the code, there is a list of valid commands:
valid_cmd = %w(
    --option1
    --option2
    --option3
)

Using the list of parsed commands, what is the best way to check that a inputted command is valid? There is also a more difficult component to this. Let's say option2 has optional arguments. For example, --option2=anArgument is just as valid as --option2 alone. On the other hand, option3 has mandatory arguments - ie. --option3=foo is valid but --option3 is not. How can we account for this as well?


text:
Q: R equivalent of Max windows function I'd like to calculate the maximum value for a column so far in the dataset
The SQL equivalent would be something like this:
SELECT MAX(Sepal.length) over (PARTITION BY Species
           ROWS BETWEEN unbounded preceding and current row) as max_so_far

This is my code
iris %>%
  group_by(Species) %>%
  mutate(
    flower_id = row_number()
  ) %>%
  ungroup()

I'd like to get the max Sepal length for any flower with the same flower id or a smaller flower ID in that species

A: You are looking for cummax :
library(dplyr)
iris %>%
  group_by(Species) %>%
  mutate(
    flower_id = row_number()
  ) %>%
  ungroup() %>%
  mutate(running_max = cummax(Sepal.Length))


text:
Q: Use one Mongo doc to hold thousands of objects, or thousands of docs each holding one? In my web app, an authenticated user can pick songs from his spotify playlist to play at a party. I want guests (nonauthenticated users) to be able to view the picked songs on a dynamically created react route and vote on their favorite songs on their own device (probably a phone).
I am using a Mongo, Express, React/Redux, Node stack.
Since the guests don't have access to my app's redux store, the only way they can view the authenticated user's picked songs is through a GET request to my app's database. My initial plan was to just store playlist documents, and the users can GET those playlists to make a request to the spotify api. However, they are unauthorized and need an access token. This means that my database has to store every single one of the songs that the authenticated user picked.
My question has to do with design. I don't think it's a good idea for my one document to hold every song because some people might want to pick thousands of songs, and one document won't be able to hold all of the songs. On the other hand, creating a separate document for each song seems a little bit too excessive.
Can anyone help me figure out which option is better, or if there is a different option I haven't thought of that can avoid this problem altogether? Thank you

A: Assuming that if you would store each song in a separated document, the main disadvantage of this strategy is the space complexity, you'll need more space to store all documents.
But, supposing you'll keep all song documents at the same collection, it gives some advantages, for example: queries and sorts operations will be more flexible and faster. It helps you to save both processing and development time. A similar logic is showed here.
Use just one document to store all songs makes your database operations more complex, what requires more development time and code to organize all retrieved data on the proper way. Another disadvantage is that it isn't a long term scalable strategy, mainly because the limit of a BSON document is 16MB.
At my vision, the design of separated documents for each song is more appropriate and the reasons are:

*

*Space is monetarily cheap.

*Save time complexity must be a priority on all points of software development. Database queries usually are the slower operations in a software. So, reduce the cost of time at database operations is a good objective to seek. Storing all documents in one collection instead of in one document will retrieve all data already organized, with no no need to retreat at code.


text:
Q: In a data warehouse with small amount of writes, would RAID 1 be better than RAID 1+0? We are using HP Vertica database 7.2 community version.  300GB of data on one node. Thats a small amount of data.
HP officially recommends RAID 1+0.
https://community.dev.hpe.com/t5/Vertica-Knowledge-Base/RAID-Storage-for-HPE-Vertica/ta-p/234225
But I do not envision a problem with write performance which is the point of RAID 0.  I am not planning to load, insert or write large amounts of data.  I am planning to query large amounts of data, but not write a lot.  It seems to me that RAID 1 is sufficient.
Is there anything wrong with using RAID 1 instead of 1+0?

A: This is a pretty open ended question and you might want to just test it yourself and see.  It depends on how you query and write the data.  This will determine how many IOPS you need at peak use, which if you want to ensure you'd figure out by testing then deciding.
However if that is not an option, do you have hundreds of gigs of RAM?  Some systems do.  If so, perhaps your read/write patterns will hit RAM and Disk IO won't matter.  Are you using SSDs or magnetic disks?  SSDs have a much higher disk IO and IOPS than traditional spinning media so the write penalty might not even be noticeable.
Really not sure how much more to add here, it'll come down to your testing results and IOPS needs.


text:
Q: Найти рекурсию двух функций, зависящих одна от другой Ak=0.3Ak+0.2Bk
Bk=Ak+Bk

В делфи есть forward, что можно сделать в с++?

A: В C++ тоже есть
double FooBar();

double FooBar()
{
    // Do something
}

A: Где то так
float B(int k);
float A(int k) {
  return 0.3 * A(k) + 0.2*B(k);
}

float B(int k) {
  return A(k) + B(k);
}

вот только не пытайтесь это запускать - зависнет. Как минимум, следующий элемент должен зависеть от предыдущего, а не от себя самого. А во вторых, должно быть так называемое "условие выхода из рекурсии".


text:
Q: jquery - replace next element and add css class to next element I would like to replace next element of a given element and add css class to the next element.
I tried like this but it didn't work.
$(".validate_txt_sContactFirstName")
    .next()
    .replaceWith('
2
')
    .addClass("atleastTwoChars");

    <nobr>
        <input name="ctl00$objContentPageTag$spzContactInformation$txt_sContactFirstName$txt"
        type="text" size="25"
        id="ctl00_objContentPageTag_spzContactInformation_txt_sContactFirstName_txt"
        class="xqh_TextBox_Edit validate_txt_sContactFirstName error"
        style="width:150px;margin-right:1px;">

    </nobr>

A: $(".validate_txt_sContactFirstName")
    .next()
    .text(2);

This is what you could use here. That way only the content of the
 is edited. If you need HTML replace text(2) with html('2')

A: if i am getting you correctly you can do it in a very simple way, because when you already have the class atleastTwoChars in the div what is meaning of replacing it adding text in it and then add same class. you can just replace inner value of div.
$('.atleastTwoChars').html(2);

fiddle : http://jsfiddle.net/qXydv/


text:
Q: MPI - Suppress output from some processors Is there a way to make MPI just print the output from one (or a subset) of the processes? I know how to do that on code level, but I am wondering whether there is some way to specify this after the executable has already been compiled. I am thinking of getting the output as in one of the windows in the following command
mpirun -np [#processes]  xterm -e [path to executable]

just without using xterm.
I know that I can tag the output using the -tag-output option and then can filter it by hand, but this is kind of tedious. As MPI knows exactly where the output is coming from, is there no easier way to accomplish this goal?

A: You could write a wrapper script. Since Open MPI makes the process rank in MPI_COMM_WORLD available in an environment variable called OMPI_COMM_WORLD_RANK, it is very easy to do something like:
#!/bin/bash

UNMUTE=$1
shift 1

if [ "$OMPI_COMM_WORLD_RANK" == "$UNMUTE" ]; then
  exec $*
else
  exec $* >/dev/null 2>&1
fi

Save this to unmute.sh and execute it like:
$ mpiexec -n #procs unmute.sh #rank executable [params]

The script redirects the standard output and error streams to /dev/null for all ranks except for the one specified. You could make the comparison logic more elaborate, e.g. compare against a range or a list of ranks.
Here is a sample of the above script in action:
$ mpiexec -n 6 printenv | grep COMM_WORLD_RANK
OMPI_COMM_WORLD_RANK=0
OMPI_COMM_WORLD_RANK=1
OMPI_COMM_WORLD_RANK=2
OMPI_COMM_WORLD_RANK=3
OMPI_COMM_WORLD_RANK=4
OMPI_COMM_WORLD_RANK=5
$ mpiexec -n 6 unmute.sh 3 printenv | grep COMM_WORLD_RANK
OMPI_COMM_WORLD_RANK=3


text:
Q: Why does the general normal distribution include $\mu$ and $\sigma$? The normal distribution function is defined as $$\phi(x) = \frac{1}{\sigma \sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$
I follow the logic of how and why we can obtain
$$f(x) = \frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}$$
and why this function is useful. So it should only be a small step from this to the general normal distribution. However, I don't understand the purpose of including $\mu$ and $\sigma$ in the exponent.
My Question
What purpose does including $\mu$ and $\sigma$ in the exponent serve? How does putting these variables in the exponent help with this?
Remark:
Also, $\sigma$ is a function of $\mu$
$$\sigma(\mu) = \sqrt{E[(x-\mu)^2]}$$
So isn't the normal distribution really only a function of $\mu$?
Remark:
All I really understand about $\sigma$'s role is that it affects the width of the distribution and $\mu$ affects where the distribution is centered.

A: The density $$f(z) = \frac{1}{\sqrt{2\pi}} e^{-z^2/2}, \quad -\infty < z < \infty,$$ corresponds to a random variable $Z$ that is normally distributed with mean $0$ and variance $1$.  This much should be clear.  Now we generalize this distribution by considering the location-scale family of such distributions characterized by $$X = \sigma Z + \mu,$$ i.e., we scale the random variable $Z$ by a factor of $\sigma > 0$, and add a location parameter $\mu$.  By the linearity of expectation, we see that $$\operatorname{E}[X] = \operatorname{E}[\sigma Z + \mu] = \operatorname{E}[\sigma Z] + \operatorname{E}[\mu] = \sigma \operatorname{E}[Z] + \mu = \sigma(0) + \mu = \mu,$$ and clearly $$\operatorname{Var}[X] = \operatorname{Var}[\sigma Z] = \sigma^2 \operatorname{Var}[Z] = \sigma^2 \cdot 1 = \sigma^2.$$  Consequently, $X$ has mean $\mu$ and variance $\sigma^2$.  The density of $X$ is found by observing that $$F_X(x) = \Pr[X \le x] = \Pr[\sigma Z + \mu \le x] = \Pr\left[Z \le \frac{x - \mu}{\sigma}\right] = F_Z\left(\frac{x-\mu}{\sigma}\right),$$ consequently $$f_X(x) = \frac{d}{dx}\left[F_Z\left(\frac{x-\mu}{\sigma}\right)\right] = f_Z\left(\frac{x-\mu}{\sigma}\right) \cdot \frac{1}{\sigma}, $$ by the chain rule.  But this is precisely $$f_X(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{-(x-\mu)^2/(2\sigma^2)}.$$

A: $\mu$ and $\sigma$ are both independent defined by the distribution, so you have to input then on the distribution.
When you say $\sigma(\mu) = \sqrt{E[(X-\mu)^2]}$, you have to remember, also, that $\mu = E[X]$. Thus, in the end, both are defined by X.


text:
Q: Integration BannerviewController In project I created a project without storyboard and xib. I have multiple views and wanted a shared banner to be displayed on all views. I went through the sample code given by apple and tried to use the BannerViewController.h and .m files but I am not getting any proper output. Can u please tell me how to properly make the iAd work in my project.
From Below Link i downloaded the IAd sample code
https://developer.apple.com/library/ios/samplecode/iAdSuite/Introduction/Intro.html
I added the bannerviewcontroller.h and m files with in my project.
In my application MainViewcontroller, the NSNotificationCenter is not getting called and no banner is display.
#import "BannerViewController.h"

 - (void)viewDidLoad {
            [super viewDidLoad];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willBeginBannerViewActionNotification:) name:BannerViewActionWillBegin object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishBannerViewActionNotification:) name:BannerViewActionDidFinish object:nil];
        }

- (void)willBeginBannerViewActionNotification:(NSNotification *)notification
{
    NSLog(@"Will begin banner view action notification");
}

- (void)didFinishBannerViewActionNotification:(NSNotification *)notification
{
    NSLog(@"Did finish banner view action notification");
}

Please let me know what i missed.
Thanking you in advance!


text:
Q: Getting git server on VM I'm using Vagrant&VirtualBox to work with ubuntu machine.
Now, I want to make this machine as a server through commands in the terminal.
I am using this machine on a Windows based PC, and I want to make a git project on the Windows PC and push it to the server that sits on the Virtual machine.
I saw this guides:
http://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server
http://git-scm.com/book/en/v2/Git-on-the-Server-Getting-Git-on-a-Server
And I did all the steps but got stuck in the step of configuring the URL for the remote. As I said my remote server sits on the Ubuntu VM that I created using Vagrant.
I made the address like this:
vagrant@127.0.0.1:/opt/git/project.git
(I assume there is a problem in this address)
but when I try to push I get errors like:
fatal: 'vagrant@127.0.0.1/opt/git' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I already copied the id_rsa.pub that i generated from Windows into the .ssh library and copied it to authorized_keys.
What is the problem? (might be lots of them..)

A: I think problem is with address, you cannot access localhost from different machine. binding of repository with machine's ip/hostname should be there. Let's say your local machine and VM are on 192.168.x.y series (considering network bridge). Then you can access without any error. Or you can try GitStack
to host git server on windows machine and access it using any git client.


text:
Q: Firebase UI for Flutter for Auth Given Firebase and Flutter are both Google products I assumed the integration would be quite tight.
Whilst the Firebase API's are available in Flutter, I was surprised to see that Firebase UI isn't. It would be immensely useful to have this feature, especially given the features it supports.
There are two community plugins, both of work do not compile to iOS due to Twitter x64 compatibility issues.
Whilst a Firebase Flutter UI integration is in the works, would it be worth creating the integration with platform channels?
I think it's a huge shame we don't support this feature and it can really hinder the progress of development for apps that rely on the Firebase login features.


text:
Q: How to hide / show the content of a component that is reused by different views in ReactJS I have two views that call a particular component and this makes it difficult for me to hide / show when the component is needed. In this way, I have the following:
I tried to make a display: none to overide the styles but it is a problem. This is because the views when using the same component, the classes of the CSS are called the same and when I make the display: none, I get it not to show in "News" but in "Home" it also affects and it is not shown to me.
I tried it:
Component Section:

        {orden.map(this.renderSection)}
        <ViewAllNews mostrarCategorias={false} categoriaId={newsId} />

If I remove the title like this, I'll leave the view "Home" and "News", and that's not what I intend to do.
Next, I leave the original piece of code:
View named "Home":

**View named "News": **

Component Section:

        <Titles title={title || (category && category.title)} />
        {orden.map(this.renderSection)}
        <ViewAllNews categoriaId={newsId} />

Component ViewAllNews:
  return (
    <Link to={`/news/c/${categoryId}/`}>

View All

          <FontAwesomeIcon icon="chevron-circle-right" />

    </Link>
  );
};

As you can see, the view of "Home" and "Views" make use of the same component.
What I really need is to hide the component named  for the "News" view and also hide the "ViewAllNews" component only for the "News" view.
Thanks for your help!

A: The easiest way to hide / show react components is to use conditional rendering
Here is a basic example:
class MyComponent Extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      isVisible: false, // <-- add a value to state so we can track the components visibility
    }
  }

  show = () => {
    this.setState({ isVisible: false })
  }

  hide = () => {
    this.setState({ isVisible: true })
  }

  render(){
    if(this.state.isVisible){
      return (
       /* your component code */
      )
    }
  }
}

If you want to toggle the component from inside a parent component then you can control this with a ref:
class Parent Extends React.Component {
  constructor(props){
    this.myRef = React.createRef()
  }

  render(){
    return <MyComponent ref={this.myRef}>
  }
}

Once the component mounts, you can check if the ref has been set and call the method anywhere in your code:
if(this.myRef.current){
  this.myRef.current.show() // or .hide()
}

You can also control the components visibility via props:
function MyComponent({ isVisible }){
  if(isVisible){
    return (
      /* your component code */
    )
  }
}

Hope that helps, let me know if you have any questions!

A: a way to implement this componentWillUnmount() and componentWillMount() ,
like to this example , hope help you this.


text:
Q: Equation With Logarithm- How can we solve?
How can we solve $e^x-e=\ln x$?

I have tried to subtract exponents, but I can't find the solution. Please help. I know there is a simple method to solve this, but I can't remember it.

A: I don't think there exists a closed form solution for $x$ in terms of elementary functions. However, you can use a numerical method.
I will use the Newton-Raphson method.
The process is as follows:
$$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)} \tag{1}$$
Our function to consider is given by:
$$f(x)=e^x-e-\ln(x)$$
Evaluating its derivative gives:
$$f'(x)=e^x-\frac{1}{x}$$
Substituting into $(1)$ gives:
$$x_{n+1}=x_n-\frac{e^{x_n}-e-\ln(x_n)}{e^{x_n}-\frac{1}{x_n}}$$
Applying this iteration by setting appropriate initial values of $x_0$ (An 'educated guess' for the solution), we notice that there exists 2 solutions. As the iterations $n\to \infty$, we see that $x_n\to x$.
By setting $x_0=0.1$, we see the following:
\begin{array}{c|c}n&x_n\\\hline0&0.1\\1&0.177514\\2&0.223620\\3&0.232971\\4&0.233269\\5&0.233270\\6&0.233270\\\end{array}
After many more iterations, we obtain:
$$x \approx 0.2332697479983673$$
There is an obvious solution which is $x=1$. This solution can also be found using the same method. For example, if you set $x_0=1.5$, you will see that the iterations will converge towards $1$.
You can apply this iteration using a spreadsheet or by using more sophisticated software such as MATLAB.

A: obviously is $x=1$ one solution the other one $$x \approx 0.233269747998367328501$$)we get by a numeric method, e.g. the Newton-Raphson method.


text:
Q: Kdenlive melt-7 dependency broke package manager Any kind soul able to help out?
I tried to install a package and received an error from the terminal that
sub-process /usr/bin/dpkg returned an error code (1)

After running:
sudo dpkg --configure -a

I get the following terminal output:
dpkg: dependency problems prevent configuration of kdenlive:
 kdenlive depends on melt-7; however:
  Package melt-7 is not installed.

dpkg: error processing package kdenlive (--configure):
 dependency problems - leaving unconfigured
Processing triggers for desktop-file-utils (0.26-1ubuntu3) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu3) ...
Processing triggers for mailcap (3.70+nmu1ubuntu1) ...
Processing triggers for bamfdaemon (0.5.6+22.04.20220217-0ubuntu1) ...
Rebuilding /usr/share/applications/bamf-2.index...
Errors were encountered while processing:
 kdenlive

I've tried removing and purging Kdenlive to no avail - the package manager still seems to be broken.
(ETA: I installed Kdenlive via the PPA)
Trying sudo apt-get install -f yields this output:
sudo apt-get install -f
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libgdk-pixbuf2.0-0 liblept5 libmlt-data libopencv-calib3d4.5d libopencv-contrib4.5d libopencv-dnn4.5d
  libopencv-features2d4.5d libopencv-flann4.5d libopencv-highgui4.5d libopencv-ml4.5d
  libopencv-objdetect4.5d libopencv-video4.5d libtesseract4 melt
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  libmlt7-data melt-7
The following NEW packages will be installed:
  libmlt7-data melt-7
0 upgraded, 2 newly installed, 0 to remove and 145 not upgraded.
1 not fully installed or removed.
Need to get 0 B/121 kB of archives.
After this operation, 773 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
(Reading database ... 391414 files and directories currently installed.)
Preparing to unpack .../libmlt7-data_7.8.0-1~ubuntu22.04.1_all.deb ...
Unpacking libmlt7-data (7.8.0-1~ubuntu22.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/libmlt7-data_7.8.0-1~ubuntu22.04.1_all.deb (--unpack):
 trying to overwrite '/usr/share/mlt-7/avformat/blacklist.txt', which is also in package libmlt-data 7.4.0-1build1
Preparing to unpack .../melt-7_7.8.0-1~ubuntu22.04.1_amd64.deb ...
Unpacking melt-7 (7.8.0-1~ubuntu22.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/melt-7_7.8.0-1~ubuntu22.04.1_amd64.deb (--unpack):
 trying to overwrite '/usr/bin/melt-7', which is also in package melt 7.4.0-1build1
Errors were encountered while processing:
 /var/cache/apt/archives/libmlt7-data_7.8.0-1~ubuntu22.04.1_all.deb
 /var/cache/apt/archives/melt-7_7.8.0-1~ubuntu22.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Ubuntu version: Ubuntu 22.04.1 LTS
PPA installed from: ppa:kdenlive/kdenlive-stable
Any ideas for how to resolve this issue?

A: sudo apt remove libmlt7-data melt-7 kdenlive
sudo dkpg --configure -a
sudo apt install -f

A: To fix this issue, run the following commands.
sudo apt remove kdenlive libmlt7-data melt libmlt-data
sudo apt-get install kdenlive

Credit goes to sniff122 on Reddit.


text:
Q: Change the color of the main title without redefining \maketitle I'm looking for a way to change the color of the main title of a document without redefining the \maketitle.  A Google search only yields how to systematically change the section titles that does not include the main title.

A: Here is a solution
\documentclass{article}
\usepackage{xcolor}
\title{\textcolor{blue}{The title}}
\author{Me}

\begin{document}
\maketitle
\end{document}

Update if ams class used
\documentclass{amsart}
\usepackage{xcolor}
\colorlet{BLUE}{blue}
\title{\textcolor{blue}{The title}}
\author{Me}

\begin{document}
\maketitle
\end{document}


text:
Q: Firefox/jQuery is not reading any attribute for an img element So I am attempting to combine two image galleries, Galleria and Lightbox.  The way it is supposed to work is that Lightbox will read the href from the anchor tag and Galleria will read the src from the image tag in the following code:

I am attempting to pull the attribute value of the src out and use it as the value of the href.  Just for now, once I get this bit working I have to re-work the code.
This is how I am pulling the attribute value out
var imageSrc = image.attr('src');

Right now I have tested it in FF2,FF3 and neither of them are reading the value.  In Chrome and IE it reads the value.  What I was thinking is that the image is created in jQuery so perhaps Firefox is moving too quickly reading through and the jQuery hasn't had time to create the image yet?
Any thoughts?
Thanks,
Levi

A: Well how are you selecting image?
Try:
$('.replaced').each(function(){
   var imageSrc = $(this).attr('src');
   //alert(imageSrc) /*  for IE  */
   console.log(imageSrc);
});

A: Check the following:

*

*Did you define image correctly? How are you assigning a value to this?

*Did you ask for the value of image after the position of the DOM element representing that image?

*Did you make sure to put your scripts at the end of your body, just before the closing  tag? (If you don't, it's possible you'll wind up with a null reference and any Javascript execution will terminate.)

Chances are good that it's related to one of these three issues.

A: Are you wrapping your call in a ready event?
$(document).ready(function(){
    var imageSrc = $('img.replaced').attr('src');
});

Please note that if you have multiple images that share the class 'replaced' you need to read the src from each one of them. The above method will only work on a single image, if you want to read the attribute for multiple images use this:
$(document).ready(function(){
    var imageSrc = $('img.replaced').each(function(){
        $(this).attr('src');
    });
});


text:
Q: Simple Injector Property Injection How do you perform property injection with Simple Injector.
The with Ninject you do is as per bellow:
[Inject]
public IUnitOfWork UnitOfWork { get; set; }

How can I do the equivalent to this with Simple Injector. I tried finding a solution online but had no luck.
Why do I want to use Property Injection?
I want to use property injection to set up unit of work in my base controller so that it will create a new unit of work OnActionExecuting and commit the changes OnResultExecuted. It also means I don't have to pass in the UoW with each new controller I create through the constructor.

A: Another option is to use the RegisterInitializer method:
container.RegisterInitializer<BaseControllerType>(controller =>
{
   controller.UnitOfWork = container.GetInstance<IUnitOfWork>();
}

It keeps all configuration in your composition root and does not pollute your code base with all kinds of attributes.
Update: (as promised)
While this is a direct answer to your question I have to provide you with a better option, because the usage of a base class for this is a IMO not the correct design, for multiple reasons.

*

*Abstract classes can become real PITA classes as they tend to grow towards a god class which has all kinds of cross cutting concerns

*An abstract class, especially when used with property injection, hides the needed dependencies.

With focus on point 2. When you want to unit test a controller which inherits from the base controller, you have no way of knowing that this controller is dependent on IUnitOfWork. This you could solve by using constructor injection instead of property injection:
protected abstract class BaseController : Controller
{
    protected readonly IUnitOfWork uoW;
    protected BaseController (IUnitOfWork uoW)
    {
        this.uoW = uoW;
    }

}
public class SomeController : BaseController
{
    public SomeController(IUnitOfWork uoW) : base(uoW) { }
}

While this solves point 2, point 1 is still lurking. The main reason you're wanting this, as you say, is because you do not want to commit your changes in every Action method. Changes must just be saved by the context when the request is done. And thinking about design in this way is a good thing, because Saving changes is, or can be seen as a cross cutting concern and the way you're implementing this is more or less known as AOP.
If it's comes to AOP, especially if you're working with atomic actions in the action methods of your controllers, there is a far better, more SOLID and more flexible design possible which deals with this very nicely.
I'm referring to the Command/Handler pattern which is described in great detail here (also read this for the query part of your application).
With this patterns you don't inject a generic IUnitOfWork abstraction, but inject the specific needed ICommandHandler<TCommand> abstractions.
The action methods would fire the responsible commandhandler for this specific action. All commandhandlers can simple be decorated by a single open-generic SaveChangesCommandHandlerDecorator, 'ValidationDecorator', 'CheckPermissionsDecorator', etc...
A quick example:
public class MoveCustomerCommand
{
    public int CustomerId;
    public Address NewAddress;
}

public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
    public void Handle(MoveCustomerCommand command)
    {
        // retrieve customer from database
        // change address
    }
}

public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decoratee;
    private readonly DbContext db;

    public SaveChangesCommandHandlerDecorator(
           ICommandHandler<TCommand> decoratee, DbContext db)
    {
        this.decoratee = decoratee;
        this.db = db;
    }

    public void Handle(TCommand command)
    {
        this.decoratee.Handle(command);
        this.db.SaveChanges();
    }
}

// Register as
container.Register(typeof(ICommandHandler<>), new []{Assembly.GetExecutingAssembly() });
container.RegisterDecorator(typeof(ICommandHandler<>),
                       typeof(SaveChangesCommandHandlerDecorator<>));

// And use in controller as
public ActionResult MoveCustomer(int customerId, Address address)
{
     var command = new MoveCustomerCommand
                   { CustomerId = customerId, Address = address };
     this.commandHandler.Handle(command);

     return View(new ResultModel());
}

This keeps your controllers clean and let it do what it must do, namely be the layer between the business logic (the commandhandler implementation in this case) and the view.

A: Need to create the following:
First create the attribute class
[System.AttributeUsage(System.AttributeTargets.Property]
public class Inject : Attribute
{
}

Then create a custom property behavior
class PropertySelectionBehavior<TAttribute> : IPropertySelectionBehavior
where TAttribute : Attribute
{
    public bool SelectProperty(Type type, PropertyInfo prop)
    {
        return prop.GetCustomAttributes(typeof(TAttribute)).Any();
    }
}

Finally tell the container to use custom behavior
container.Options.PropertySelectionBehavior = new PropertySelectionBehavior<Inject>();

All that is left to do is decorate the property with the attribute
[Inject]
public IUnitOfWork UnitOfWork { get; set; }


text: Q: Are Windows programs allowed to see which other programs are running and their Taskbar Names? Are Windows programs allowed to see which other programs are running and their Taskbar Names? For example is Program X allowed to see that Word 2016 is open, running, and editing My Document.docx?


text:
Q: Unable to retrieve property value through ValueMap - CQ 5.4 I accidentally encountered a situation when trying to access the property of the resource as mentioned in this Sling Docs.
The ValueMap always returns null if the name of the property starts with a number, whereas accessing the same property via the Node API returns the value correctly.
Tried to check if the key is available in the ValueMap through #keySet() and #containsKey(). It shows all the keys, but the value corresponding to the key is null.
The following is the piece of code which i was trying to execute.
Iterator<Resource> resources = resourceResolver.findResources(query, "xpath");

while(resources.hasNext()) {
    Resource res = resources.next();
    ValueMap resProps = res.adaptTo(ValueMap.class);
    String xyz = resProps.get("2014_xyz",String.class); // returns null

    Node node = res.adaptTo(Node.class);
    if(node.hasProperty("2014_xyz")) {
        String abc = node.getProperty("2014_xyz").getString(); //returns value
    }
}

Was there any restriction that the name of the property shouldn't start with a number?
I went through the JCR repository model Section 3.2.2 to check the valid names. It says valid characters as XmlChar – InvalidChar, where XmlChar is any character matching the char production at http://www.w3.org/TR/xml/#NT-Char
Do they also consider the Common Syntactic Constructs mentioned in the document? And if so, why does JCR allow the use of such names as well as return the values correctly?
Or, has this got to do with the implementation of Sling? Am i missing something here?
P.S: I tested the same in CQ 5.6.1 and ValueMap appears to be working fine there. Not sure of CQ 5.5.

A: try
resProps.get("2014_xyz", "")

also make sure the sling version you are referencing is the one matching cq. I"m not too sure about your specific case but i've seen similar problems if the version used for compiling didn't match the version on the server.

A: If this works in CQ 5.6.1 it looks like a bug that was fixed in the meantime, there's nothing wrong with a JCR property name starting with a number.
You might want to check the actual data type of the 2014_xyz property, there might be an upstream conversion that makes it different from what you think.


text:
Q: Highlighting lines starting with #IF... using User Defined Language in Notepad++ I want to use syntax highlighting in Notepad++ for a script language that I'm working with. I set up keywords and stuff in "User Defined Language" and pretty much everything works as I'd like it to except for the following:
The script language uses #IF and #ENDIF (just like C), but I can't figure out how to configure Notepad++ so that entire lines starting with #IF or #ENDIF are highlighted (just like it is in C).
Using keywords, only the keywords #IF and #ENDIF are highlighted and not the entire line.
Operators & Delimiters doesn't work either since there is no closing delimiter for lines with these statements.
How can this be achieved?

A: It can be kludged in as a comment style.
You can do this by defining #IF and #ENDIF as two possible beginnings of a comment line.

An alternate method is to make #IF and #ENDIF delimiters.

The delimiters #IF and #ENDIF just need to have their end markers as the end of the line. The special keyword 'EOL' expands to a vector of three strings: "\r\n", "\n", and "\r"


text:
Q: Detect an  inside an area using JavaScript My problem is, I got an horizontal slider with years inside so its like a timeline, the years are fetched by a query, at this moment, the user has to scroll by the years and then click one specific year and the information on the website will filter.
Is there a way to detect the year that is in the center of that horizontal slide? Maybe with a hidden area at the center?

A: maybe you should observe the scroll event of the slider element. you have to measure after each scroll process which element is inside of the visible slider area (I suppose others are hidden by overflow: scroll from the CSS, right?)...
you should use a small delay so that the function only triggers when the scrolling was really stopped and not constantly
as it is better to show that with actually working code... checkout my jsfiddle. It is at least working in Chrome but I suppose it will work in other browsers too... when you scroll through the year list and you stop for 50ms this list item that is visible in the visible area of the slider div is logged into with console.log into the JS console... hope that helps you =)
EDIT: had a small CSS error... fixed and URL updated


text:
Q: Extend Visual Studio to wrap around an external provider I want to write a visual studio extension to build a wrapper around a technology outside of .Net. Essentially I am looking to create functionality similar to the "Service Reference" where the user will specify a resource and my extension will build a .Net wrapper around that resource.
I read this question which references the article Create custom editors and designers. The article explains editors but despite its name barely mentions designers and never really distinguishes the two.
Also, the article has a line that makes me think that writing an editor may not be what I need,

Note, however, that users will not be able to use a custom editor to
  edit standard Visual Studio projects.

So, in order to make a custom editor I have to make my own project type? What if I want my extension to be usable in any project type?
I would appreciate any direction that can be provided. I have extensive .Net experience, but am new to writing VS Extensions. I am building in visual Studio 2019 RC.


text:
Q: Access denied while creating content database from event receiver I have created one timer job which will add SharePoint content database.
When I am running timer job manually from central admin, Content database is being created successfully.
Now I have one list and and i have added "Item Added" event receiver on that list and on that event receiver I am running the same code used by the above timer job programmatically and in this context the code is throwing an "Access Denied" exception while creating content data base.(I am running code with SPsecurity.RunwithElevatedPrivileges)
I have checked following in my environment

*

*Application Pool account of my web application is added on "Farm Administrators"

*Application Pool account has "db_owner" rights on SharePoint config database

*I have added "Application pool" account in "Local Administrators" group.

Any suggestion what configuration I am missing?

A: Based on the situation you describe, you seem to be yet another victim of the remote administration security block introduced by SP2010 and still active by default in the 2013 version.
Strictly speaking, the block was developed to force security when managing SPPersistedObject.

Taken from Ms knowledgbase: "This feature explicitly blocks any modifications to the objects inheriting from SPPersistedObject in the Microsoft.SharePoint.Administration namespace and does not allow the content web applications to update the configuration database"

This roughly translates to - if you try to make an update that touches an SPPersistedObject from a web-site collection scopes you will be blocked with a generic Access Denied error even if you should be able to perform the action because you are running under farm admin account.
To confirm this is actually your case, you can try to disable the RemoteAdministratorAccessDenied property and see if this change enables your code to run.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $null
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$contentService.RemoteAdministratorAccessDenied = $false
$contentService.Update()

The above PowerShell script (taken from here for sake of simplicity) will turn of the aforementioned security setting and enable you to perform the test (remember to reset the property to the original value afterwards!).
There is a problem though: if you are indeed a victim of this security setting, then the only solution that comes to mind is disabling the security check altogether. As you may expect, this isn't exactly a desirable solution. For that reason, should the test I suggest above confirm that you are indeed seeing the result of what I describe, before considering disabling the setting I strongly suggest that you consider reworking your solution so that you won't need to perform the offending operation.

A: I got the same exception while accessing the content database in Time Job Class. then I added the below code in Time Job Class which resolved the issue.
protected override bool HasAdditionalUpdateAccess()
        {
            return true;
        }

Hope this helps...


text:
Q: How can I change gridview templatecolumn order dynamically? How can I change gridview templatecolumn order dynamically?

A: *

*Iterate through all columns of the GridView object and Store them in a collection.
List<DataControlField> columns = new List<DataControlField>();
foreach (DataControlField column in gv.Columns)
{
    columns.Add(column);
}

*Rearrange the column-objects as you want in the collection.
//Rearrange columns' collection..

*Clear all columns of the GridView object and add columns from the collection to GridView object.
 gv.Columns.Clear();
 foreach (DataControlField column in columns)
 {
     gv.Columns.Add(column);
 }

A: This does not seem to work with template fields.
After removing and re-adding the columns the template fields are empty
(the bound fields show the correct values).

A: On the RowCreated event, iterate through each column, save the first cell of each row (the template field) on a varible (oCell) and delete it from the collection, then use column.Add(oCell) to add it to the end of the collection.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e){

    GridViewRow row = e.Row;
    // Intitialize TableCell list
    List<TableCell> columns = new List<TableCell>();
    foreach (DataControlField column in GridView1.Columns)
    {
        //Get the first Cell /Column
        TableCell cell = row.Cells[0];
        // Then Remove it after
        row.Cells.Remove(cell);
        //And Add it to the List Collections
        columns.Add(cell);
    }

    // Add cells
    row.Cells.AddRange(columns.ToArray());
}

http://geekswithblogs.net/dotNETvinz/archive/2009/06/03/move--autogenerate-columns-at-leftmost-part-of-the-gridview.aspx


text:
Q: The area of a triangle determined by the bisectors. How can I calculate the area of a triangle determined by the interior bisectors? What I want to say it is represented in the following picture:

$AQ$ is the bisector of the angle $\angle BAC$, $BR$ -bisector for $\angle ABC$ and $CP$ -bisector for $\angle ACB$. Now, it must calculated the area for the triangle $PQR$ knowing that $AB=c$, $BC=a$ and $CA=b$.
I tried to use the angle bisector theorem for every bisectors but I didn't obtained anything.
Thanks :)

A: We'll derive the equation using the fact:
$$A_{PQR}=A_{ABC}-A_{PBR}-A_{RCQ}-A_{QAP}, \quad (I)$$
Using the angle bisector theorem we get:
$$BP=\frac{ac}{a+b},\quad (1)$$
$$BR=\frac{ac}{b+c}, \quad (2)$$
$$CR=\frac{ab}{b+c},\quad (3)$$
$$CQ=\frac{ab}{a+c},\quad (4)$$
$$AQ=\frac{bc}{a+c},\quad (5)$$
and
$$AP=\frac{bc}{a+b}. \quad (6)$$
Each mentioned area can be calculated using:
$$A_{PQR}=\frac{1}{2}ab\sin\gamma, \quad (7)$$
$$A_{PBR}=\frac{1}{2}BP\cdot BR\sin\beta, \quad (8)$$
$$A_{RCQ}=\frac{1}{2}CR\cdot CQ\sin\gamma, \quad (9)$$
and
$$A_{QAP}=\frac{1}{2}AQ\cdot AP\sin\alpha. \quad (10)$$
Let $R$ be the circumradius, we  know that:
$$\sin \alpha = \frac{a}{2R}, \quad (11)$$
$$\sin \beta = \frac{b}{2R}, \quad (12)$$
$$\sin \gamma = \frac{c}{2R}, \quad (13)$$
Now if we substitute all the 13 equations in equation $(I)$ we get:
$$A_{PQR}=\frac{1}{2} \cdot \frac{abc}{2R}-\frac{1}{2} \frac{a^2c^2b}{(a+b)(b+c)2R}-\frac{1}{2} \cdot \frac{a^2b^2c}{(b+c)(a+c)2R}-\frac{1}{2} \cdot \frac{b^2c^2a}{(a+b)(a+c)2R}, \Rightarrow$$
$$A_{PQR}=\frac{abc}{4R}[1-\frac{ac}{(a+b)(b+c)}-\frac{ab}{(b+c)(a+c)}-\frac{bc}{(a+b)(a+c)}], \Rightarrow$$
$$A_{PQR}=\frac{abc}{2R}[\frac{abc}{(a+b)(b+c)(a+c)}], \Rightarrow$$
$$A_{PQR}=A_{ABC}[\frac{2abc}{(a+b)(b+c)(a+c)}]$$
Using Heron's formula we are done.

A: This triangle has area $$\frac{2abc}{(a+b)(a+c)(b+c)}\cdot A,$$ where $A$ is the area of the reference triangle with sides $a,b,c$. It
may be called the "Cevian triangle" with respect to the incenter $I$ of the given reference triangle with sides $a,b,c$, or the "incentral triangle."


text:
Q: ASP.NET databound string column format in my web application I have a gridview where I have data from a database. It looks like this:

number
place

1234579
home2

1787543
home1

And i want edit fist column (number) to format - fifth character from right side bold and three characters from right side also bold.

number
place

1234579
home2

1787543
home1

How can I achieve this? I work in a visual studio, it can be set in design mode or in the source, or how. Thanks

A: You can use the TemplateField to move the data to code behind and format there as you wish - because here you have to split your number and then reformat it.
So inside the GridView add a <asp:TemplateField>
<Columns>
    <asp:TemplateField HeaderText="number" >
        <ItemTemplate>
            <%#RenderLine(Container.DataItem)%>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

and on code behind do your format..
protected string RenderLine(object oItem)
{
    var yourNumber = DataBinder.Eval(oItem, "fieldname").ToString();

     // split yourNumber, then reformat it using  etc... and return it
     // need to do some work here, here is an example
     var newNumberFormat = string.Format("{0}", yourNumber);

     return newNumberFormat;
}

A: Well it is assumed the source is some kind of database, so bottom line is you have to pull that data and format it with code.
I mean, trivial to make the WHOLE column bold. But this is a bit of whack job of a request here.
Ok, so we have say this data in a table:

And our markup would be this:
 <asp:GridView ID="GridView1" runat="server" CssClass="table"></asp:GridView>

Ok, our code to load the grid is this:
    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT SNumber, Place from tblJunk", conn))
            {
                conn.Open();
                GridView1.DataSource = cmdSQL.ExecuteReader();
                GridView1.DataBind();
            }
        }
    }

and we now have this:

Now, as a "general" rule, formatting grids/listview etc, we can try and inject message server expressions into the markup, but for setting color, highlights, and formatting it better to use the databound event of that control.
So, we could have this code:
   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string txt = e.Row.Cells[0].Text;

            // bold 5th from right
            int rPos = txt.Length - 4;
            txt = MyBold(txt, rPos, 1);

            // bol last 3 chars
            rPos = txt.Length - 2;
            txt = MyBold(txt, rPos, 3);
            e.Row.Cells[0].Text = txt;
        }
    }

And now our output is this:

So, for changing status and formatting the grid (say a color for status etc.), then the above is the general appoarch.
Of course we need some function called MyBold.
Say like this:
   string MyBold(string s,int iStart, int iEnd)
    {
        // ONE based postions - NOT 0 based!
        iStart -= 1;

        s = rLeft(s, iStart) + "" + s.Substring(iStart, iEnd) + "" +
            s.Substring(iStart + iEnd, s.Length - (iStart + iEnd));
        return s;
    }

    string rLeft(string s,int r)
    {
        return s.Substring(0, r);
    }


text:
Q: dynamically set the carousel width to the window size i am using a bootstrap carousel in asp.net. i want to set the width of the carousel so that it occupies the full width of the browser window with a fixed height if i change the width to 100% it does not work. Following is the code for carousel

i have set the width of the images and the carousel to the browser window manually but i want this to be dynamic.
following is the CSS
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
      transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
width: 1177px;
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}

and also when i scroll to the right the carousel comes on top of sidebar. how do i avoid that.

A: You have to give 100% width to all the width given inline.
I could see some 7-8 width:1177px in html code make all to width:100%
Also in css make width:100% for all the classes.
CODE:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

      Previous

      Next


text:
Q: Android Phone - Input field retaining every keypress and appending on replace Aim : Disallow numeric values on an input Field
Logic: I am trying to replace every numeric value with empty string.
But on every next keypress, the original val string is prepended to it.
For example :
---------------------------------------------------------
Key Entered          |         Value reflected in Input
---------------------------------------------------------
A                    |                A
b                    |                Ab
1                    |                Ab
c                    |                AbAbc
----------------------------------------------------------

Code :
HTML
 <input id="charText" value="" class="alpha">

Script
$('.alpha').on('keyup', function () {

    //$(this).val( $(this).val().replace(/[^A-Za-z]/g,'') );
    $val = $(this).val().replace(/[^A-Za-z]/g,'');;
    $('.alpha').val($val);
    });
});

Works for desktop. Error only in my Android mobile

A: I was able to solve the same using following script
(Ref : JavaScript keypress event not raised on Android browser)
$(window).load(function(){
    $('.alpha').on('keyup input', function (event) {

        if(event.type == 'input') {
          var bufferValue = $(this).val().replace(/[^A-Za-z]/g,'');
          $(this).val(bufferValue);
        }

    });
});


text:
Q: Is OpenCart or WordPress responding with 404 error for /blog/sitemap-misc.xml? I am using OpenCart v.1.5.6.5_rc for an e-Shop and WordPress v.4.1 for the e-Shop's blog.
I am a little bit confused on which of the two is responding with a 404 error for the blog's sitemap-misc.xml which is generated from the WordPress plugin Google XML Sitemaps (https://wordpress.org/plugins/google-sitemap-generator/).
Before using this plugin, I was using WordPress SEO by Yoast (https://wordpress.org/plugins/wordpress-seo/) to generated the sitemap xml (for the blog) and I thought that was causing the 404 error, but it wasn't!
My structure is
-admin
-blog/sitemap.xml (/blog/sitemap-misc.xml, /blog/sitemap-tax-post_tag.xml, /blog/sitemap-pt-post-2015-01.xml etc)
-catalog
-download
-image
-system
-vqmod
sitemap.xml (OpenCart: Extensions -> Product Feeds) - works fine

What confuses me more is that the /blog/sitemap.xml works, but the analysis of the /blog/sitemap.xml
-blog/sitemap.xml
      sitemap-misc.xml
      sitemap-tax-post_tag.xml
      sitemap-pt-post-2015-01.xml

fails with a General HTTP error: 404 not found!
Actually, if I use the full path on my browser http://www.example.com/blog/sitemap-misc.xml, OpenCart respondes with a 404 error.
Any help is appreciated.
Thank you!

A: My problem was not caused either by OpenCart or WordPress (core).
The W3 Total Cache (https://wordpress.org/plugins/w3-total-cache/) WordPress plugin that I am using was causing the 404 errors!
I had checked the option in Performance -> Browser Cache
Do not process 404 errors for static objects with WordPress.
Reduce server load by allowing the web server to handle 404 (not found) errors for static files (images etc).
If enabled - you may get 404 File Not Found response for some files generated on-the-fly by WordPress plugins. You may add those file URIs to 404 error exception list below to avoid that.
# BEGIN W3TC Skip 404 error handling by WordPress for static files
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !(robots\.txt|sitemap(_index)?\.xml(\.gz)?|[a-z0-9_\-]+-sitemap([0-9]+)?\.xml(\.gz)?)
    RewriteCond %{REQUEST_FILENAME} \.(css|htc|less|js|js2|js3|js4|html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip)$ [NC]
    RewriteRule .* - [L]
</IfModule>
# END W3TC Skip 404 error handling by WordPress for static files

So, when I unchecked that option my problem was resolved!
I guess I could just remove this line
RewriteCond %{REQUEST_URI} !(robots\.txt|sitemap(_index)?\.xml(\.gz)?|[a-z0-9_\-]+-sitemap([0-9]+)?\.xml(\.gz)?)
from the /blog/.htaccess file to reduce server load.


text:
Q: Explode list into columns in a dataframe I have a dataframe with two columns : ID and Demographic_distribution.
ID is just a number (ex:123456).
demographic_impression has a list for each ID. here's an example of what you get in the demographic_distribution column for one ID :
ID : 123456
Demographic_distribution : [{percentage: 0.000952, age: 25-34, gender: unknown}, {percentage: 0.093621, age: 55-64, gender: male}, {percentage: 0.002856, age: 35-44, gender: unknown}, {percentage: 0.031736, age: 18-24, gender: female}, {percentage: 0.085052, age: 25-34, gender: male}, {percentage: 0.019994, age: 18-24, gender: male}, {percentage: 0.085687, age: 35-44, gender: male}, {percentage: 0.133608, age: 55-64, gender: female}, {percentage: 0.112345, age: 65+, gender: female}, {percentage: 0.000317, age: 18-24, gender: unknown}, {percentage: 0.095208, age: 45-54, gender: female}, {percentage: 0.067598, age: 65+, gender: male}, {percentage: 0.086004, age: 45-54, gender: male}, {percentage: 0.075849, age: 25-34, gender: female}, {percentage: 0.098699, age: 35-44, gender: female}, {percentage: 0.003174, age: 65+, gender: unknown}, {percentage: 0.003174, age: 45-54, gender: unknown}, {percentage: 0.004126, age: 55-64, gender: unknown}]
You can see that there are 5 age groups, 3 genders and many percentages. I would like to split the demographic column into three different columns for each parameters. Let's not forget that these informations are liked to an ID in each row, otherwise it doesn't make sense.
I tried .explode, but it didn't work.
Any idea how to do this ?

A: json.normalize is what you are after.
pandas docs

A: I did something like this give a try once.
import json
import os
import pandas as pd

#if Demographic Distribution is more then you can iterate through loop

Demographic_distribution = [
    {"percentage": 0.000952, "age": "25-34", "gender": "unknown"},
    {"percentage": 0.093621, "age": "55-64", "gender": "male"},
    {"percentage": 0.002856, "age": "35-44", "gender": "unknown"},
    {"percentage": 0.031736, "age": "18-24", "gender": "female"},
    {"percentage": 0.085052, "age": "25-34", "gender": "male"},
    {"percentage": 0.019994, "age": "18-24", "gender": "male"},
    {"percentage": 0.085687, "age": "35-44", "gender": "male"}]

df = pd.DataFrame.from_dict(Demographic_distribution)
df['ID'] = 123456

df.to_csv("D:\\Path\\Output.csv",index=False)

Output

A: Try:
df = df.explode("Demographic_distribution")

df = pd.concat(
    [df, df.pop("Demographic_distribution").apply(pd.Series)], axis=1
)
print(df)

Prints:
       ID  percentage    age   gender
0  123456    0.000952  25-34  unknown
0  123456    0.093621  55-64     male
0  123456    0.002856  35-44  unknown
0  123456    0.031736  18-24   female
0  123456    0.085052  25-34     male
0  123456    0.019994  18-24     male
0  123456    0.085687  35-44     male
0  123456    0.133608  55-64   female
0  123456    0.112345    65+   female
0  123456    0.000317  18-24  unknown
0  123456    0.095208  45-54   female
0  123456    0.067598    65+     male
0  123456    0.086004  45-54     male
0  123456    0.075849  25-34   female
0  123456    0.098699  35-44   female
0  123456    0.003174    65+  unknown
0  123456    0.003174  45-54  unknown
0  123456    0.004126  55-64  unknown

df used:
       ID                                                                                Demographic_distribution
0  123456  [{'percentage': 0.000952, 'age': '25-34', 'gender': 'unknown'}, {'percentage': 0.093621, 'age': '55-64', 'gender': 'male'}, {'percentage': 0.002856, 'age': '35-44', 'gender': 'unknown'}, {'percentage': 0.031736, 'age': '18-24', 'gender': 'female'}, {'percentage': 0.085052, 'age': '25-34', 'gender': 'male'}, {'percentage': 0.019994, 'age': '18-24', 'gender': 'male'}, {'percentage': 0.085687, 'age': '35-44', 'gender': 'male'}, {'percentage': 0.133608, 'age': '55-64', 'gender': 'female'}, {'percentage': 0.112345, 'age': '65+', 'gender': 'female'}, {'percentage': 0.000317, 'age': '18-24', 'gender': 'unknown'}, {'percentage': 0.095208, 'age': '45-54', 'gender': 'female'}, {'percentage': 0.067598, 'age': '65+', 'gender': 'male'}, {'percentage': 0.086004, 'age': '45-54', 'gender': 'male'}, {'percentage': 0.075849, 'age': '25-34', 'gender': 'female'}, {'percentage': 0.098699, 'age': '35-44', 'gender': 'female'}, {'percentage': 0.003174, 'age': '65+', 'gender': 'unknown'}, {'percentage': 0.003174, 'age': '45-54', 'gender': 'unknown'}, {'percentage': 0.004126, 'age': '55-64', 'gender': 'unknown'}]


text:
Q: Finding covariance using $E[X]$ and $E[Y]$ I have a table

where I have found $E[X] = 2.6$ and $E[Y] = 2.44$.
\begin{align*}
E[X] &= 2 \times 0.4 + 3 \times 0.6 = 2.6 \\
E[Y] &= 2 \times 0.56 + 3 \times 0.44 = 2.44
\end{align*}
I have tried:
$$ Cov[X,Y] = E[XY] - E[X] E[Y]$$
How do I solve for covariance between $X$ and $Y$?

A: Using the formula you shared
$$Cov[X,Y] = E[X*Y] - E[X] * E[Y]$$
you have computed both $E(X),E(Y)$ . Now to compute $E(XY)$ treat $XY$ as a single random variable, ie the outcomes are $2\times 3=6$, $2\times 2=4 $ and $3\times 3 =9$. Get their respective probabilies from the table and compute the average as you did.


text:
Q: Update Username (User_Login) on Email Change (WooCommerce) A number of questions have been raised on StackOverflow in regards to using email address as username when registering via My Account. I have the working code included below.
$this->loader->add_filter('pre_user_login', $plugin_public, 'audp_wc_register_email_as_username' );

public function audp_wc_register_email_as_username( $user_login ) {

    if ( isset ( $_POST['email'] ) ) {

        $user_login = $_POST['email'];

    }

    return $user_login;

}

I've updated my own question with the following code to update the user_login details.
$this->loader->add_action( 'woocommerce_save_account_details', $plugin_public, 'audp_wc_update_email_and_username', 20, 1 );

public function audp_wc_update_email_and_username() {

    if ( isset( $_POST['account_email'] ) ) {

        global $wpdb;

        $user_id = get_current_user_id();
        $new_login = $_POST['account_email'];

        // Update user user_login
        $wpdb -> update( $wpdb -> users,
            array( 'user_login' => $new_login, 'user_nicename' => $new_nicename ),
            array( 'ID' => $user_id )
        );
    }
    // Update nickname
    update_user_meta( $user_id, 'nickname', $new_login );
}

A: I've updated the question to include the full code. Because we are dealing with user_login we cannot use wp_update_user(), I have used the class description above, but the below code is standard (non-class) functions.
add_action( 'woocommerce_save_account_details', 'audp_wc_update_email_and_username', 20, 1 );
function audp_wc_update_email_and_username() {

if ( isset( $_POST['account_email'] ) ) {

    global $wpdb;

    $user_id = get_current_user_id();
    $new_login = $_POST['account_email'];

        // Update user user_login
        $wpdb -> update( $wpdb -> users,
            array( 'user_login' => $new_login, 'user_nicename' => $new_nicename ),
            array( 'ID' => $user_id )
        );

    // Update nickname
    update_user_meta( $user_id, 'nickname', $new_login );
}


text:
Q: Error #1442 MySQL - making a trigger I have a problem to making a trigger. I want make a 'copy' of field 'nome' in 'nome1' whenever I make an insert of a record (casello). I receive this error:

#1442 - Can't update table 'casello' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

How Can i fix it?
this is the structure of my table:
    --
    -- Struttura della tabella `casello`
    --

   CREATE TABLE IF NOT EXISTS `casello` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `posizione` double NOT NULL,
  `nome` varchar(100) NOT NULL,
  `nome1` varchar(100) DEFAULT NULL,
  `modalita_pagamento` varchar(255) NOT NULL,
  `servizio_assistenza` tinyint(1) DEFAULT NULL,
  `l_nome` varchar(100) DEFAULT NULL,
  `nome_autostrada` varchar(4) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `l_nome` (`l_nome`),
  KEY `nome_autostrada` (`nome_autostrada`),
  KEY `nome` (`nome`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;

  --
  -- Dump dei dati per la tabella `casello`
  --

  INSERT INTO `casello` (`id`, `posizione`, `nome`, `nome1`, `modalita_pagamento`,
          `servizio_assistenza`, `l_nome`, `nome_autostrada`) VALUES
  (3, 35, 'napoli nord', NULL, 'contanti, carte, telepass', 1, 'caserta', 'a1'),
  (4, 15, 'napoli sud', NULL, 'contanti, carte, telepass', 1, 'napoli', 'a1'),
  (5, 310, 'roma nord', NULL, 'contanti, carte, telepass', 1, NULL, 'a1'),
  (6, 280, 'roma sud', NULL, 'contanti, carte, telepass', 1, NULL, 'a1'),
  (11, 25, 'palma campania', 'NULL', 'contanti, carte, telepass', 1, NULL, 'a30'),
  (12, 30, 'sarno', 'NULL', 'contanti, carte, telepass', NULL, NULL, 'a30'),
  (13, 35, 'nocera', NULL, 'contanti, carte, telepass', 1, NULL, 'a30');

  --
  -- Triggers `casello`
  --
  DROP TRIGGER IF EXISTS `cp nome nome1`;
  DELIMITER //
  CREATE TRIGGER `cp nome nome1` AFTER INSERT ON `casello`
  FOR EACH ROW UPDATE casello
  set casello.nome1=casello.nome
  //
  DELIMITER ;

P.S. Of course if I make this:
UPDATE casello
SET casello.nome1=casello.nome

as a simple query it will works and it copies data.

A: You can achieve it like this:
DROP TRIGGER IF EXISTS `cp nome nome1`;
DELIMITER //
CREATE TRIGGER `cp nome nome1` BEFORE INSERT ON `casello`
FOR EACH ROW
SET NEW.nome1=NEW.nome
//
DELIMITER ;

You don't make an UPDATE after the rows are inserted, you change them BEFORE they are INSERTed.
Note, NEW is a keyword here, not a table name.


text:
Q: spring data jdbc. Can't add custom converter for enum I want to have enum as a field for my entity.
My application is look like:
Spring boot version
plugins {
        id 'org.springframework.boot' version '2.6.2' apply false

repository:
@Repository
public interface MyEntityRepository extends PagingAndSortingRepository<MyEntity, UUID> {
 ...

entity:
@Table("my_entity")
public class MyEntity{
   ...
   private FileType fileType;
  // get + set
}

enum declaration:
public enum FileType {
    TYPE_1(1),
    TYPE_2(2);

    int databaseId;

    public static FileType byDatabaseId(Integer databaseId){
        return Arrays.stream(values()).findFirst().orElse(null);
    }
    FileType(int databaseId) {
        this.databaseId = databaseId;
    }

    public int getDatabaseId() {
        return databaseId;
    }
}

My attempt:
I've found following answer and try to follow it : https://stackoverflow.com/a/53296199/2674303
So I've added bean
@Bean
public JdbcCustomConversions jdbcCustomConversions() {
    return new JdbcCustomConversions(asList(new DatabaseIdToFileTypeConverter(), new FileTypeToDatabaseIdConverter()));
}

converters:
@WritingConverter
public class FileTypeToDatabaseIdConverter implements Converter<FileType, Integer> {
    @Override
    public Integer convert(FileType source) {
        return source.getDatabaseId();
    }
}

@ReadingConverter
public class DatabaseIdToFileTypeConverter implements Converter<Integer, FileType> {
    @Override
    public FileType convert(Integer databaseId) {
        return FileType.byDatabaseId(databaseId);
    }
}

But I see error:

The bean 'jdbcCustomConversions', defined in class path resource
[org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration$SpringBootJdbcConfiguration.class],
could not be registered. A bean with that name has already been
defined in my.pack.Main and overriding is disabled.

I've tried to rename method jdbcCustomConversions() to myJdbcCustomConversions(). It helped to avoid error above but converter is not invoked during entity persistence and I see another error that application tries to save String but database type is bigint.
20:39:10.689  DEBUG  [main] o.s.jdbc.core.StatementCreatorUtils: JDBC getParameterType call failed - using fallback method instead: org.postgresql.util.PSQLException: ERROR: column "file_type" is of type bigint but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 174

I also tried to use the latest(currently) version of spring boot:
id 'org.springframework.boot' version '2.6.2' apply false

But it didn't help.
What have I missed ?
How can I map enum to integer column properly ?
P.S.
I use following code for testing:
@SpringBootApplication
@EnableJdbcAuditing
@EnableScheduling
public class Main {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Main.class, args);
        MyEntityRepositoryrepository = applicationContext.getBean(MyEntityRepository.class);
        MyEntity entity =  new MyEntity();
        ...
        entity.setFileType(FileType.TYPE_2);
        repository.save(entity);
    }

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration()
                .setMatchingStrategy(MatchingStrategies.STRICT)
                .setFieldMatchingEnabled(true)
                .setSkipNullEnabled(true)
                .setFieldAccessLevel(PRIVATE);
        return mapper;
    }

    @Bean
    public AbstractJdbcConfiguration jdbcConfiguration() {
        return new MySpringBootJdbcConfiguration();
    }
    @Configuration
    static class MySpringBootJdbcConfiguration extends AbstractJdbcConfiguration {
        @Override
        protected List<?> userConverters() {
            return asList(new DatabaseIdToFileTypeConverter(), new FileTypeToDatabaseIdConverter());
        }
    }
}

UPDATE
My code is:
@SpringBootApplication
@EnableJdbcAuditing
@EnableScheduling
public class Main {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Main.class, args);
        MyEntityRepositoryrepository = applicationContext.getBean(MyEntityRepository.class);
        MyEntity entity =  new MyEntity();
        ...
        entity.setFileType(FileType.TYPE_2);
        repository.save(entity);
    }

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration()
                .setMatchingStrategy(MatchingStrategies.STRICT)
                .setFieldMatchingEnabled(true)
                .setSkipNullEnabled(true)
                .setFieldAccessLevel(PRIVATE);
        return mapper;
    }

    @Bean
    public AbstractJdbcConfiguration jdbcConfiguration() {
        return new MySpringBootJdbcConfiguration();
    }

    @Configuration
    static class MySpringBootJdbcConfiguration extends AbstractJdbcConfiguration {
        @Override
        protected List<?> userConverters() {
            return asList(new DatabaseIdToFileTypeConverter(), new FileTypeToDatabaseIdConverter());
        }

        @Bean
        public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext,
                                           NamedParameterJdbcOperations operations,
                                           @Lazy RelationResolver relationResolver,
                                           JdbcCustomConversions conversions,
                                           Dialect dialect) {

            JdbcArrayColumns arrayColumns = dialect instanceof JdbcDialect ? ((JdbcDialect) dialect).getArraySupport()
                    : JdbcArrayColumns.DefaultSupport.INSTANCE;
            DefaultJdbcTypeFactory jdbcTypeFactory = new DefaultJdbcTypeFactory(operations.getJdbcOperations(),
                    arrayColumns);

            return new MyJdbcConverter(
                    mappingContext,
                    relationResolver,
                    conversions,
                    jdbcTypeFactory,
                    dialect.getIdentifierProcessing()
            );
        }
    }

    static class MyJdbcConverter extends BasicJdbcConverter {
        MyJdbcConverter(
                MappingContext<? extends RelationalPersistentEntity<?>, ? extends RelationalPersistentProperty> context,
                RelationResolver relationResolver,
                CustomConversions conversions,
                JdbcTypeFactory typeFactory,
                IdentifierProcessing identifierProcessing) {
            super(context, relationResolver, conversions, typeFactory, identifierProcessing);
        }

        @Override
        public int getSqlType(RelationalPersistentProperty property) {
            if (FileType.class.equals(property.getActualType())) {
                return Types.BIGINT;
            } else {
                return super.getSqlType(property);
            }
        }

        @Override
        public Class<?> getColumnType(RelationalPersistentProperty property) {
            if (FileType.class.equals(property.getActualType())) {
                return Long.class;
            } else {
                return super.getColumnType(property);
            }
        }
    }
}

But I experience error:
Caused by: org.postgresql.util.PSQLException: Cannot convert an instance of java.lang.String to type long
    at org.postgresql.jdbc.PgPreparedStatement.cannotCastException(PgPreparedStatement.java:925)
    at org.postgresql.jdbc.PgPreparedStatement.castToLong(PgPreparedStatement.java:810)
    at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:561)
    at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:931)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setObject(HikariProxyPreparedStatement.java)
    at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:414)
    at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:231)
    at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:146)
    at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:283)
    at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.createPreparedStatement(PreparedStatementCreatorFactory.java:241)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
    ... 50 more
Caused by: java.lang.NumberFormatException: For input string: "TYPE_2"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:589)
    at java.lang.Long.parseLong(Long.java:631)
    at org.postgresql.jdbc.PgPreparedStatement.castToLong(PgPreparedStatement.java:792)
    ... 59 more

A: Try the following instead:
@Bean
public AbstractJdbcConfiguration jdbcConfiguration() {
    return new MySpringBootJdbcConfiguration();
}

@Configuration
static class MySpringBootJdbcConfiguration extends AbstractJdbcConfiguration {
    @Override
    protected List<?> userConverters() {
        return List.of(new DatabaseIdToFileTypeConverter(), new FileTypeToDatabaseIdConverter());
    }
}

Explanation:
Spring complains that JdbcCustomConversions in auto-configuration class is already defined (by your bean) and you don't have bean overriding enabled.
JdbcRepositoriesAutoConfiguration has changed a few times, in Spring 2.6.2 it has:
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(AbstractJdbcConfiguration.class)
static class SpringBootJdbcConfiguration extends AbstractJdbcConfiguration {

}

In turn, AbstractJdbcConfiguration has:
@Bean
public JdbcCustomConversions jdbcCustomConversions() {

    try {

        Dialect dialect = applicationContext.getBean(Dialect.class);
        SimpleTypeHolder simpleTypeHolder = dialect.simpleTypes().isEmpty() ? JdbcSimpleTypes.HOLDER
                : new SimpleTypeHolder(dialect.simpleTypes(), JdbcSimpleTypes.HOLDER);

        return new JdbcCustomConversions(
                CustomConversions.StoreConversions.of(simpleTypeHolder, storeConverters(dialect)), userConverters());

    } catch (NoSuchBeanDefinitionException exception) {

        LOG.warn("No dialect found. CustomConversions will be configured without dialect specific conversions.");

        return new JdbcCustomConversions();
    }
}

As you can see, JdbcCustomConversions is not conditional in any way, so defining your own caused a conflict. Fortunately, it provides an extension point userConverters() which can be overriden to provide your own converters.
Update
As discussed in comments:

*

*FileType.byDatabaseId is broken - it ignores its input param

*as the column type in db is BIGINT, your converters must convert from Long, not from Integer, this addresses read queries

*for writes, there is an open bug https://github.com/spring-projects/spring-data-jdbc/issues/629 There is a hardcoded assumption that Enums are converted to Strings, and only Enum -> String converters are checked.
As we want to convert to Long, we need to make amendments to BasicJdbcConverter by subclassing it and registering subclassed converter with as a @Bean.
You need to override two methods

*

*public int getSqlType(RelationalPersistentProperty property)

*public Class<?> getColumnType(RelationalPersistentProperty property)
I hardcoded the Enum type and corresponding column types, but you may want to get more fancy with that.
@Bean
public AbstractJdbcConfiguration jdbcConfiguration() {
    return new MySpringBootJdbcConfiguration();
}

@Configuration
static class MySpringBootJdbcConfiguration extends AbstractJdbcConfiguration {
    @Override
    protected List<?> userConverters() {
        return List.of(new DatabaseIdToFileTypeConverter(), new FileTypeToDatabaseIdConverter());
    }

    @Bean
    public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext,
                                       NamedParameterJdbcOperations operations,
                                       @Lazy RelationResolver relationResolver,
                                       JdbcCustomConversions conversions,
                                       Dialect dialect) {

        JdbcArrayColumns arrayColumns = dialect instanceof JdbcDialect ? ((JdbcDialect) dialect).getArraySupport()
                : JdbcArrayColumns.DefaultSupport.INSTANCE;
        DefaultJdbcTypeFactory jdbcTypeFactory = new DefaultJdbcTypeFactory(operations.getJdbcOperations(),
                arrayColumns);

        return new MyJdbcConverter(
                mappingContext,
                relationResolver,
                conversions,
                jdbcTypeFactory,
                dialect.getIdentifierProcessing()
        );
    }
}

static class MyJdbcConverter extends BasicJdbcConverter {
    MyJdbcConverter(
            MappingContext<? extends RelationalPersistentEntity<?>, ? extends RelationalPersistentProperty> context,
            RelationResolver relationResolver,
            CustomConversions conversions,
            JdbcTypeFactory typeFactory,
            IdentifierProcessing identifierProcessing) {
        super(context, relationResolver, conversions, typeFactory, identifierProcessing);
    }

    @Override
    public int getSqlType(RelationalPersistentProperty property) {
        if (FileType.class.equals(property.getActualType())) {
            return Types.BIGINT;
        } else {
            return super.getSqlType(property);
        }
    }

    @Override
    public Class<?> getColumnType(RelationalPersistentProperty property) {
        if (FileType.class.equals(property.getActualType())) {
            return Long.class;
        } else {
            return super.getColumnType(property);
        }
    }
}