text:
Q: Speech to Text: Piping microphone stream to Watson STT with NodeJS I am currently trying to send a microphone stream to Watson STT service but for some reason, the Watson service is not receiving the stream (I'm guessing) so I get the error "Error: No speech detected for 30s".
Note that I have streamed a .wav file to Watson and I have also tested piping micInputStream to my local files so I know both are at least set up correctly. I am fairly new to NodeJS / javascript so I'm hoping the error might be obvious.
const fs = require('fs');
const mic = require('mic');
var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1');

var speechToText = new SpeechToTextV1({
  iam_apikey: '{key_here}',
  url: 'https://stream.watsonplatform.net/speech-to-text/api'
});

var params = {
  content_type: 'audio/l16; rate=44100; channels=2',
  interim_results: true
};

const micParams = {
    rate: 44100,
    channels: 2,
    debug: false,
    exitOnSilence: 6
  }
  const micInstance = mic(micParams);
  const micInputStream = micInstance.getAudioStream();

  micInstance.start();
  console.log('Watson is listening, you may speak now.');

// Create the stream.
var recognizeStream = speechToText.recognizeUsingWebSocket(params);

// Pipe in the audio.
var textStream = micInputStream.pipe(recognizeStream).setEncoding('utf8');

textStream.on('data', user_speech_text => console.log('Watson hears:', user_speech_text));
textStream.on('error', e => console.log(`error: ${e}`));
textStream.on('close', e => console.log(`close: ${e}`));

A: Conclusion: In the end, I am not entirely sure what was wrong with the code. I'm guessing it had something to do with the mic package. I ended up scrapping the package and using "Node-audiorecorder" instead for my audio stream https://www.npmjs.com/package/node-audiorecorder
Note: This module requires you to install SoX and it must be available in your $PATH. http://sox.sourceforge.net/
Updated Code: For anyone wondering what my final code looks like here you go. Also a big shoutout to NikolayShmyrev for trying to help me with my code!
Sorry for the heavy comments but for new projects I like to make sure I know what every line is doing.
    // Import module.
    var AudioRecorder = require('node-audiorecorder');
    var fs = require('fs');
    var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1');

    /******************************************************************************
    * Configuring STT
    *******************************************************************************/
    var speechToText = new SpeechToTextV1({
        iam_apikey: '{your watson key here}',
        url: 'https://stream.watsonplatform.net/speech-to-text/api'
    });

    var recognizeStream = speechToText.recognizeUsingWebSocket({
        content_type: 'audio/wav',
        interim_results: true
      });

    /******************************************************************************
    * Configuring the Recording
    *******************************************************************************/
    // Options is an optional parameter for the constructor call.
    // If an option is not given the default value, as seen below, will be used.
    const options = {
        program: 'rec',     // Which program to use, either `arecord`, `rec`, or `sox`.
        device: null,       // Recording device to use.

        bits: 16,           // Sample size. (only for `rec` and `sox`)
        channels: 2,        // Channel count.
        encoding: 'signed-integer',  // Encoding type. (only for `rec` and `sox`)
        rate: 48000,        // Sample rate.
        type: 'wav',        // Format type.

        // Following options only available when using `rec` or `sox`.
        silence: 6,         // Duration of silence in seconds before it stops recording.
        keepSilence: true   // Keep the silence in the recording.
      };

    const logger = console;

    /******************************************************************************
    * Create Streams
    *******************************************************************************/

    // Create an instance.
    let audioRecorder = new AudioRecorder(options, logger);

    //create timeout (so after 10 seconds it stops feel free to remove this)
    setTimeout(function() {
        audioRecorder.stop();
      }, 10000);

    // This line is for saving the file locally as well (Strongly encouraged for testing)
    const fileStream = fs.createWriteStream("test.wav", { encoding: 'binary' });

    // Start stream to Watson STT Remove .pipe(process.stdout) if you dont want translation printed to console
    audioRecorder.start().stream().pipe(recognizeStream).pipe(process.stdout);

    //Create another stream to save locally
    audioRecorder.stream().pipe(fileStream);

    //Finally pipe translation to transcription file
    recognizeStream.pipe(fs.createWriteStream('./transcription.txt'));


text:
Q: What is equivalent of $("select") without jQuery for selecting all dropdown? Maybe I did not look for well but I cannot find vanilla javascript way for selecting all dropdown in dom.
In jQuery I could use
var allDropdowns = $("select") ;

Do you know equivalent in pure javascript?

A: For the best "similar" experience I would suggest using document.querySelectorAll if your browser compat levels allow it.

console.log(document.querySelectorAll('select'));
<select id="a"><option>1</option></select>
<select id="b"><option>1</option></select>

For IE8 you should be careful, and IE7- you'd need a polyfill. For just about all other scenarios you should be fine.

A: var allDropdowns = document.getElementsByTagName("select");

A: document.querySelector('select')

if it's more than one:
document.querySelectorAll('select')

redpajama_set_name: RedPajamaStackExchange


text:
Q: LINQ - to Entities doesn't recognize the method system.string ToString() exception I've got the above ring exception in my code. What I try is to use where clause with a list variable and that's why I use Contains method but I keep getting the error and I can't understand what I do wrong
List<string> TouristID = (List<string>)Session["TouristID"];
    List<Tourist> customerInterests = (from tourist in db2.Tourist
                             where (TouristID.Contains(tourist.Tourist_ID.ToString()))
                             select tourist).ToList();

foreach (var customer in customerInterests)
{
    String strName_kir = customer.Name_kir;
    String Lastname_kir = customer.Midname_kir;
}

A: you cannot use .ToString() inside a LinqToSql expression because it will try to translate it to SQL

A: You cannot use ToString or any other methods that cannot be translated to SQL.
You should be able to do the following:
List<string> TouristID = (List<string>)Session["TouristID"];

//Get them as integers
var touristIds = TouristID.Select(x => int.Parse(x));

List<Tourist> customerInterests = (from tourist in db2.Tourist
                         where (touristIds.Contains(tourist.Tourist_ID))
                         select tourist).ToList();

A: The ToString() method is not evaluated by LinQ to Entities, because it cannot be translated to SQL.
Try to change the type of your list to the destination type or parse them into a new List.


text:
Q: Transaction log backup impact on CPU I had a serious CPU bottleneck 24/24 (it reaches 100% very often) for some weeks. The application has a pure aggressive OLTP (a thousand of query that retrieves often 1 row based on several joins).
This week I decided to begin a backup of the transaction log file, and hopefully the CPU bottleneck disappears.
Is there a direct relation between the transaction log file (size,backup or whatever) a the CPU bottleneck?

A: Backups of the transaction log will not help your CPU bottleneck.

*

*How many deadlocks per hour or day do you have?

*What is you CXPACKET wait value?

*How much blocking do you have?

I am not saying to stop your transaction log backups, I am saying that this won't help the CPU bottleneck.


text:
Q: How to take a Packard Bell Maestro LCD Monitor apart? Does anybody know how to take a Packard Bell Maestro LCD Monitor apart? I need to separate the layers of the screen in order to remove a fly which is stuck inside it. There are no screws on the back which makes me even wonder if it is even possible to open it up. Any help would be much appreciated.
-Alex

A: With the information i have, I'd guess your monitor is held together by clips between the bezel and back. Taking apart your monitor WILL void your warranty - and its not easy to do cleanly without practice. With the BenQ monitors i've taken apart in the past, there was an obvious slot to take it apart in the middle bottom of the frame.Make sure that there's no screws, especially under labels - if there are any undo them.
When i did it, i used a small flathead screwdriver, and a set of sharpened dowels (acting as wedges to keep the pryed apart parts apart). Start at one point, pry, and wedge, and work your way around the edge of the area between the bezel and back of the case. If it won't come apart, check for non obvious screws. You may prefer to use a set of spudgers (ifixit and others have them) - they are pretty cheap and probably worth it if you wanted to avoid cosmetic damage.


text:
Q: how to call another visualforce page from an apex command button I have an Apex command button in my Visual Force page. Using that button I want to call another visual force page, which in turn should call action function written in the controller.
Please advise.

A: Put the below code in the controller action method that is being called on click of command button

PageReference pr = new PageReference('/apex/yourVFPageName');
pr.getParameters().put('key','value');
pr.setRedirect(true); // If you want a redirect. Do not set anything if you want a forward.
return pr;

Edit:
In the constructor of the 'yourVFPageName' page controller you can call any method.
As @Vigneshwaran G has mentioned:
use action attribute in page to call that method. Otherwise if the method being called from constructor contains any DML statements it will throw error.

A: visual force page code:
 <apex:commandButton value="button" action="{!redirect}"/>

in the controller define this function:
public PageReference redirect()
{
   PageReference pr = new PageReference('/apex/yourVFPageName');
   return pr;
}

A: visual force code:
<apex:commandButton value="redirect" action="{!redirect}"/>

controller:
public PageReference redirect() {
    return Page.existingPageName;
}

Advantage of declaring this way is:

PageReference for a Visualforce page that has already been
  saved in your organization. By referring to a page in this way, the
  platform recognizes that this controller or controller extension is
  dependent on the existence of the specified page and will prevent the
  page from being deleted while the controller or extension exists.

PageReference Class


text:
Q: Transform Map using Guava I have a Group object which has list of elements like below.
class Group {
    List<E> elements;
    public List<E> getElements() { return elements; }
}

I have Map object represented as below.
Map<Group, Double> groups = with some values....

I have a another Map as below.
Map<Element, Double> elementVal = with some values....

My Final map should be a
Map<Element, Double> = with some values

where value is multiplication of element's group value (groups map) * element's value (elementVal map).
I am looking for Map transformation preferably using Guava or any other cleaner way to this rather than exploding the maps.
thanks.

A: So...
version with neasted loops

    @Test
    public void multiplyMaps() {
        Element e1 = new Element(1.);
        Element e2 = new Element(2.);
        Element e3 = new Element(3.);
        Element e4 = new Element(4.);

        Map elementVal = new HashMap();
        elementVal.put(e1, e1.d);
        elementVal.put(e2, e2.d);
        elementVal.put(e3, e3.d);
        elementVal.put(e4, e4.d);

        Group g12 = new Group(Lists.newArrayList(e1, e2));
        Group g23 = new Group(Lists.newArrayList(e2, e3));
        Group g34 = new Group(Lists.newArrayList(e3, e4));

        Map groups = new HashMap();
        groups.put(g12, e1.d + e2.d);
        groups.put(g23, e2.d + e3.d);
        groups.put(g34, e3.d + e4.d);

        for (final Map.Entry groupEntry : groups.entrySet()) {
            for (Map.Entry elementValEntry : elementVal.entrySet()) {
                System.out.println(groupEntry.getValue() + "*" + elementValEntry.getValue());
            }
        }
    }

Then we apply little guava for inner loop;)

@Test
public void multiplyMaps2() {
    Element e1 = new Element(1.);
    Element e2 = new Element(2.);
    Element e3 = new Element(3.);
    Element e4 = new Element(4.);

    Map elementVal = new HashMap();
    elementVal.put(e1, e1.d);
    elementVal.put(e2, e2.d);
    elementVal.put(e3, e3.d);
    elementVal.put(e4, e4.d);

    Group g12 = new Group(Lists.newArrayList(e1, e2));
    Group g23 = new Group(Lists.newArrayList(e2, e3));
    Group g34 = new Group(Lists.newArrayList(e3, e4));

    Map groups = new HashMap();
    groups.put(g12, e1.d + e2.d);
    groups.put(g23, e2.d + e3.d);
    groups.put(g34, e3.d + e4.d);

    for (final Map.Entry groupEntry : groups.entrySet()) {

        Collection transform = Collections2.transform(elementVal.entrySet(), new Function, Object>() {
            @Nullable
            @Override
            public String apply(@Nullable Map.Entry elementValEntry) {
                return groupEntry.getValue() + "*" + elementValEntry.getValue();
            }
        });
        System.out.println(transform);
    }
}

And finally convert outside loop plus use FluentIterable

    @Test
    public void multiplyMaps3() {
        Element e1 = new Element(1.);
        Element e2 = new Element(2.);
        Element e3 = new Element(3.);
        Element e4 = new Element(4.);

        final Map elementVal = new HashMap();
        elementVal.put(e1, e1.d);
        elementVal.put(e2, e2.d);
        elementVal.put(e3, e3.d);
        elementVal.put(e4, e4.d);

        Group g12 = new Group(Lists.newArrayList(e1, e2));
        Group g23 = new Group(Lists.newArrayList(e2, e3));
        Group g34 = new Group(Lists.newArrayList(e3, e4));

        Map groups = new HashMap();
        groups.put(g12, e1.d + e2.d);
        groups.put(g23, e2.d + e3.d);
        groups.put(g34, e3.d + e4.d);

        Collection> transform = Collections2.transform(groups.entrySet(), new Function, Collection>() {
            @Nullable
            @Override
            public Collection apply(@Nullable final Map.Entry groupEntry) {
                return Collections2.transform(elementVal.entrySet(), new Function, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable Map.Entry elementValEntry) {
                        return groupEntry.getValue() + "*" + elementValEntry.getValue();
                    }
                });
            }
        });

        FluentIterable objects = FluentIterable.from(transform).transformAndConcat(new Function, Iterable>() {
            @Nullable
            @Override
            public Iterable apply(@Nullable Collection strings) {
                return strings;
            }
        });
        System.out.println(objects);
    }

Finally we have iterable object contains multiply results.
Of course it not solution of your problem becasue You will need apply one more transformation that take result from objects and match them with Element. It's not so hard because you should only change String to some kind of Entry (pair of objects).


text:
Q: How can I complete this python program that implements the Anonymous Gregorian Computus algorithm to compute the date of Easter? I have tried to compute the date Easter falls on a particular year with this python program using the Anonymous Gregorian Computus Algorithm but I keep getting one error. My code block outputs the right result but I am finding it difficult to attach 'st' to the numbers in the 'st' list.
# Read the input from the user
year = int(input("Please enter a year to calculate the date of Easter: "))

a = year % 19
b = year // 100
c = year % 100
d = b // 4
e = b % 4
f =( b + 8) // 25
g = (b - f + 1) // 3
h =  ((19 * a) + b - d - g + 15) % 30
i = c // 4
k = c % 4
l = (32 + (2 * e) + (2 * i) - h - k) % 7
m = (a + (11 * h ) + (22 * l)) // 451
month = (h + l - (7 * m) + (114)) // 31
day = 1 + (( h + l - (7 * m) + (114)) % 31)

st = ['1', '21', '31']
nd = ['2', '22']
rd = ['3', '23']
th = ['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '24', '25', '26', '27', '28', '29', '30']

if day in st:
    print("In the year", year, "Easter will fall on the", str(day) + "st", "of", month)
elif day in nd:
    print("In the year", year, "Easter will fall on the", str(day) + "nd", "of", month)
elif day in rd:
    print("In the year", year, "Easter will fall on the", str(day) + "rd", "of", month)
else:
    print("In the year", year, "Easter will fall on the", str(day) + "th", "of", month)

Using this algorithm, I have computed for different years to check if my code block is correct but when I compute for years like 2024 and 2040 that have their Easter dates falling on the days in the 'st' list, I keep getting '31th and 1th' instead of '31st and 1st'. I don't know what lines of code I am missing. If you can help me with this or tell me how best to compute this, I will really appreciate it.
PS: I have searched for other similar questions but the ones I have solved were in a totally different language and I didn't find one that used the Anonymous Gregorian Computhus Algorithm to compute the date of Easter.
Thank you.

A: You can easily see your problem by using the Python interpreter:
$ python3
>>> st = ['1', '21', '31']
>>> 21 in st
False
>>> '21' in st
True

Strings and numbers are different things. You compute a number, so your test has to be with numbers.
$ python3
>>> st = [1, 21, 31]
>>> 21 in st
True

You should use sets instead of lists for inclusion tests. In this case, it doesn't make much difference but it's a good habit to get into in case there are lots of values.


text:
Q: Legend as filled rectangles in plot area I'm writing charts for a client and the style requires the legend to be (a) placed within the plotting area and (b) mapping fill to filled rectangles with labels. My current attempt looks like this:
library(ggplot2)
library(dplyr)
data(diamonds)

diamonds %>%
  group_by(color, cut) %>%
  summarise(price = mean(price)) %>%
  #
  ggplot(aes(x = color, y = price, fill = cut)) +
  geom_bar(stat = "identity",
           position = "dodge") +
  theme_bw() +
  annotate("rect", xmin = "D", xmax = "E", ymin = 6000, ymax = 6500, fill = "red") +
  annotate("text", x = 1.5, y = 6250, label = "Fair")

(The fact that the colour is "red" and not the ggplot red is irrelevant: the colours are manually set. Also, obviously I would need the labels for the other fill variables)
This is adequate, but I would like to know:

*

*Is there a way to detect where ggplot has white space and place the legend there (or create white space in which to place the legend)?

*Is there in general a more automatic solution than annotate?

A: The short answer is no, there is no way to "automatically detect the correct place to put the legend within the plot", at least not one that will always work. At some point you will have to fiddle with it yourself.
You can move the default legend into the plot via something like:
diamonds %>%
    group_by(color, cut) %>%
    summarise(price = mean(price)) %>%
    #
    ggplot(aes(x = color, y = price, fill = cut)) +
    geom_bar(stat = "identity",
                     position = "dodge") +
    theme_bw() +
    theme(legend.position = c(0.25,0.8),
                legend.direction = "horizontal")

if that's appealing to you.


text:
Q: Повесить картинку на кнопку Как можно повесить картинку на кнопку?

function make_pay() {
  if (($('#price').val() == '') || (!/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test($('#price').val()))) {
    $('#price').css('border-color', 'red');
  } else
    $.get("/payment/makeform.php", {
        price: $('#price').val(),
        desc: $('#desc').val(),
      },
      onAjaxSuccess
    );

  function onAjaxSuccess(data) {
    $('#form_responce').html(data);
    $('#form_responce form').submit()
  }
}

<form>
  <input id="price" name="price" type="hidden" value="1000">
  <button type="button" onclick="make_pay();" class="btn btn_green">Оплатить</button>

</form>

A: Так?

function make_pay() {
  alert("Hello");
}
img {
  width: 40px;
  vertical-align: middle;
}


text:
Q: Import schema into BigQuery via R I have a folder containing:
-- schema.yml
-- table1.csv
-- table2.csv
-- table4.csv

This folder is stored locally.
I looked around for a while and I want to ask:
Is there a way to batch upload this schema into BigQuery directly from R?

A: If you want to use R with bigquery. Bigquery documentation recommends to use tibble in conjuntion with bigrquery.
bigrquery
This package implements the bigquery rest API, where you can make use of low_level_api in the package to perform bigquery operations.
For your specific case, you can read your schema.yml file and use it to create the table fields data and create the bq_fields needed to create your table trough bq_table .In the last bit, you can read the files and create either a single file or an iteration to populate your table. This will depend in your criteria and the amount of data you are handling.
Here is a small sample to get starting using tibble with bigrquery in a notebook. ( I use a R python notebook from GCP )
library(tibble)
library(bigrquery)

# authenticate
# use if notebook is outside gcp
#bigrquery::bq_auth(path = '/Users/me/restofthepath/bigquery-credentials.json')

# set my project ID and dataset name
project_id <- '<my-project-id>'
dataset_name <- '<my-dataset-name>'

# set fields
sample_fields<-list(
  bq_field(name = "name", type = "string"),
  bq_field("age", "integer")
)

# set values
sample_df<-tribble(
   ~name,  ~age,
   "erika",  21,
   "isabel", 18,
)

# create table and upload your values
sample_table = bq_table(project = project_id, dataset = dataset_name, table = '<my-table-name>')
bq_table_create(x = sample_table, fields = as_bq_fields(sample_fields))
bq_table_upload(x = sample_table, values = sample_df, create_disposition='CREATE_IF_NEEDED', write_disposition='WRITE_APPEND')

Note: you may need to implement the env and install the libraries. For it you can do this:
# install libraries
install.packages("bigrquery")
install.packages("tibble")

# set env
print(Sys.setenv(BIGQUERY_TEST_PROJECT = "<my-project-id>"))
Sys.getenv("BIGQUERY_TEST_PROJECT")


text:
Q: Python validate String containing start_date and end_date for today's date I have a string containing start_date and end_date seperated by / like below
2017-01-30T12:00-0300/2017-03-30T00:00-0300

Here T represents time.
I want to check if this date doesn't exceed today date, do something.
What I tried-
sale_price_effective_date = current_row['sale_price_effective_date'].split("/")
            start_date = sale_price_effective_date[0]
            end_date = sale_price_effective_date[1]
            print start_date
            print end_date

Here sale_price_effective_date is the string which contains start_date and end_date.
I would like to do-
if (end_date-start_date)>datetime.now():
      //do something

Please help. Looking forward to your suggestions.

A: How about this:
In [1]: from dateutil import parser

In [2]: s = "2017-01-30T12:00-0300/2017-03-30T00:00-0300"

In [3]: start, end = s.split("/")

In [4]: start_date = parser.parse(start)

In [5]: start_date
Out[5]: datetime.datetime(2017, 1, 30, 12, 0, tzinfo=tzoffset(None, -10800))

In [6]: end_date = parser.parse(end)

In [7]: start_date > end_date
Out[7]: False

Edit:
To check if today's date is between start and end you can do:
In [19]: from datetime import datetime

In [20]: start_date < datetime.now(tz=start_date.tzinfo) < end_date
Out[20]: False

As shown by MYGz.

A: You can do it like so:
import dateutil
from datetime import datetime

a = "2017-01-30T12:00-0300/2017-03-30T00:00-0300"
a = map(dateutil.parser.parse, a.split('/'))

if datetime.now(tz=a[1].tzinfo) < a[1]:
    print "Todays date is less than end date"
else:
    print "Todays date is greater than end date"

If todays datetime can be less than or equal to end datetime, then put an additional equals sign = in comparison like so:
datetime.now(tz=a[1].tzinfo) <= a[1]


text:
Q: Pardot SDK for python after Feb 15 login change We are using Pardot SDK (package: Pypardot) to pull and update data from Pardot API (version 4).
Since the authentication change was implemented, the SDK method of Pardot is not supported anymore and it means that we need to recreate our whole API calls from scratch.
Is there any solution to use SF authentication alongside with Pardot SDK?

A: I haven't used it yet myself, you might want to checkout PyPardotSF.
https://github.com/anelendata/PyPardotSF
Based on the documentation, this library should be a bit more feature-rich than the original as it supports both V3 and V4.
There is no mention yet of the V5 API, so if that's important to you then you may need to make adjustments and use what you can.


text:
Q: SurveyMonkey API get_survey_details Why is get_survey_details response returning this error msg?
When running a request via the SurveyMonkey API for the get_survey_details method
https://api.surveymonkey.net/v2/surveys/get_survey_details
The response is:
{"status":3,"errmsg":"Survey requested 'xxxxxxx' has more than 200 pages" }
This is a custom app, using the API key and token generated in the API console.  My user has the Gold plan.
The online guide for the api indicates a limit (any plan level) of 1000 questions and 1000 pages.  https://developer.surveymonkey.com/mashery/limits
Any help is appreciated

A: The max page size limit is used for pagination. It represents the maximum number of resource items that can be returned for a page. For example, you can only fetch a maximum of 1000 surveys from /v2/surveys/get_survey_list per call.
I've updated the docs to provide a bit more clarity.

A: There is a limit on the number of pages a survey can have in order to be serviceable by SurveyMonkey's API. 200 is the hard limit currently configured.
That limit is documented here as, "1000 questions or 200 pages, surveys over limit will not be returned"


text:
Q: jquery can't get input value from dynamically created field within a function 'This is a little strange, and different than what I can find in the forums, but I encounter this problem again and again when I work with jQuery.
I have code that calls ajax and creates (on success) an input like:
Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u();">Execute</button>

In the main body of the HTML, I have a function like this:
<script type="text/javascript" language="javascript">
function reassign_u()
{
   alert($("#gr_start_dt").val());
}
</script>

This will alert to "undefined".
If I change the button in the ajax generated section to:
<button onclick="alert($('#gr_start_dt').val());">Execute</button>

it will alert with the value of the box.
I can get the value from outside of the function, but not within the function.
Am I missing something here? Is there some scope I'm not aware of with jquery and dynamically generated pages with ajax?
I'm using jquery 2.1.3 and 2.1.4, Firefox 39.

A: I think that is because when the javascript function was cached into the browser the element $("#gr_start_dt") is not yet defined. And calling the function will just call the function that was cached having the undefined element inside the alert function.
So why not do it like this:
below is the html
Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u($('#gr_start_dt'));">Execute</button>

below is the javascript:
<script type="text/javascript" language="javascript">
function reassign_u(el)
{
   alert($(el).val());
}
</script>

A: Removing the the line: $("#invoice_detail_content").html(''); from the following function should resolve the issue. This line removes the the textbox in question.
function reassign_user2() {
    $("#action_menu_container").hide();
    $("#invoice_detail_content").html(''); //<== REMOVE THIS
    $("#invoice_detail").show();
    $("#loading").show();

    console.log($("#group_start_dt"));

    alert($("#group_start_dt").val());

    $.ajax({
        url: "fetch.php",
        cache: false,
        method: "POST",
        data: {
            action: 'reassign_group',
            parameters: JSON.stringify(parameters)
        }
    })
    .done(function(result) {
        $("#loading").hide();
        result = result.trim();
        if(result)
        {
            $("#invoice_detail_content").html(result);
        }
        else
        {
            $("#invoice_detail").hide();
            show_invoices($("#invoice_status_select").val());
        }
    })
    .fail(function( jqXHR, textStatus ) {
        $("#loading").hide();
        alert( "Request failed: " + textStatus );
    });
}

A: So I'm taking a bit of a stab at this so hopefully I don't get down voted :(, though I believe I have the answer to this question.
When the DOM tree is created on the first page load all of the javascript events are bound to the all their respective elements, thus your .val() isn't attaching to any dynamically generated elements, but, one thing I have noticed, is that if you dynamically add some javascript with that dynamically created element it will run its binding process right then and there and still work, which is what you have done by putting the alert($(element).val()) directly on the dynamically generated element.
Hopefully this helps you, if not somebody out there. I realized the answer is a bit late.

A: I'm pretty sure creating things with JQuery/AJAX still causes it to enter the DOM, which means it can be gotten with $('selector'). So it should be just as straightforward usual.
I used:
<script>
    function on_clicked() {
       alert($("#text_input").val());
    }
</script>

<input type="text" id="text_input" size=10>
<button onclick="on_clicked();">Execute</button>

Working JSFiddle here.
I found that you have to declare the function before setting it to the onclick attribute. Which makes sense. Otherwise I don't see any other big problems.
Update
I am now making the <form> element "asynchronously" (I used a timeout to simulate AJAX. As long as the callback is declared before and in scope, it works fine.
JSFiddle
I've replicated what you are saying as well as I can, and it still works.

A: It works for me. May be you should put the js function in the same file from which you make the AJAX call.
here's the code
index.php
<head>
            function doSomeTheing() {
                $.ajax({
                    url: 'test01.php',
                    success: function (mydata) {
                        $('#container').html(mydata);
                    }
                });
            }

            function reassign_u()
            {
                alert($("#gr_start_dt").val());
            }
</head>
<body>
        <input type="button" id="abc" onclick="doSomeTheing()" value="test">
        <div id="container">

        </div>
</body>

test.php contains
<?php

echo 'Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u();">Execute</button>';


text:
Q: How to use Schema.org 'name' and 'url' in  tag? This code was suggested to me:
…

But do you think this code is also correct?

     Home

A: No, this is not correct. There are special parsing rules for a.
Currently you'd have these name-value pairs:
url: Home
name: http://any.com/

But, of course, it should be the other way around. So:

*

*The url property needs to be specified on a.

*The name property needs to be specified on something other than a.

You could use, for example:

  Home

(See also my answer to a similar question on Webmasters.)


text:
Q: Sorting Icelandic index correctly using LaTeX (accented characters after non-accented) I'm using Xindy to make an index for my book. It sorts the words mostly correctly, but it doesn't sort accented characters (i.e. á é í ó ú ý) after the corresponding non-accented characters (a e i o u y), unless the words are otherwise identical. For example, Xindy will sort 'ís' after 'is', but it will sort 'auga' after 'ás'.
I would like it to sort ás after auga, and in general I want it to sort the accented characters after the corresponding non-accented character. For the record, this is the correct sort order:
a, á, b, c, d, ð, e, é, f, g, h, i, í, j, k, l, m, n, o, ó, p, q, r, s, t, u, ú, v, w, x, y, ý, z, þ, æ, ö
Here's my MWE:
% filename alphabet.tex
\documentclass[a4paper,11pt]{book}
\usepackage[icelandic]{babel}
\usepackage[T1]{fontenc}
\usepackage{makeidx}
\makeindex

\title{My book}
\author{Me}
\begin{document}
\chapter{Stafrófið}

Ananas\index{ananas}, ás\index{ás},
banani\index{banani}, dagblað\index{dagblað}, epli\index{epli}, ég\index{ég}, flugvél\index{flugvél}, gíraffi\index{gíraffi}, hús\index{hús}, indíáni\index{indíáni}, ís\index{ís}, jörðin\index{jörðin}, kisa\index{kisa}, lykill\index{lykill}, mús\index{mús},
nef\index{nef}, ormur\index{ormur}, óbó\index{óbó}, píanó\index{píanó}, rós\index{rós}, skæri\index{skæri}, tré\index{tré}, ugla\index{ugla}, úr\index{úr}, varir\index{varir}, yddari\index{yddari}, ýta\index{ýta}, þvottavél\index{þvottavél}, æð\index{æð}, ör\index{ör}, auga\index{auga}, eyra\index{eyra}.

\printindex
\end{document}

I compile it using
pdflatex alphabet.tex
texindy -L icelandic alphabet.idx
pdflatex alphabet.tex

(you may have to update Xindy, as I had to do).
What I'm hoping for is some kind of command, either in my .tex document or in some file that Xindy reads, but other solutions are appreciated.
This question is similar and has an answer that seems to work but it uses LuaTex while I use LaTeX (switching is not an option). It's also very long and technical for such a (seemingly) simple change.
Edit: I failed to mention that my LaTeX file is not utf-8 encoded and I'm not using \usepackage[utf8]{inputenc}, which I think might matter. I'm working on a 300+ book and I'm afraid that changing the encoding might have unexpected effects, so if there's a solution that doesn't require utf-8, that would be preferred.

A: The solution can be found at question Texindy sorting Icelandic - Edit 2 A minimalistic version and  LuaTex is not required to obtain the solution.
Download the first file using a terminal and place it inside your LaTex folder:
wget http://striz7.fame.utb.cz/tex-sx/is-min/icelandicmalmin.xdy

Update: Download iec2utf and place all files inside your LaTex folder:
https://github.com/michal-h21/iec2utf

Run the following commands:
pdflatex alphabet
texlua iec2utf.lua <alphabet.idx >mal-temp.idx
xindy -M texindy -M icelandicmalmin-test -M mal-style -o alphabet.ind mal-temp.idx
biber alphabet
pdflatex alphabet
pdflatex alphabet

Example of index sorting Icelandic characters with accents:


text:
Q: Print list in specific format I have a list with 72 bounding boxes. This is the dput (just 5 of them).
list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178
), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007
), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007
), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007
), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007
))

and this is the desired output:
c(7.4267580,47.3983490,7.8508356,47.6861780)

How can I print each bounding box in the desired output using a for loop?

A: You'll get this output by running
dput(lapply(your_list, unname))

However, if you want to save the stringified vectors to a new vector, there's a more direct way, via the toString function. first off, here's what toString does to a vector:
toString(1 : 5)
# [1] "1, 2, 3, 4, 5"

Great! That's almost what we want; we just need to put it into c(…):
paste0('c(', toString(1 : 5), ')')
# [1] "c(1, 2, 3, 4, 5)"

And now we need to apply this operation to every element in the original list. vapply does that:
result = vapply(your_list, \(x) paste0('c(', toString(x), ')'), character(1L))

A: The following will print each element of the list in the required format:
have <- list(`1` = c(V1 = 7.426758, V2 = 47.398349, V3 = 7.8508356, V4 = 47.686178
), `10` = c(V1 = 7.8508356, V2 = 47.686178, V3 = 8.2749132, V4 = 47.974007
), `11` = c(V1 = 8.2749132, V2 = 47.686178, V3 = 8.6989908, V4 = 47.974007
), `12` = c(V1 = 8.6989908, V2 = 47.686178, V3 = 9.1230684, V4 = 47.974007
), `13` = c(V1 = 9.1230684, V2 = 47.686178, V3 = 9.547146, V4 = 47.974007
))

for (item in have) {dput(unname(item))}


text:
Q: Передача значения по ссылке Допустим, на сайте есть 4 страницы:

*

*page.html (здесь 2 ссылки<a>, которые ведут на другую страницу - example.html)

*example.html (пустая страница)

*result1.html

*result2.html
Как сделать так, чтобы при нажатии на первую ссылку, открывалась страница example.html с содержимым result1.html? Соответственно, при нажатии на вторую ссылку, также открывается example.html, но в неё подгружается содержимое result2.html.
Насколько я понимаю, по ссылке необходимо передавать некоторое значение, а на пустой странице делать проверку: если значение одно, то показываем содержимое result1.html, если другое - то result2.html. Подскажите, как можно осуществить подобное и с помощью чего (JS, PHP или стандартными средствами HTML)?
Заранее огромное спасибо.

A: ну если только подсказать, а не код писать то расcкажу про JS варианты:
A вариант:
1 - при наведение курсора на необходимую ссылку (событие onmousemove) записать в куку(coockies) сделать то то (это зависит от той ссылки над которой сейчас курсор)
2 - в коде example.html на событие onload или в самом начале страницы повешать код который прочитает куку и в зависимости от того что там написано выполняет необходимое действие
B вариант
1 - В нужной ссылке в параметр href кроме самой ссылке добавить GET параметры
2 - .. и ловить их в example.html и в зависимости от того что в параметрах выполнять соответствующие действия
C вариант
использовать локальное хранилище из HTML5 действия будут аналогичны A варианту
PS
а вообще вам следует узнать способы передачи данных между страницами на JS

A: Можно на PHP.
К ссылке на example.php добавьте GET-запрос example.php?page=1 или example.php?page=2
Код в example.php будет примерно такой:
<?php
if ($_GET['page'] == 1)
  readfile("result1.html");
if ($_GET['page'] == 2)
  readfile("result2.html");
?>


text:
Q: Xpage the Domino bookmarks nsf I am trying to create an XPage version of the domino bookmarks.nsf used for creating the home page in the client. The users want to be able to see their most used databases with a link to go straight there.
Does anybody know how the domino favorites works and how to consume data from it?

A: The bookmark.nsf is beaten in mystery only by the desktop.dsk :-)
All entries in the Open button are stored as Outline design elements. Outlines are read/write in the LotusScript/Java/SSJS API, so you could grab them in a SSJS library. I don't know when/how the favorites are updated


text:
Q: Using mechanize (or even Net::HTTP) with ruby 1.9 returns 'OpenSSL::SSL::SSLError' - how to force SSLv3? For the past 2 days, I think I've been through every single available (google'able) post about this SSL-Error in connection with Net::HTTP:
OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A
What I tried doing in the first place, was connecting to a EtherPad server (https://test.titanpad.com), signing in, and downloading a zip-archive via using rubygems & mechanize; however, unfortunately I don't even get up to that point due to said SSL-Error. After trying to debug the issue from within a mechanize object (f.e. by setting cert, ca_file, cert_store, verify_mode, etc. manually in the script), I went one level closer to the actual issue, trying to connect to https://test.titanpad.com by simply using Net::HTTP:
(in this example, I first connected to https://encrypted.google.com to make sure, SSL should work out; the attempt to connect to the EtherPad server starts from line 6)
irb(main):001:0> require 'net/https'
=> true
irb(main):002:0> google = Net::HTTP.new('encrypted.google.com', 443)
=> #<Net::HTTP encrypted.google.com:443 open=false>
irb(main):003:0> google.use_ssl = true
=> true
irb(main):004:0> google.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt' if File.exists?('/opt/local/share/curl/curl-ca-bundle.crt')
=> "/opt/local/share/curl/curl-ca-bundle.crt"
irb(main):005:0> google.request_get('/')
=> #<Net::HTTPOK 200 OK readbody=true>

irb(main):006:0> etherpad = Net::HTTP.new('test.titanpad.com', 443)
=> #<Net::HTTP test.titanpad.com:443 open=false>
irb(main):007:0> etherpad.use_ssl = true
=> true
irb(main):008:0> etherpad.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt' if File.exists?('/opt/local/share/curl/curl-ca-bundle.crt')
=> "/opt/local/share/curl/curl-ca-bundle.crt"
irb(main):009:0> etherpad.request_get('/')
OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `connect'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `block in connect'
    from /opt/local/lib/ruby1.9/1.9.1/timeout.rb:54:in `timeout'
    from /opt/local/lib/ruby1.9/1.9.1/timeout.rb:99:in `timeout'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `connect'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:755:in `do_start'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:744:in `start'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1284:in `request'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1195:in `request_get'
    from (irb):9
    from /opt/local/bin/irb:12:in `<main>'

Even when using verify_mode OpenSSL::SSL::VERIFY_NONE, OpenSSL bails out:
irb(main):010:0> etherpad.verify_mode = OpenSSL::SSL::VERIFY_NONE
=> 0
irb(main):011:0> etherpad.request_get('/')
OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `connect'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `block in connect'
    from /opt/local/lib/ruby1.9/1.9.1/timeout.rb:54:in `timeout'
    from /opt/local/lib/ruby1.9/1.9.1/timeout.rb:99:in `timeout'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:799:in `connect'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:755:in `do_start'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:744:in `start'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1284:in `request'
    from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1195:in `request_get'
    from (irb):11
    from /opt/local/bin/irb:12:in `<main>'

After further playing around with openssl itself, it turns out the real trouble in this case is that the use of SSLv3 has to be forced for the handshake with the Jetty 6.1.20 server behind titanpad.com to work:
irb(main):001:0> require 'net/https'
=> true
irb(main):002:0> etherpad = Net::HTTP.new('test.titanpad.com', 443)
=> #<Net::HTTP test.titanpad.com:443 open=false>
irb(main):003:0> etherpad.use_ssl = true
=> true
irb(main):004:0> etherpad.ssl_version = "SSLv3"
=> "SSLv3"
irb(main):005:0> etherpad.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt' if File.exists?('/opt/local/share/curl/curl-ca-bundle.crt')
=> "/opt/local/share/curl/curl-ca-bundle.crt"
irb(main):006:0> etherpad.request_get('/')
=> #<Net::HTTPFound 302 Found readbody=true>

Now while this obviously works when using Net::HTTP, there is no such option as to set the SSL version to use in Mechanize... and I'd therefore be really glad if someone could point out to me as to how I could enforce SSLv3 via said gem o.O
Thanks again!
System: Mac OSX 10.6.8
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin10]
rubygems installed with mechanize: domain_name (0.5.2), mechanize (2.1.1), net-http-digest_auth (1.2), net-http-persistent (2.4.1), nokogiri (1.5.0), ntlm-http (0.1.1), unf (0.0.4), unf_ext (0.0.4), webrobots (0.0.13)

A: Has been fixed by porting the ssl_version functionality from Net::HTTP (via net-http-persistent) to Mechanize v. 2.1.2 (see https://github.com/tenderlove/mechanize/commit/4a228899855e0676ab69c2bf548170c8717465d8).


text:
Q: Interpreting LRT output I am comparing the fit of two models:
> lrtest(fullmodel,reducedmodel)
Likelihood ratio test

Model 1: MM ~ x * y + (1 | Replicate)
Model 2: MM ~ x * y
  #Df LogLik Df  Chisq Pr(>Chisq)
1   8 357.35
2   7 368.40 -1 22.095  2.595e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So from looking at the output the models are significant. How do I tell what model is best - do you use the LogLik value? Do I pick the one with the lowest LogLik value (e.g. in this case Model 2 has the lowest LogLik so that is the best model)?

A: The models are not significant. Read There is a significant difference in the two compared models (in log likelihoods). In this particular implementation it appears that you want to maximize the LogLik, so in your case Model 2 (without random effects) is the more parsimonious model.


text:
Q: What is "crypt32" in Windows XP? On my Windows XP machine I am getting an application error as follows in the event viewer:

Failed extract of third-party root list from auto update cab at:
  http://www.download.windowsupdate.com/msdownload/update/v3/static/trustedr/en/authrootstl.cab
  with error: A required certificate is not within its validity period
  when verifying against the current system clock or the timestamp in
  the signed file.

This error is attributed to "crypt32". What is it trying to do?

A: When searching for authroot.stl (the file inside the CAB archive) you'll find it's the list of trusted root certificates. For example, this article is among the results.
Windows is trying to update its root certificate storage.
Unfortunately, this file isn't counter-signed with a timestamp and the signing certificate has expired on April 12, 2018. As such, it is now useless. It's timestamp indicates it was created on September 22, 2017.
Unless Microsoft renews the file, Windows XP will not receive updates to its root certificates. This isn't terribly critical, unless one of the trusted Certificate Authorities were to be compromised.

A: https://www.microsoft.com/en-gb/windowsforbusiness/end-of-xp-support
It basically means that WinXp is no longer supported and the certificate is outdated. You will run into all sorts of problems trying to continue using WinXP and you will receive little to none support on those.
Crypt32 itself is a library containing cyrptographic functions used by Windows Crypto API:
https://docs.microsoft.com/en-us/windows/desktop/seccrypto/crypt32-dll-versions
If I remember correctly Windows XP did not receive a critical update of crypt32 and some other dll that are required to support newest SHA algorithm. This was the major crushing blow to those tryint to continue using WinXP and older IE.
Could it be that you are trying to get Windows XP / IE 8 to access some modern https webservice by installing updates?


text:
Q: Can I create an ambient transaction for testing? My current system has a rather aggressive data layer that creates an SqlDatabase instance for me by calling a static method. I pass in a stored procedure name (string) and the magic just happens.
I want to try and get some of this crazy system under test and so want to control what is in the database.
Having realised that this structure
[Test]
public void Should_do_some_thing()
{
  using (var scope = new TransactionScope())
            {
                CleanUpDatabase();
                SetupDatabaseData();

                //Run Test

                Assert.That(someResult,Is.EqualTo("ExpectedValue");

                scope.Dispose();
            }
}

does what I want (no database changes persist outside the test) It would clearly be nicer if I could set up the transaction within a [SetUp] method and remove without committing in the [TearDown] section.
Is this possible?
Note I cannot call any methods on a command object or whatever...

A: You could use TestInitialize and TestCleanup to do the set up/clean up:
private TransactionScope scope;

[TestInitialize]
public void TestInitialize()
{
    scope = new TransactionScope();
    CleanUpDatabase();
    SetupDatabaseData();
}

[Test]
public void Should_do_some_thing()
{
    //Run Test

    Assert.That(someResult,Is.EqualTo("ExpectedValue");
}

[TestCleanup]
public void CleanUp()
{
    scope.Dispose();
}

You may need to add error handling etc but this is the basics of it:
TestInitialize:

Identifies the method to run before the test to allocate and configure resources needed by all tests in the test class. This class cannot be inherited.

TestCleanUp:

Identifies a method that contains code that must be used after the test has run and to free resources obtained by all the tests in the test class. This class cannot be inherited.

If you are using NUNIT then you can use [SetUp] and [TearDown] instead of [TestInitialize] and [TestCleanUp] respectively.


text:
Q: Angular - How to Unit Test a Subscription on a Service? I've been trying to find a way to test a subscription that is on a mocked service within Angular using Jest. But I can't find a way to mock the Observable and test the assignment of the isMobile property.
When I try to spyOn and then mock the service to return a value, it is never updated. And I would like to be able to test the code with different responses from the service.
Code below.
Component
import { Component, Input, OnInit } from '@angular/core';
import { BREAKPOINT, BreakpointService } from '../../services';

@Component({
  selector: 'auxiliary-bar',
  templateUrl: './auxiliary-bar.component.html',
  styleUrls: ['./auxiliary-bar.component.scss'],
})
export class AuxiliaryBarComponent implements OnInit {
  public isMobile = false;

  constructor(private breakpointService: BreakpointService) {}

  ngOnInit(): void {
    this.breakpointService.onBreakpoint$.subscribe(
      (breakpoint) => (this.isMobile = breakpoint <= BREAKPOINT.SM),
    );
  }
}

Breakpoint Service
import { Injectable, NgZone, OnDestroy } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

export enum BREAKPOINT {
  XS,
  SM,
  MD,
  LG,
  XL,
}

@Injectable({
  providedIn: 'root',
})
export class BreakpointService implements OnDestroy {
  private breakpointSubject: Subject<BREAKPOINT> = new Subject();
  private observer!: ResizeObserver;
  private sizes = [
    {
      id: BREAKPOINT.SM,
      width: 0,
    },
    {
      id: BREAKPOINT.SM,
      width: 320,
    },
    {
      id: BREAKPOINT.MD,
      width: 768,
    },
    {
      id: BREAKPOINT.LG,
      width: 1024,
    },
    {
      id: BREAKPOINT.XL,
      width: 1200,
    },
  ];

  constructor(private zone: NgZone) {
    this.observer = new ResizeObserver((entries) => {
      this.zone.run(() => {
        const matchedSize = this.sizes
          .slice(1)
          .reverse()
          .find(
            (size) => window.matchMedia(`(min-width: ${size.width}px)`).matches,
          );
        this.breakpointSubject.next(
          matchedSize ? matchedSize.id : BREAKPOINT.XS,
        );
      });
    });
    this.observer.observe(document.body);
  }

  ngOnDestroy(): void {
    this.observer.unobserve(document.body);
  }

  public get onBreakpoint$(): Observable<BREAKPOINT> {
    return this.breakpointSubject.asObservable().pipe(distinctUntilChanged());
  }
}

Attempted Test Suite
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockProvider } from 'ng-mocks';
import { Observable, of } from 'rxjs';

import { BreakpointService } from '../../services';
import { AuxiliaryBarComponent } from './auxiliary-bar.component';

describe('AuxiliaryBarComponent', () => {
  let component: AuxiliaryBarComponent;
  let fixture: ComponentFixture<AuxiliaryBarComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        AuxiliaryBarComponent,
      ],
      providers: [
        MockProvider(BreakpointService, {
          onBreakpoint$: new Observable(),
        }),
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AuxiliaryBarComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should', () => {
    const breakpointService = TestBed.inject(BreakpointService);
    const spy = jest
      .spyOn(breakpointService, 'onBreakpoint$', 'get')
      .mockReturnValue(of(3));
    fixture.detectChanges();
    expect(breakpointService.onBreakpoint$.subscribe).toHaveBeenCalled();
  });
)};

A: I'm pretty sure it's too late because the component is already instantiated and therefore ngInit is already called by the time your it starts. If I'm right, then a fix might be as easy as inserting component.ngOnInit() before your last fixture.detectChanges() to re-trigger it.
As an aside, your component shouldn't subscribe if you can help it. Instead, if it works for your needs then I would change the component's ngOnInit to
public isMobile$: Observable<boolean>;
ngOnInit(): void {
  this.isMobile$ = this.breakpointService.onBreakpoint$.pipe(
    map(breakpoint => breakpoint <= BREAKPOINT.SM)
  );
}

and then in your template, wherever you used to have isMobile, use (isMobile$ | async) instead.
But if you must subscribe within a service or component (or maybe also do this for safety and good programming practice), your service should have an ngOnDestroy that calls this.breakpointSubject?complete();.


text:
Q: symbols display wrong in `screen` - ascii or utf I don't know since when and why :
$ mkdir -p a/b/c x/y/{1,2,3}
$ tree
.
├── a
│   └── b
│       └── c
└── x
    └── y
        ├── 1
        ├── 2
        └── 3

8 directories, 0 files

when I run screen, displays symbols full of question marks:
$ screen
<-- screen starts... -->
$ tree
.
��� a
�   ��� b
�       ��� c
��� x
    ��� y
        ��� 1
        ��� 2
        ��� 3

8 directories, 0 files

Similarly for utf characters.
Even if I move away my .screenrc (e.g. with mv -v ~/.screenrc{,.bak} ) it's still strange characters set.
It happens on screen on my main user, on root user, but on my secondary user it does not. On this one characters work properly in screen. And it's not .screenrc as I played with it.
Updates:
Re: $TERM - seems unrelated

*

*without screen: TERM==xterm-256color

*user A inside screen: TERM==screen.xterm-256color and display incorrectly

*user B inside screen: TERM==screen.xterm-256color and display correctly

Re: defutf8 on - does something
After adding defutf8 on in .screenrc there is now mix ;p some symbols work some don't, example :
$ tree
.
├── a
│�� └── b
│��     └── c
└── x
    └── y
        ├── 1
        ├── 2
        └── 3

8 directories, 0 files

A: Thanks to comments in my original question, they helped me to narrow troubleshooting and find that this one line in my ~/.bashrc is the cause - locale staff I guess:
export LC_PAPER=a4

with this line, e.g. tree displays correctly without screen but incorrectly inside screen.
After removing this line from .bashrc it looks good again.


text:
Q: When should I flag off-topic questions for migration? Let's say I come across a recently posted question on Stack Overflow which is clearly better suited for another Stack Exchange site.
Let's also assume that the site it belongs on is not one of the automatic migration targets listed in the "close as off topic" menu (which it usually isn't — the SE network is big, and automatic migration targets are few and far between).
How should I deal with it?

*

*a) Flag it for ♦ moderator attention, with a note saying "Migrate to whatever.SE."

*b) Vote to close it as off topic, and leave a polite comment pointing the asker to the other site.

*c) Both of the above.

*d) Something else.

Also, should the decision depend on whether the question already has answers?  Or on whether it already has an accepted (or highly upvoted and clearly correct) answer?

Ps. For some background, my usual approach in the past has been (a) — flag the question promptly for migration, so that it can be cleanly and smoothly rerouted to the appropriate site, while ensuring that anyone else finding the question on Google will also be sent to the right place.
I'm aware that, by doing so, I've been creating extra work for the ♦ mods, but nobody's explicitly complained about it so far, and past meta threads on the subject have pretty clearly implied that this is appropriate.
However, lately I've seen a few of these flags declined, and also many of them accepted as "helpful" but without the question actually being migrated.  So, naturally, I'm starting to wonder if I'm handling these situations the wrong way, and whether there's some better approach (like, say, (b) above)?
I'd particularly like to get some "official" feedback from the SO mods: give that you end up making the final call anyway, what sort of questions should I and should I not send your way?
Pps. For more concrete context, here are some recent example entries (in reverse chronological order) from my flag history since Christmas:

*

*Best way to send email when PHP process dies: flagged as "Migrate to serverfault."; awaiting review.

*How to find private key in RSA: flagged as "Migrate to crypto.SE."; flag deemed helpful, post closed as off topic by a ♦ mod, but not migrated.

*DES key expansion: why are these two descriptions different?: flagged as "Migrate to crypto.SE."; awaiting review.

*Rule Handling for a Mao (Card Game): flagged as "More of a design than a programming question. Migrate to gamedev.SE?", also left a comment pointing the OP to gamedev.SE; flag deemed helpful, post deleted by OP but not, apparently, reposted anywhere.

*Why should a salt have the same length as the hashed value?: flagged as "Migrate to crypto.SE.", also left comment and voted to close; flag deemed helpful, post closed as off topic by 5 voters including me, not migrated.

*how to find an open webform on my website?: flagged as "Off topic, migrate to webmasters.SE or security.SE."; flag deemed helpful, post closed by a ♦ mod, not migrated.

*Booting BZ image on qEmu: flagged as "Migrate to unix.SE?", also voted to close; flag deemed helpful, post closed by 5 voters, not migrated.

*GMAIL API for visualizing inbox: flagged as "Migrate to webapps.SE?", also voted to close: flag deemed helpful, post closed by 5 voters, not migrated.

*Xming gedit not displayed: flagged as "Migrate to ServerFault?", also voted to close; flag declined, post closed by 5 voters.

*Does Apple notify me if my bug which has been marked as a duplicate has been addressed?: flagged as "Migrate to Ask Different?", also voted to close; flag deemed helpful, post closed by 5 voters, not migrated.

*Website sometimes slow down?: flagged as "Off topic, migrate to webmasters.SE?"; flag deemed helpful, post closed by 5 voters, not migrated.

*Bash prompt script with an error: flagged as "Migrate to unix.SE?", also voted to close; flag deemed helpful, post closed by 5 voters, not migrated.

*Image encryption, resistant to scaling and color grading - is there an algorythm?: flagged as "Off topic for SO. Should be on topic for crypto.SE, migrate there?"; flag declined, post closed by 5 voters.

*Http basic Authentication instead of TlS client certificaiton: flagged as "Migrate to security.SE?"; flag deemed helpful, post still open and not migrated.

*Secure data in database: flagged as "Not really a programming question. Migrate to security.SE?"; flag declined with custom note "This is not a high-quality question, so should not be migrated.", post closed as not constructive by 5 voters.

*Bash terminal and color output: flagged as "Migrate to unix.SE?"; flag deemed helpful, post closed by a ♦ mod, not migrated.

*Initial states with interpolated fixed time steps: flagged as "Migrate to gamedev.SE?"; flag deemed helpful, post still open and not migrated.
That's 17 flags over about four (admittedly busy) days, three of them declined and not a single one actioned.  That kind of suggests to me that I must be doing something wrong here.
I'm happy to also receive any critique, even harsh, on those specific flags (especially if accompanied by helpful advice on how to deal with such cases better), but what I'm mainly hoping for is more general feedback that could be useful to others as well; I only added the list to make it clear what kind of questions and flags I'm taking about.

A: When all of the following criteria apply:

*

*The question could not be closed for any of the other reasons.

*The question isn't more than 60 days old (regular users and moderators can no longer vote for migration, but nothing stops users from flagging it anyways).

*You are familiar enough with the target site to know, with 100% certainty, that it belongs there.
If the question does not meet any one of those, just vote to close it and move on.

A: The majority of those questions are just way too low-quality to migrate anywhere.  One or two of the following might be salvagable, but that's really the best I can say.  None of them are really great questions that we should be in a hurry to migrate anywhere.  I think all of these would be closed on the target site if they were migrated.

*

*Secure data in database

*Image encryption, resistant to scaling and color grading - is there an algorythm?

*Bash prompt script with an error

*Website sometimes slow down?

*Does Apple notify me if my bug which has been marked as a duplicate has been addressed?

*Xming gedit not displayed

*GMAIL API for visualizing inbox

*how to find an open webform on my website?

*Booting BZ image on qEmu

*How to find private key in RSA
You can improve your accept rate on these types of flags if you only flag questions that are of really high quality, and that you know the community on another site will want.  If you're not 100% sure it would be a great question on another site, just vote to close it where it's at.


text:
Q: Eigen operator(Index, Index) of a temporary matrix product Let's say i'm only interested in a single (i, j) element of a matrix product, so I do (A * B)(i, j). Will Eigen compute the full product of A and B and then access the (i, j) element or will it be smart about it and only calculate what's necessary? If not, what can I do about it?
I'm currently doing SVD-based lossy matrix compression for memory reasons, so I want to store the U, S and V matrices of the SVD and compute elements of the original matrix on the fly: aij = (U * S.asDiagonal() * V.transpose())(i,j) hereby my question.

A: Good question. Computing matrix products coefficient-wise is inefficient, and in current version of Eigen, calling operator(i,j) on a matrix product is thus forbidden (at compile time). So if you access most of the aij, it is much better to evaluate it in a temporary. If you access a very few percent of them in a non structured manner, then you can wrap it in a function implementing:
return U.row(i) * S.asDiagonal() * V.row(j).transpose();

In future version of Eigen, that is 3.3 or maybe 3.4 only, Eigen will automatically propagate the information to the leaves of the expression tree for you.


text:
Q: make a duplication of a branch with identical but not the same commits as of the original branch I have this project added to a git repository with the main branch consisting of a number of commits.
      A--->B--->C--->D--->E

as i'm doing some experimental modifications on commits A through B i want to keep a copy of the commits of main branch inside a different branch main-copy in case anything went wrong due to play with commits in main branch and i wouldn't want to go through restoring, i still have an intact copy of main branch.
if i create main_copy branch on top of commit E where Head is currently at i will not actually make a copy of main branch because commits A to B are common between the two branches.
so i need to create a branch on top of commit A and do the same commits in this branch. the final repository would be something like this.
     A--->B--->C--->D--->E
     |
     `--->B'--->C'--->D'--->E'

I have no idea how to do this without going back to commit A making another branch and doing commits B through E again one by one.
is there any devoted command to do this on git?

A: TL;DR
All you need to do is create a branch name before you start experimenting.
Long-ish

... I'm doing some experimental modifications on commits A through ...

No, you're not.
I don't mean you aren't trying to do that.  I mean it's literally impossible to do that, so no matter what you try, that doesn't actually happen.
The trick here is this: commits are immutable, but we don't find them by their immutable true names.  The true name of any given commit is its hash ID, and using that hash ID will find that commit.  That commit can never be changed, no matter how hard you try; using that name again later will find that commit (with one caveat: see below).
A branch name, in Git, is a database entry, but you can think of it as a small file, because it's sometimes implemented as a small file.  This "file" (or actual file) contains one string, and that one string the entry provides is the hash ID of the last commit we want to claim is "in the branch".
That is, given a string of commits:
... <-F <-G <-H

which ends at commit H, if we create a branch name entry and stuff the raw hash ID of commit H into that name, we get:
...--F--G--H   <-- somebranch

Running git log somebranch shows us commit H, then commit G, then commit F, and so on.
If we attempt to change some of these commits—such as G—what happens instead is that we immediately get a new commit, a G', whose parent is F.  New commit G' has no child, and to find G' we will use a name, such as a branch name, because humans are so bad at using hash IDs:
...--F--G--H   <-- somebranch
      \
       G'  <-- newbranch

If the purpose of making "modified" commit G' was to edit just the text of the commit message in G, new commit G' will hold as its snapshot the same snapshot that G holds (and the two snapshots will be 100% de-duplicated and thus the one for G' takes no extra space).  We then have to make a new H' copy of H where the one thing we change in H' is its saved parent hash ID: commit H' must point backwards to our new G':
...--F--G--H   <-- somebranch
      \
       G'-H'  <-- newbranch

Once we're in this situation, if we stuff H's hash ID into the name somebranch, we get:
...--F--G--H   ???
      \
       G'-H'  <-- somebranch, newbranch

If we now delete the temporary name newbranch, it seems as though we've edited commit G' somehow:
       G--H   ???
      /
...--F--G'-H'  <-- somebranch

We literally can't find commit H unless we've memorized its hash ID somewhere.
Of course, the place to memorize its hash ID is obvious: we just create a new branch name before we do whatever it is that we do that "modifies" G to make G'.  Then, once the name somebranch locates H' instead of H, our branch we created earlier locates H:
       G--H   <-- original-somebranch
      /
...--F--G'-H'  <-- somebranch

and git log original-somebranch shows us the original commits, which still exist.
What if we forget to create the name?
If we forget to create a name like original-somebranch, we must find the hash ID of old commit H.  We have some time to do this: a Git repository will not discard an old commit, even if it's unfindable by ordinary means, for "some time".  How long is that "some time"?  Well, that depends on many things.  Some hosting systems (e.g., GitHub) never discard old commits.  Git by default sets three expiration times though: 14 days, 30 days, and 90 days.  After one of these three times, old commits that can't be found by any name can go away.
You're safest, of course, if you make the new name first, before doing git rebase -i or whatever it is that you are doing.  But most actions place a copy of a commit hash ID into another name, or a reflog entry, and here the 30 or 90 day default kicks in.  To be safe we should just consider the shorter expiration: 30 days after we were able to find H, if we haven't bothered to create a name for it, Git may get around to removing it.  Git's process for doing this is kind of lazy so it could stick around for many more months or years, but it has "become vulnerable" after the 30 day expiry of the reflog entry.
You can view reflog entries with git reflog, which is actually a front end that runs git log -g.  See the documentation for git reflog for details.  Note that in a sea of random-looking hash IDs and commit messages, it can be hard to tell one old commit from another.  That's the other reason to make the name before you start working.
If a commit is removed via the "garbage collector" git gc, and you give Git its true name (hash ID), Git will say that it doesn't recognize that hash ID.  The same thing happens if you just make up a hash ID—although if you "make up" a shortened one, there's a good chance that this is the valid prefix of some existing commit, so you want to make sure you remember the full hash ID.  If you use a branch name (or tag name or other name) to hold the hash ID, that also stops git gc from removing it, since the commit is now find-able by some human-readable name.  This also protects all commits "behind" (earlier than) this commit, since those too are find-able.


text:
Q: In WebGL what are the differences between an attribute, a uniform, and a varying variable? Is there an analogy that I can think of when comparing these different types, or how these things work?
Also, what does uniforming a matrix mean?

A: *

*uniform are per-primitive parameters (constant during an entire draw call) ;

*attribute are per-vertex parameters (typically : positions, normals, colors, UVs, ...) ;

*varying are per-fragment (or per-pixel) parameters : they vary from pixels to pixels.

It's important to understand how varying works to program your own shaders.
Let's say you define a varying parameter v for each vertex of a triangle inside the vertex shader. When this varying parameter is sent to the fragment shader, its value is automatically interpolated based on the position of the pixel to draw.
In the following image, the red pixel received an interpolated value of the varying parameter v. That's why we call them "varying".

For the sake of simplicity the example given above uses bilinear interpolation, which assumes that all the pixels drawn have the same distance from the camera. For accurate 3D rendering, graphic devices use perspective-correct interpolation which takes into account the depth of a pixel.

A:
In WebGL what are the differences between an attribute, a uniform, and a varying variable?

In OpenGL, a "program" is a collection of "shaders" (smaller programs), which are connected to each other in a pipeline.
// "program" contains a shader pipeline:
//   vertex shader -> other shaders -> fragment shader
//
const program = initShaders(gl, "vertex-shader", "fragment-shader");
gl.useProgram(program);

Shaders process vertices (vertex shader), geometries (geometry shader), tessellation (tessellation shader), fragments (pixel shader), and other batch process tasks (compute shader) needed to rasterize a 3D model.
OpenGL (WebGL) shaders are written in GLSL (a text-based shader language compiled on the GPU).
// Note: As of 2017, WebGL only supports Vertex and Fragment shaders

<!-- Vertex Shader -->
<script id="shader-vs" type="x-shader/x-vertex">

  // <-- Receive from WebGL application
  uniform vec3 vertexVariableA;

  // attribute is supported in Vertex Shader only
  attribute vec3 vertexVariableB;

  // --> Pass to Fragment Shader
  varying vec3 variableC;

</script>

<!-- Fragment Shader -->
<script id="shader-fs" type="x-shader/x-fragment">

  // <-- Receive from WebGL application
  uniform vec3 fragmentVariableA;

  // <-- Receive from Vertex Shader
  varying vec3 variableC;

</script>

Keeping these concepts in mind:
Shaders can pass data to the next shader in the pipeline (out, inout), and they can also accept data from the WebGL application or a previous shader (in).

*

*The Vertex and Fragment shaders (any shader really) can use a uniform variable, to receive data from the WebGL application.
// Pass data from WebGL application to shader
const uniformHandle = gl.glGetUniformLocation(program, "vertexVariableA");
gl.glUniformMatrix4fv(uniformHandle, 1, false, [0.1, 0.2, 0.3], 0);

*The Vertex Shader can also receive data from the WebGL application with the attribute variable, which can be enabled or disabled as needed.
// Pass data from WebGL application to Vertex Shader
const attributeHandle = gl.glGetAttribLocation(mProgram, "vertexVariableB");
gl.glEnableVertexAttribArray(attributeHandle);
gl.glVertexAttribPointer(attributeHandle, 3, gl.FLOAT, false, 0, 0);

*The Vertex Shader can pass data to the Fragment Shader using the varying variable. See GLSL code above (varying vec3 variableC;).

A: Copied directly from http://www.lighthouse3d.com/tutorials/glsl-tutorial/data-types-and-variables/. The actual site has much more detailed information and would be worthwhile to check out.

Variable Qualifiers
Qualifiers give a special meaning to the variable. The following
  qualifiers are available:

*

*const – The declaration is of a compile time constant.

*attribute – Global variables that may change per vertex, that are passed from the OpenGL application to vertex shaders. This qualifier
  can only be used in vertex shaders. For the shader this is a
  read-only variable. See Attribute section.

*uniform – Global variables that may change per primitive [...], that are passed from the OpenGL
  application to the shaders. This qualifier can be used in both vertex
  and fragment shaders. For the shaders this is a read-only variable.
  See Uniform section.

*varying – used for interpolated data between a vertex shader and a fragment shader. Available for writing in the vertex shader, and
  read-only in a fragment shader. See Varying section.

As for an analogy, const and uniform are like global variables in C/C++, one is constant and the other can be set. Attribute is a variable that accompanies a vertex, like color or texture coordinates. Varying variables can be altered by the vertex shader, but not by the fragment shader, so in essence they are passing information down the pipeline.

A:
Uniforms are another way to pass data from our application on the CPU to the shaders on the GPU, but uniforms are slightly different compared to vertex attributes. First of all, uniforms are global. Global, meaning that a uniform variable is unique per shader program object, and can be accessed from any shader at any stage in the shader program. Second, whatever you set the uniform value to, uniforms will keep their values until they're either reset or updated

I like the description from https://learnopengl.com/Getting-started/Shaders , because the the word per-primitive is not intuitive


text:
Q: Unable to parse template "Class" Error whenever I try to open a new java class I'm doing an Android Studio project (from this tutorial here: http://www.kilobolt.com/day-2-setting-up-libgdx.html).
When I press New Java Class I'm getting the error that's described in the title:

Unable to parse template "Class" Error message: This template did not
  produce a Java class or an interface.

I don't know why. I've searched on this site, there doesn't seem to be an answer.
There are No error messages in the code.
For what it is worth, I recently updated the gradle version for android studio before.
Anyone know how to fix this?


text:
Q: jquery array json push multidimensional I need to create json to jquery on the fly.
Entering page content balances the database.
The tag automatically generates an insertion in several databases ...
I'm stuck on the generation of the multidimensional array
expected result : {"rh" : [{"name":"me"}, {"surname":"doe"}]}

input db = rh
input name => name and surname
input val => me and doe

html :

    Prénom

        <input id="rh_prenom" name="rh_pid" what="prenom" db="rh" type="text" class="form-control" placeholder="Prénom de la ressource..." />

    Date de naissance

        <input id="rh_prenom" name="rh_pid" what="date_naissance" db="rh" type="text" class="form-control" placeholder="yyyy-mm-dd" data-date-format="yyyy-mm-dd" data-provide="datepicker" data-date-autoclose="true" />

js :
$("[name='" + who + "']").each(function (index) {
    console.info(index + ": " + $(this).attr("what") + " :: " + $(this).val() + " | " + $(this).attr("db"));

    var what = $(this).attr("what");
    var db = $(this).attr("db");
    var item = {};

    item[what] = $(this).val();
    jsonObj.push(item);
});


text:
Q: VM azure and web application in same network I'm setting up my environment in azure and I´d to know how I can put my VM on the same network as my application server (web sites)?
Currently, there is a big latency between my database (on VM) and my application (on web sites).

A: You can connect Azure Web Applications to VNETs - the best practice is to make sure they are in the same data center.
You're still going to have some latency (more than what you would on your local dev machine) - but as long as they are in the same datacenter region (EAST US, etc), that should minimize latency.
Your database should also not be open to the public (best practices here), and a VNET would solve this problem.

A: You can add them to the same Virtual Network, to add a VM to a virtual network in the old portal remember to choose to "Create from gallery" as that is the only place where you can choose virtual network.
In the new portal you can add a website to the Virtual Network when opening the website.
One point worth remembering is that it is a VIRTUAL network, but as it used to be with affinity groups a VNET should make sure that your servers are located "close by"


text:
Q: Converting number to decimal when given both I have 2 columns: price and dec. As shown in this sample dataframe:
price  dec
505    2
300    2
680    3
100    2

What I'd like to do is make another column that takes the price and decimal and then converts it like so:
price  dec  realprice
505    2    5.05
300    2    3.00
680    3    .680
100    2    1.00

How do I make a function that does this?

A: Using div with **
df.price.div(10**df.dec)
Out[510]:
0    5.05
1    3.00
2    0.68
3    1.00
dtype: float64

A: Just divide the columns and use powers of 10:
df['realprice'] = df['price']/(10**df['dec'])

Yields:
   price  dec  realprice
0    505    2       5.05
1    300    2       3.00
2    680    3       0.68
3    100    2       1.00


text:
Q: Wireless earphones connection I accidentally deleted my bluetooth speakers from my macbooks devices list. Now it will not show up again. How can I get it to show up again so I can reconnect it?

A: Hold the bluetooth pairing button on your bluetooth speakers for about 3-5 seconds (typically until some audible cue is played). Then you should be able to pair it with your MacBook again in bluetooth preferences.


text:
Q: How to test that block is run on a CoroutineDispatcher if it's invoked via launch(dispatcher) {...} We've recently started using coroutines on our Android application. All's gone fine and dandy, until someone wrote something roughly equivalent to the following function:
fun example(dispatcher: CoroutineDispatcher, block: () -> Unit) {
    launch(dispatcher) {
        block()
    }
}

We'd like to write a test that verifies that block is executed using dispatcher.
We've tried the following, but this doesn't work because we get a NullPointerException because dispatcher.parentContext is not mocked. I'm loathe to mock it, because we don't care what context it's executed in, just that it's executed:
@Test
fun `test that doesn't work`() {
    val dispatcher: CoroutineDispatcher = mock()
    val block: () -> Unit = mock()

    // fails here, specifically on the call to `launch` in example()
    example(dispatcher, block)

    val captor = argumentCaptor<Runnable>()
    verify(dispatcher).dispatch(any(), captor.capture())
    verify(block, never()).invoke()

    captor.firstArgument.run()
    verify(block).invoke()
}

We've come upon this as an option, but it still doesn't feel right:
@Test
fun `test that works but doesn't feel right`() {
    val executor: ExecutorService = mock()
    val block: () -> Unit = mock()

    example(executor.asCoroutineDispatcher(), block)

    val captor = argumentCaptor<Runnable>()
    verify(executor).execute(captor.capture())
    verify(block, never()).invoke()

    captor.firstArgument.run()
    verify(block).invoke()
}

Can anyone come up with anything better?
EDIT:
Notable dependencies are as follows:
com.nhaarman:mockito-kotlin:1.5.0
org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5
junit:junit:4.12
org.jetbrains.kotlin:kotlin-stdlib:1.2.30

A: Since launch returns a Job, you need to wait for its completion to be able to verify anything that has been done.
You can do that in two ways:
Since you are launching a coroutine, your actual unit test might be finished before the launch's execution is done. You need to wait for its execution to make sure your test does not finish early. You can do that in multiple ways.

*

*Change your function signature to return the Job from launch (e.g.fun example(dispatcher: CoroutineDispatcher, block: () -> Unit) = launch(dispatcher) { .... This way you can call .join() on the example function to wait for its completion.

*Keep an internal var exampleJob:Job? = null, and set it using the execution of launch, e.g. exampleJob = launch { ...}. This way, in your tests, you can use exampleJob.join() to wait for its completion and do your verifications afterwards.

Bonus solution:
You can also use MockK to verifyWithTimeout your unit-test. This way, your unit test waits for the verification to finish.


text:
Q: How to visualize some terms in direct product? I have difficulty in understanding few terms when i have to deal with direct product of groups. Let $G = A \times B$ be a group which is a direct product of two groups $A$ and $B$. It is easy to visualize the elements of $G$ as of the form $(a,b)$ where $a \in A$ and $b \in B$.
Question 1 :  How to visualize $\text{Cent}_G(B)$?
Question 2 : How to visualize elements of $B$ in $A \times B$?
Question 3 : How to visualize $G/A$?

A: It is easiest to answer question 2 first. If we write $1_A$ for the identity element in the group $A$, then you can think of an element $b \in B$ as being the element $(1_A,b) \in G$.
Next, question 3 is related to question 2. It is a standard fact that $G/A \cong B$. The isomorphism is given by $\overline{(a,b)} \mapsto b$, where the "bar" denotes the equivalence class in the quotient. From the discussion in question 2 above, you can identify $a \in A$ with $(a,1_B) \in G$. Then you can see that $\overline{(a,b)} = \overline{(1_A,b)}$, since they differ by multiplication by the element $(a^{-1},1_B)$.
Lastly, let's look at question 1. The centralizer of $B$ is the set of all elements that commute with any element in $B$. Again by our previous discussion, we identify $B$ with $1_A \times B \subset G$. So a generic element in $B \subset G$ looks like $(1_A,b)$. If $(\alpha,\beta)$ is in the centralizer of $B$, then we have for any $b$:
$$
\begin {align*}
(1_A,b)(\alpha,\beta) &= (\alpha,\beta)(1_A,b) \\
(\alpha,b\beta) &= (\alpha,\beta b)
\end {align*}
$$
You see that it doesn't really matter what $\alpha$ is. All you need is that $b \beta = \beta b$ for all $b$, or in other words, $\beta \in Z(B)$ (the center of $B$). So $\mathrm{Cent}_G(B) = A \times Z(B)$.


text:
Q: Why are anti-diagonal / persymmetric matrices not as important as diagonal / symmetric matrices? Diagonal matrices and diagonalizability are key topics in linear algebra as well as numerical linear algebra. Likewise, symmetric matrices have lots of nice properties that make them widely studied and important both theoretically and computationally.
However, anti-diagonal matrices seem to be no more than a curiosity in matrix algebra. While symmetry along the main diagonal seems to count for so much, persymmetry does not seem to count for very much at all.
Is there a reason for this? After all (and this might sound naive) why should one diagonal (left to right) matter so much more than the other one? Is this an artifact / convention arising from the development of matrix algebra or does it reflect something deeper.
Or, are anti-diagonal and per-symmetric matrices of far greater importance than I think?
I was thinking about this and was not really able to come up with anything close to a satisfactory answer.

A: I don't know how satisfying this answer will be, but I'll give it a shot anyway.  The punchline, I think, is that although these "diagonal properties" have just as much aesthetic appeal as their "anti-diagonal" counterparts, the diagonal properties happen to give us information that is more useful for a matrix as it is used mathematically.  That is, diagonal symmetry is a more natural thing to look for in the context of linear algebra.
First of all, note that all of these properties are properties of square (that is, $n \times n$) matrices, which are implicitly linear maps from $\Bbb F^n$ to $\Bbb F^n$ (that is, they produce vectors of $n$ entries from vectors of $n$ entries).
The properties that we really care about in linear algebra are the ones that tell us something about how matrices interact with vectors (and ultimately, with other matrices).
Diagonal Matrices
Diagonal matrices are important because they describe a particularly nice class of linear transformations.  In particular:
$$
\pmatrix{d_1\\&d_2\\&&\ddots \\ &&& d_n} \pmatrix{x_1\\ x_2\\ \vdots \\ x_n} =
\pmatrix{d_1 x_1\\ d_2 x_2\\ \vdots \\ d_n x_n}
$$
I would say that what a diagonal matrix represents is the fact that each of the $n$ variables required to specify a vector are decoupled.  For example, in order to find the new $x_2$, one only needs to look at the old $x_2$, and do what the matrix says.
When we "diagonalize" a matrix, we're finding a way to describe each vector (that is, $n$ independent "pieces of information") that are similarly decoupled as far as the transformation is concerned.  So, for example, the matrix
$$
A = \pmatrix{0&1\\4&0}
$$
takes a vector $x = (x_1,x_2)$ and produces a new vector $Ax = (x_2,2x_1)$.  There's a nice symmetry to that; in particular, applying $A$ twice gives us the vector $A^2 x = (2x_1,2x_2)$, which is to say that $A$ acts like a diagonal matrix whenever you apply it an even number of times.
However, I would argue that we get a clearer picture of what $A$ does if we diagonalize it.  In particular, if we write a vector as $x = a_1(1,2) + a_2(1,-2)$, $A$ gives us the new vector
$$
Ax = a_1 A(1,2) + a_2 A(2,1) = 2a_1(1,2) - 2a_1(1,-2)
$$
In particular, one we know the two pieces of information $a_1$ and $a_2$, we can figure out the new vector using these pieces separately, without having them interact.
So, we see that this antidiagonal $A$ is nice, but just not nearly as simple as the "diagonal version" of the transformation.
Symmetric matrices
Symmetric matrices are particularly nice when we care about dot-products. Dot products are needed whenever you want to think about the angle between vectors in some capacity.
In particular: if we define the dot-product
$$
(x_1,\dots,x_n) \cdot (y_1,\dots,y_n) = x_1y_1 + \cdots x_n y_n
$$
Then a symmetric $A$ will have the property that
$$
(Ax) \cdot y = x \cdot (Ay)
$$
Ultimately, this whole thing connects back to diagonal matrices since every symmetric matrix can be diagonalized in the sense described above.  The fact that this can be done is known as the spectral theorem.
Persymmetric matrices, however, don't act in a particularly nice way with respect to any usual operations (like the dot product).

A: $\newcommand{\dd}{\partial}$If $A$ is an $n \times n$ matrix, and if $x$ and $y$ are columns satisfying $y = Ax$, then the $(i, j)$-entry of $A$ measures the "sensitivity" of $y_{i}$ to changes in $x_{j}$. Precisely, if every variable except $x_{j}$ is held constant, then a change of $\Delta x_{j}$ in $x_{j}$ changes $y_{i}$ by $A_{ij}y_{i}$. (This is immediate from the definition of matrix multiplication, and explains why the derivative matrix of a vector-valued function of $n$ variables has the partial derivative $\dd y_{i}/\dd x_{j}$ in the $(i, j)$ entry.)
To say $A$ is diagonal is to say $y_{i}$ depends only on $x_{i}$, the variable with the same index. This condition is invariant under relabeling variables. By contrast, anti-diagonality is not invariant under relabeling.
I don't know of a similarly naive reason that symmetry is so important, but naturally the spectral theorem for matrices guarantees a symmetric matrix is orthogonally diagonalizable; that is, up to a rotational change of variables, $A$ is diagonal.


text:
Q: The set of left cosets, homogeneous space, and homotopy group Here are statements that I attempt to make sure I am doing things on the right track.
Below we take $N=3$ for all $N$.

*

*Consider the group:

$$G=\frac{SU(N)_A \times SU(N)_B \times U(1)}{(\mathbb{Z}_N)^2},$$

this group can be understood as a triplet
$$(g_A, g_B, e^{i \theta}) \in SU(N)_A \times SU(N)_B \times U(1),$$
such that
$(e^{i \frac{2\pi}{N}}, 1, e^{-i \frac{2\pi}{N}})$ is the first $\mathbb{Z}_N$ generator mod out in $G$, while $(1,e^{i \frac{2\pi}{N}}, e^{-i \frac{2\pi}{N}})$ is the second $\mathbb{Z}_N$ generator mod out in $G$. Namely (1) the center of $SU(N)_A$, (2) the center of $SU(N)_B$ and (3) the $e^{i \frac{2\pi}{N}}\in U(1)$ overlap, thus we only mod out the twice redundant $(\mathbb{Z}_N)^2$.
Now consider the subgroup $H$ of the $G$ as:

$$H=\frac{SU(N)_{A,B}}{\mathbb{Z}_N}\times \mathbb{Z}_2,$$

where
this group can be understood as a doublet
$(g_{A,B}, g_1) \in SU(N)_{A,B}\times \mathbb{Z}_2= (SU(N)_{A,B}, \{\pm 1 \}) =H \subset G,$
where there is a one-to-one correspondence between
$$(g_{A,B}, g_1) \in H$$ and $$(g_{A,B},g_{A,B}^*, g_1) \in G$$ with $g_{A,B}=g_A=g_B^*$, where $g_B^*$ means the complex conjugation (without the transpose $T$) of $g_B $.
Finally, we need $\frac{SU(N)_{A,B}}{\mathbb{Z}_N}$ to mod out ${\mathbb{Z}_N}$, where we consider
$(g_{A,B}',g_{A,B}'^*)=(e^{i \frac{2\pi}{N}},e^{-i \frac{2\pi}{N}})\mathbb{I} \in {\mathbb{Z}_N}$;  this particular rank-$N$ diagonal matrix is the ${\mathbb{Z}_N}$ we modded out .
We have that
$$\frac{SU(N)_{A,B}}{\mathbb{Z}_N} \subset  SU(N)_A \times SU(N)_B, $$
$$ \mathbb{Z}_2 = \{\pm 1 \} \subset U(1). $$
So this explains how $H$ is embedded as a subgroup in $G$.
Question:

*

*What is the precise topological space of the set of left coests
  $$
G/H=\frac{\frac{SU(N)_A \times SU(N)_B \times U(1)}{(\mathbb{Z}_N)^2}}{\frac{SU(N)_{A,B}}{\mathbb{Z}_N}\times \mathbb{Z}_2}?
$$
  Is this certain smooth homogeneous space like a sphere or a complex/real projective space?

*What is the homotopy group?
  $$
\pi_j(G/H)=?,
$$
  for $j=1,2,3,4,5$.

Some background info that I made attempt and showed for your free use:
(1). $\pi_i(U(N))=\pi_i(\frac{SU(N)\times U(1)}{\mathbb{Z}_N})$:
$$\pi_m(U(N))=\pi_m(SU(N)), \text{ for } m \geq 2$$
$$\pi_1(U(N))=\mathbb{Z}, \;\;\pi_1(SU(N))=0,$$
(2). $\pi_1(\mathbb{Z}_N)=\mathbb{Z}_N$ and $\pi_i(\mathbb{Z}_N)=0$ for $i\geq 2$.

A: This is not a complete answer, since on the one hand, I think there is a small error in your question and second the various quotients by centers got too complicated for me. (They only lead to some finite coverings and thus quotients in $\pi_1$ and isomorphisms in the higher $\pi_i$'a anyway.) What I think is an error in your question is that you can view
$$\{(g,g^*):g\in SU(N)\}$$ as a subgroup in $SU(N)\times SU(N)$ since $$(gh)^*=h^*g^*$$ but not $g^*h^*$.
But for any Lie group you can take $G\times G$ and naturally view $G$ as the diagonal subgroup $\Delta:=\{(g,g):g\in G\}\subset G\times G$. As one may expect naively, the quotient $(G\times G)/\Delta$ is diffeomorphic to $G$ itself. (This is the standard way to view a Lie group as a symmetric space.) Explicitly, this diffeomorphism can be seen by considering the left action of $G\times G$ on $G$ defined by $(g,h)\cdot\tilde g:=g\tilde gh^{-1}$. Denoting by $e$ the neutral element of $G$, you see that $(g,e)\cdot e=g$, so the action is transitive and that $(g,h)\cdot e=e$ if and only if $gh^{-1}=e$ and hence $g=h$. Thus the isotropy group is $\Delta$ and hence $G\cong (G\times G)/\Delta$.
I am sure that a small adaption of this construction can be used to identify the homogeneous space you are interested in with something that is close to $U(N)$ or $SU(N)$, which should also allow identifying the homotopy groups.


text:
Q: Double free error on fclose() on previously closed file handle I have a class that contains file handle fHandle that points to an open file. Now, it can be closed by any one of the multiple routines and that is based on dynamic run of the program.
To be sure that a file is indeed closed, I put simple snippet in my destructor: if(fHandle!=NULL) fclose(fHandle);. Turns out, if one of the routines had previously closed this file, then the running the destructor snippet causes double free operation and I get **glib detected** error message.
How do I make sure that I don't close the file handle that has previously been closed (apart from putting NULL check)?

A: fclose doesn't set the fhandle to NULL. So, after calling fclose if you set the fhandle to NULL explicity it should solve your problem.
Your code should be something like below:
if(NULL != fhandle)
{
   fclose(fhandle);
   fhandle = NULL;
}

Note: This solution will not work if your function that calls close is called from multiple threads.

A: You say you've tried:
if(fHandle!=NULL) fclose(fHandle);

To avoid a double fclose(), just set fHandle to NULL whereever else you may call fclose on that handle, so the above code in the destructor won't pass the conditional test....

A: Is this specifically C or C++. One easy fix for your latter issue to use a seperate flag to check if the file is closed or not? Something like this
void CloseFile(){
  if(flag ==0){
    fclose(fHandle);
      flag =1;
  }
}

If this is for c++ you can encapsulate the file handle inside a class and use RAII to automatically call the close just once by adding that call in the class's destructor. You could also (not recommended) not do RAII and merely encapsulate the flag within the same class if you want to go that way, and call close manually.


text:
Q: Assembly string instructions register DS and ES in real mode I have been studying this assembly program from my book and I have a question about it. The purpose of this program is to simply copy string1 to string2. My question relates to the following two instructions:
mov    AX,DS
mov    ES,AX

I see without them, the program doesn't work properly, but I would have thought by pointing ESI to string1 and EDI to string2, that would be all you need to do. Then just increment ESI and EDI and move it character by character. What exactly does DS hold and why do we need to move it to ES?
.DATA
string1    db    'The original string',0
strLen     EQU   $ - string1
.UDATA
string2    resb    80
.CODE
    .STARTUP
    mov    AX,DS          ; set up ES
    mov    ES,AX          ;  to the data segment
    mov    ECX,strLen     ; strLen includes NULL
    mov    ESI,string1
    mov    EDI,string2
    cld                   ; forward direction
    rep    movsb

A: All the string instructions that use EDI use ES:EDI.  (or di or rdi)
Explicit addressing modes using EDI (like [edi]) default to DS, but movs/stos/scas/cmps (with/without rep/repz/nz) all use es:edi.  lods only uses ds:esi.  (rep lods "works", but is rarely useful.  With cx=0 or 1 it can work as a slow conditional load, because unlike loop, rep checks cx before decrementing.)
Note that even though scas is read-only, it uses (r|e)di.  This makes it work well with lods: load from one array with lods, the scas to compare against a different array.  (Optionally with some kind of processing of (r|e)ax before the compare).

Normally when you can use 32-bit addresses, you have a flat memory model where all segments have the same base and limit.  Or if you're making a .COM flat binary with NASM, you have the tiny real-mode memory model where all segments have the same value.  See @MichaelPetch's comments on this answer and on the question.  If your program doesn't work without setting ES, you're doing something weird.  (like maybe clobbering es somewhere?)
Note that rep movsb in 16-bit mode without an address-size prefix uses CX, DS:SI, and ES:DI, regardless of whether you used operand-size prefixes to write edi instead of di.

Also note that rep string instructions (and especially the non-rep versions) are **often not the fastest way to do things.  They're good for code-size, but often slower than SSE/AVX loops.
rep stos and rep movs have fast microcoded implementation that store or copy in chunks of 16 or 32 bytes (or 64 bytes on Skylake-AVX512?).  See Enhanced REP MOVSB for memcpy.  With 32-byte aligned pointers and medium to large buffer sizes, they can be as fast as optimized AVX loops.  With sizes below 128 or 256 bytes on modern CPUs, or unaligned pointers, AVX copy loops typically win.  Intel's optimization manual has a section on this.
But repne cmpsb is definitely not the fastest way to implement memcmp: use SSE2 or AVX2 SIMD compares (pcmpeqb), because the microcode still only compares a byte at a time.  (Beware of reading past the end of the buffer, especially avoid crossing a page (or preferably cache line) boundary.)  Anyway, repne / repe don't have "fast strings" optimizations in Intel or AMD CPUs, unfortunately.