text:
Q: Ruby YAML Multiple Documents Here is my YAML file, 'test.yml':
---
alpha: 100.0
beta: 200.0
gama: 300.0
--- 3
...

The first document is a hash.
The second document is an integer.
I am trying to load these to a Ruby program as a hash and an integer.
Here is my current attempt:
require 'yaml'

variables = YAML.load_file('test.yml')
puts variables.inspect

A: The Tin Man is correct that the OP should not be using multiple documents for his specific problem; however, the situation of multiple documents in a YAML stream does occur in practice, for example when multiple YAML documents are appended to a single file, so it's worth knowing how to deal with it.
require 'yaml'

yaml = <<EOT
---
alpha: 100.0
beta: 200.0
gama: 300.0
---
int: 3
...
EOT

loop do
  puts YAML.load(yaml)
  break if !yaml.sub!(/(?<!#)(-{3}.+?(?=-{3})\n?){1}/m,'')
  break if yaml.empty?
end

# >> {"alpha"=>100.0, "beta"=>200.0, "gama"=>300.0}
# >> {"int"=>3}

A: To access multiple YAML documents in a single file, use the load_stream method (as already mentioned by "matt" in a comment to one of the other answers):
YAML.load_stream(File.read('test.yml')) do |document|
  puts document
end

A: Don't use multiple documents; They're not a substitute for defining individual elements in your data:
require 'yaml'

yaml = <<EOT
---
hash:
  alpha: 100.0
  beta: 200.0
  gama: 300.0
int: 3
EOT

YAML.load(yaml)
# => {"hash"=>{"alpha"=>100.0, "beta"=>200.0, "gama"=>300.0}, "int"=>3}

You can access the contents by assigning YAML.load(yaml) to a variable:
data = YAML.load(yaml)
data['hash'] # => {"alpha"=>100.0, "beta"=>200.0, "gama"=>300.0}
data['int'] # => 3

Think of it this way, you're asking for an object of some sort from YAML after it parses the YAML file. You need to be able to extract specific values from it, so make it easy on yourself and define an array or a hash that contains what you want, in a way that works the way your brain does, within YAML's limitations and specs.
If I'm going to be creating a complicated structure, I do it in Ruby first and have YAML dump the format for me:
require 'yaml'

data = {
  "hash" => {
    "alpha" => 100.0,
    "beta" => 200.0,
    "gama" => 300.0
  },
  "int" => 3
}

puts data.to_yaml

# >> ---
# >> hash:
# >>   alpha: 100.0
# >>   beta: 200.0
# >>   gama: 300.0
# >> int: 3

I can put the Ruby code into a script and run it, redirecting it to a YAML file:
ruby test.rb > test.yaml

Then I can expand the structure:
require 'yaml'

data = {
  "hash" => {
    "alpha" => 100.0,
    "beta" => 200.0,
    "gama" => 300.0
  },
  "int" => 3,
  "array" => %w[a b c]
}

puts data.to_yaml

# >> ---
# >> hash:
# >>   alpha: 100.0
# >>   beta: 200.0
# >>   gama: 300.0
# >> int: 3
# >> array:
# >> - a
# >> - b
# >> - c

Testing it round-trip:
require 'yaml'

yaml = <<EOT
---
hash:
  alpha: 100.0
  beta: 200.0
  gama: 300.0
int: 3
array:
- a
- b
- c
EOT

YAML.load(yaml)
# => {"hash"=>{"alpha"=>100.0, "beta"=>200.0, "gama"=>300.0}, "int"=>3, "array"=>["a", "b", "c"]}

Iteratively do that until you're comfortable with YAML syntax, then you can build/tweak your YAML file by hand.
Now, here's how smart it is. The YAML spec supports aliases, which let us define a variable, then reuse it multiple times using & and * respectively. Creating those by hand is a pain when your document gets large, but the YAML driver is smart and will output them for you:
require 'yaml'

FOO = ['foo']
BAR = ['bar']

foobar = [FOO, BAR]

data = {
  "foo" => FOO,
  'bar' => BAR,
  'foobar' => foobar,
}

puts data.to_yaml

# >> ---
# >> foo: &1
# >> - foo
# >> bar: &2
# >> - bar
# >> foobar:
# >> - *1
# >> - *2

foo: &1 defines ["foo"], and gets reused at the bottom as *1.
"Yaml Cookbook at the YamlForRuby site" is a great reference for working with YAML.


text:
Q: Session[counter].open(options) does not work. Is there a workaround? I really need to have a Sessionarray that i can open with my options. I tried this code but all it does is throw a nullreferenceexception. I found out that this exception is only thrown when i use a session array.
 Session[] sessions = new Session[(int)counter];

  sessions[(int)counter].Open(options);

Midway I thought, maybe there was no Session at the index existing so i did this
Session[] sessions = new Session[(int)counter];
 Session session1 = new Session();
sessions[(int)counter]= session1;
      sessions[(int)counter].Open(options);

it still didn't work.
What can i do to make this work. Please Help. I don't understand the concept of Session["something"] since it doesn't really work when creating a Session[]

A: what kind of project? which Session-class?
I guess you will not need an Session-array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No 'apply now' button for careers, using iPad Air/iOS 7.0.6 Browsing for (junior) JavaScript jobs on careers (hint, hint…) I found a few that I'd like to apply to, but browsing the job page there seems to be no way to actually apply (for clarity this applies to iPad Air/iOS 7.0.6) for positions, due to the lack of an 'apply now' button:
iPad Air/iOS 7.0.6:

iPhone 4s/iOS 7.0.6:

Nexus 7 (original model, Android KitKat):

Link to actual job page (though it's true of all job pages that I've browsed on iPad): http://careers.stackoverflow.com/jobs/45651/javascript-developer-dotmailer?a=TFVhlEhW&searchTerm=JavaScript
Incidentally, I have previously flagged this problem via the in-page 'report a problem' facility (around, or slightly before, 17/02/2014) and received this response:

Hi David,
Thanks for showing your interest in this position:
  http://careers.stackoverflow.com/jobs/485341
You should be able to see the "apply now" button at the bottom of this job listing.
  Can you try a different browser if you aren't able to see that?
Cheers,
  (Name removed, since I don't think it's fair to potentially embarrass someone)

1: Note that this is an entirely different job, though it shows the same behaviour.

A: Official answer incoming:
We don't really support applying for listing on mobile devices (phones and tablets). On phones, the site should default to the mobile theme (which hides all application functionality) and this illustrates a reason why we should do so on tablets as well.
Currently applying form a mobile device is in the "if it works, it works, but we don't explicitly support it" realm.
I am not a dev, but I could have sworn part of that reason was the way iOS handles documents. Android should fare better but I don't have a device I can test it with.
So in regards to your issue, this may be a bug in the classic sense, but it's not a bug we're prepared to spend time fixing since we don't support mobile application anyway.
I've marked it as status-deferred for now. While we have no immediate plans to allow mobile applications, we'll probably have to revisit this issue on the future since we've started releasing our own SE mobile apps.


text:
Q: Is the natural map $f^* f_* \mathcal{F} \to \mathcal{F}$ surjective? I'm trying to solve Exercise III 12.4 from Hartshorne's Algebraic geometry. There is a flat projective morphism $f: X \to Y$ of schemes of finite type over an algebraically closed field $k$. Also $Y$ is assumed to be integral, and all fibers are integral schemes.
Now suppose $\mathcal{F}$ is an invertible sheaf on $X$, that is trivial on each fiber $X_y$. I was able to show that $f_*\mathcal{F}$ is an invertible sheaf on $Y$ (this is essentially Cor 12.9), and now I would like to show that the natural map $f^*f_* \mathcal{F} \to \mathcal{F}$ is an isomorphism, for which it is enough to show that it is surjective, because both sheaves are locally free.

A: Since whether $f^*f_*\mathcal{F}\to\mathcal{F}$ is surjective is a local condition, we can check it on a cover $X$ by open subsets of the form $f^{-1}(U)$ where $U\subset Y$ is open and $f_*\mathcal{F}|_U$ is free. So it suffices to treat the case where $Y=\operatorname{Spec} R$ is affine and $f_*\mathcal{F}=\mathcal{O}_Y$.
Now let's recall some facts about the natural map $f^*f_*\mathcal{F}\to\mathcal{F}$. First, the natural map is the image of $id_{f_*\mathcal{F}}\in \operatorname{Hom}_{\mathcal{O}_Y}(f_*\mathcal{F},f_*\mathcal{F})$ under the isomorphism of $\mathcal{O}_Y(Y)=R$-modules given by the adjunction $$\operatorname{Hom}_{\mathcal{O}_Y}(f_*\mathcal{F},f_*\mathcal{F})\cong \operatorname{Hom}_{\mathcal{O}_X}(f^*f_*\mathcal{F},\mathcal{F}).$$
But since $f_*\mathcal{F}=\mathcal{O}_Y$, we have $\operatorname{Hom}_{\mathcal{O}_Y}(f_*\mathcal{F},f_*\mathcal{F})=\operatorname{Hom}_{\mathcal{O}_Y}(\mathcal{O}_Y,\mathcal{O}_Y)=\mathcal{O}_Y(Y)=R$, and $id_{f_*\mathcal{F}}=id_{\mathcal{O}_Y}=1\in R$. On the other hand, the pullback of the structure sheaf is the structure sheaf, so $\operatorname{Hom}_{\mathcal{O}_X}(f^*f_*\mathcal{F},\mathcal{F})=\operatorname{Hom}_{\mathcal{O}_X}(\mathcal{O}_X,\mathcal{F})=\mathcal{F}(X)$, so $\mathcal{F}(X)=R$. As the $R$-linear endomorphisms of $R$ are exactly given by multiplication by an element of $R$, the endomorphisms that are isomorphisms are exactly multiplication by a unit. So we see that $id_{f_*\mathcal{F}}$ must be sent to the map $\mathcal{O}_X\to\mathcal{F}$ which picks out an invertible element of $\mathcal{F}(X)$, that is, a non-vanishing global section. So $\mathcal{F}$ is trivial and the natural map $f^*f_*\mathcal{F}\to\mathcal{F}$ is an isomorphism.


text:
Q: Re-arrange Strings(words) within it's own array in Java public class Main {
public static void main(String[] args) {
    String[] colors = {"black", "yellow", "red", "blue"};
}

How does one flip/move element 3 ("blue") to element 0 ("black") in Java?
Thanks in advance!


text:
Q: Body scroll with mouse position? Basically, the functionality is here, it just needs some refinement that I don't know how to tweak, I've written this small snippet that does exactly what I want, but doesn't scroll the whole page, it just scrolls the "window" size.
Can anyone take this and make it amazing? :)
$(document).mousemove(function(e){
        percent = ((e.pageY) * 100) / $(this).height();
        $('body,html').scrollTop( percent);
});

A: Something similar to this? http://jsfiddle.net/zcVL7/4/
I condensed the JS a little, but you had most of it:
$(document).mousemove(function(e) {
    var percent = e.clientY / $(window).height();
    $('body, html').scrollTop($(document).height() * percent);
});

A: You may rather want to have a delta depending on how far the offset of mouse is with respect to the middle of the page: http://jsfiddle.net/BYUdS/2/. That way, you can keep scrolling down so that there is no scroll limit (what you have now).
$(document).mousemove(function(e) {
    $("html, body").scrollTop(function(i, v) {
        var h = $(window).height();
        var y = e.clientY - h / 2;
        return v + y * 0.1;
    });
});

Here's a version that performes smoother: http://jsfiddle.net/BYUdS/3/.
var $elems = $("html, body");
var delta = 0;

$(document).on("mousemove", function(e) {
    var h = $(window).height();
    var y = e.clientY - h / 2;
    delta = y * 0.1;
});

$(window).on("blur mouseleave", function() {
    delta = 0;
});

(function f() {
    if(delta) {
        $elems.scrollTop(function(i, v) {
            return v + delta;
        });
    }
    webkitRequestAnimationFrame(f);
})();


text:
Q: "var" type inference in C#
Possible Duplicate:
Why does var evaluate to System.Object in "foreach (var row in table.Rows)"?

I was rather suprised to discovered the following today....
SqlDataReader reader = cmd.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();

// the following compiles correctly
foreach (DataRow field in schemaTable.Rows)
{
    Console.WriteLine(field["ColumnName"]);
}

// the following does not compile as 'var' is of type 'object'
foreach (var field in schemaTable.Rows)
{
    // Error: Cannot apply indexing with [] to an expression of type 'object'
    Console.WriteLine(field["ColumnName"]);
}

Whats going on here?
Is this a type inference failure? And if so, what causes it?
Or is it part of the defined behaviour or var? And if so, why?
I thought the idea of var was that you could use it anywhere in a variable declaration/initialisation without changing behaviour.

A: The point here is not var, but the foreach loop. The foreach loop can optionally cast the iterator in addition to iterating itself.
So you can do the following:
List<object> test = new List<object>();
test.Add(1);
test.Add(2);
test.Add(3);
foreach( int i in test ){
  i.Dump();
}

So even if the list is of type object, it can be casted to int on the fly inside the foreach.

A: DataTable.Rows returns System.Data.DataRowCollection which is a subclass of InternalDataCollectionBase.
The GetEnumerator memthod on this returns IEnumerator, rather than IEnumerator<DataRows>.
Hence the only type information available is that it returns object, so when you specify you are enumerating DataRow you are adding your own cast, which var does not.

A: The confusion is that foreach(SomeType thing in SomeCollection) doesn't just iterate through the collection, it also attempts a cast to SomeType for each item as it iterates. But with var there's nothing to cast to.


text:
Q: Debugging a Dynamics365 code activity locally I have a Dynamics365 (in the cloud) setup and I am tasked with debugging some of its custom workflow activities that are suspected of not working properly.
As a long-time desktop developer, this whole cloud setup makes it very tricky to do any decent debugging.....
So my code activities all look something like this:
public class MyCustomActivity : CodeActivity
{
    public IOrganizationService OrganizationService { get; private set; }
    public IExecutionContext ExecutionContext { get; private set; }
    public CodeActivityContext ActivityContext { get; private set; }
    public ITracingService TracingService { get; private set; }

    // Bunch of input parameters
    [Input("param1")]
    public InArgument<string> Param1 { get; set; }

    [Input("param2")]
    public InArgument<string> Param2 { get; set; }

    // possibly output parameters

    // main method with all the logic
    protected override void Execute(CodeActivityContext context)
    {
        var serviceFactory = context.GetExtension<IOrganizationServiceFactory>();

        this.ActivityContext = context;
        this.ExecutionContext = context.GetExtension<IExecutionContext>();
        this.OrganizationService = serviceFactory.CreateOrganizationService(ExecutionContext.UserId);
        this.TracingService = context.GetExtension<ITracingService>();

        // actual core of the code activity
    }
}

Very basic, run-of-the-mill code for a Dynamics code activity, I believe.
I was wondering if there's a way (without moving heaven and hell) to create a custom (not really "faked") CodeActivityContext so that I could basically write a little "test app" that would create such a context, instantiate the code activity, and then run its Execute method? This would allow me to actually run and debug the test app, and go through it and see what's going on (and what might be going wrong).
I am aware of the Fake Xrm Easy package by Jordi Montana and have used it in my integration testing (wonderful piece of code!) - but I think that won't really work for me in this scenario, since I need the "real thing" - I need to have a working IOrganisationService primarily, to run the code activity's code and see what it's doing with the Dynamics platform...
Any ideas? Has anyone else attempted to do something like this before??

A: I accomplish this by decoupling the plug-in/activity logic from the plug-in/activity plumbing. The logic lives in its own class and is called from the Execute method. Pass in things you need in your logic like the org service, inputs, etc from the context and inputs. The Execute method usually just has a single line of code that calls these logic methods.
Now in your local console testing app, just reference those logic methods - they only need basic things like the org service and a few parameters, not the whole Context. Architecting your code this way also lets you easily share logic between plugins/activities, since plugins/activities are really just wrappers around your main logic.


text:
Q: Multiple table or many columns? There is a user table which have many fields actually around 120-150. All these have only user_id as the primary key. What is the best approach for the DB design. To have a single table with all these fields or spiting up to many tables. One of my main concern is if I split it into many tables will it affect the performance since it require many JOIN queries to display the data.

A: If you have 100-150 columns, it is likely some of those are repeating groups.  Those should be normalized into their own child tables (PK: user_id, sqn). Review your design. You should normalize to at least 3rd normal form.
Joins are usually very efficient, and in many cases only rows required for the result are joined.  With that many columns, it is unlikely you would ever have to return all the columns, so you would likely be joining a subset of the tables.
You should be concerned with the cost of searching for matches on columns that aren't indexed.  The higher the column number, the more expensive it is to find the column to compare it.  This cost is likely to far outweigh the cost of joining.
The main reasons I use a one-to-one tables are:

*

*Separate large tombstone data from volatile information.

*Separate data with higher security requirements, from more public data.

*Store sub-type data (one to zero-or-one).


text:
Q: Huge String Table in Java I've got a question about storing huge amount of Strings in application memory. I need to load from file and store about 5 millions lines, each of them max 255 chars (urls), but mostly ~50. From time to time i'll need to search one of them. Is it possible to do this app runnable on ~1GB of RAM?
Will
ArrayList <String> list = new ArrayList<String>();

work?
As far as I know String in java is coded in UTF-8, what gives me huge memory use. Is it possible to make such array with String coded in ANSI?
This is console application run with parameters:
java -Xmx1024M -Xms1024M -jar "PServer.jar" nogui

A: A Java String is a full blown object. This means that appart from the characters of the string theirselves, there is other information to store in it (a pointer to the class of the object, a counter with the number of pointers pointing to it, and some other infrastructure data). So an empty String already takes 45 bytes in memory (as you can see here).
Now you just have to add the maximum lenght of your string and make some easy calculations to get the maximum memory of that list.
Anyway, I would suggest you to load the string as byte[] if you have memory issues. That way you can control the encoding and you can still do searchs.

A: The latest JVMs support -XX:+UseCompressedStrings by default which stores strings which only use ASCII as a byte[] internally.
Having several GB of text in a List isn't a problem, but it can take a while to load from disk (many seconds)
If the average URL is 50 chars which are ASCII, with 32 bytes of overhead per String, 5 M entries could use about 400 MB which isn't much for a modern PC or server.

A: Is there some reason you need to restrict it to 1G? If you want to search through them, you definitely don't want to swap to disk, but if the machine has more memory it makes sense to go higher then 1G.
If you have to search, use a SortedSet, not an ArrayList


text:
Q: Button to Trigger Nav-Tab with Twitter Bootstrap This button triggers the next tab to load content, but the tab itself does not switch, it remains on the first tab..

Review

Here is the code for nav nav-tabs:

Shipping

Quantities

Summary

ANY SOLUTION for switching both the tab&content IS APPRECIATED
..perhaps a way to change the button to trigger the next() function in  * bootstrap-tab.js v2.3.1:
  , activate: function ( element, container, callback) {
      var $active = container.find('> .active')
        , transition = callback
            && $.support.transition
            && $active.hasClass('fade')

      function next() {
        $active
          .removeClass('active')
          .find('> .dropdown-menu > .active')
          .removeClass('active')

        element.addClass('active')

        if (transition) {
          element[0].offsetWidth // reflow for transition
          element.addClass('in')
        } else {
          element.removeClass('fade')
        }

        if ( element.parent('.dropdown-menu') ) {
          element.closest('li.dropdown').addClass('active')
        }

        callback && callback()
      }

      transition ?
        $active.one($.support.transition.end, next) :
        next()

      $active.removeClass('in')
    }
  }

A: You could assign your Review button a click handler using jQuery...
JS:
$('#btnReview').click(function(){
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
});

HTML:
Review

Working Demo

A: By changing 'data-toggle' to 'data-trigger' for the triggering link, the following code can trigger any tab with the same HREF attribute, for all triggers with similar markup.
(N.B. Selectors are not optimised, it's just a guide to a more flexible solution)
JS:
$( '[data-trigger="tab"]' ).click( function( e ) {
    var href = $( this ).attr( 'href' );
    e.preventDefault();
    $( '[data-toggle="tab"][href="' + href + '"]' ).trigger( 'click' );
} );

HTML:
Review

A: Using Bootstrap 4
var nextTab;
    $('.nav-link').map(function(element) {
                    if($(this).hasClass("active")) {
                        nextTab = $(this).parent().next('li');
                    }
                })

    nextTab.find('a').trigger('click');

A: It's quite simple with Bootstrap 4 & JQuery,
i'm using this solution:
 $(document).ready(function(){
        activaTab('aaa');
    });

    function activaTab(tab){
        $('.tab-pane a[href="#' + tab + '"]').tab('show');
    };

A: You can with jquery;
JS:
function change_tab(tab_id){

   $(".nav-link").attr("class","nav-link");//clear classes
   $(".tab-pane").attr("class","tab-pane fade");//clear classes

   var tab_content = "#"+tab_id;
   var tab = "#"+tab_id+"-tab";
   $(tab).attr("class","nav-link active show");
   $(tab_content).attr("class"," tab-pane fade active show");
}

HTML :
Review


text:
Q: One-class-only folds tested through GridSearchCV When using GridSearchCV on a custom estimator that is a wrapper on SVC, I get the error:
"ValueError: The number of classes has to be greater than one; got 1 class"
The custom estimator is made to add gridsearch parameters to the estimator and seemed to work fine.
Using the debugger, I found that indeed, a one-class-only train set is given to my estimator, so 2 possibilities arise:

*

*Either the estimator should handle one-class-only set

*Either the GridSearchCV should not give one-class-only set
As I get an error from the SVC.fit call and that it seems that SVC should not receive one-class-only sets, I think it is the 2nd option. However I've looked in the GridSearchCV implementation but I didn't find anywhere where it checks whether there is a one-class-only fold or why it would fail ...
I used the grid search inside a cross validation to do a nested cross validation:
gs = GridSearchCV(clf.gs_clf.get_gs_clf(), parameter_grid, cv=n_inner_splits, iid=False)
gs.fit(*clf.get_train_set(X, y, train_index))

A: As you have already mentioned in your question, the problem is with the cross-validation splits not including the 2nd class data. This is probably due to an imbalance class issue with your data that when performing a stratified n_inner_splits folds, this under-samples class gets missed.
To overcome this, you could try one of the following:
1- Decrease the n_inner_splits according to the percentage of the under sampled class data and the number of instances you have.
2- Instead of passing an integer to the cv parameter of the gridsearch, you could do the splitting your self and pass it an iterable yielding (train, test) data, where you will be sure that the 2 classes are always represented.
3- Generate/acquire more data for this under sampled class.
Check the cv parameter documentation for others way to solve this here.

A: I found the real issue, the documentation of GridsearchCV specifies for the parameter cv:
# For integer/None inputs, if the estimator is a classifier and ``y`` is
# either binary or multiclass, `StratifiedKFold` is used. In all
# other cases, `KFold` is used.

And one-class-only subsets are not possible for StratifiedKFold.
So the solution was for my custom estimator to inherit from the sklearn.base.ClassifierMixin


text:
Q: How to customize Xamarin toasts plugin for iOS? We're working on xamarin forms project. We've used to Toasts Plugin for Xamarin.Forms to display toasts. Mentioned below is the link of plugin - Toasts Plugin for Xamarin.Forms
The plugin is working perfectly on Android but on iOS it is not allowing multi-line texts. We've tried to customize it to achieve this but of no use and limited help available. Please suggest any help or any other  plugins available for displaying toasts messages. Attached is the screen shots :-

A: I also faced this issue and I just dropped this plugin and I'm gonna switch to this one UserDialogs Plugin because it offers a lot more. And we've more help. It also resolved the above mentioned issue.

A: You may modify line 210 in the source
https://github.com/EgorBo/Toasts.Forms.Plugin/blob/master/Toasts.Forms.Plugin.iOS/MessageView.cs
from
        Description.DrawString(descriptionRectangle, DescriptionFont, UILineBreakMode.TailTruncation, UITextAlignment.Left);

to
        Description.DrawString(descriptionRectangle, DescriptionFont, UILineBreakMode.WordWrap, UITextAlignment.Left);


text:
Q: Is it possible to access LocalStorage from App Script? I have an App Script project that uses some config settings. These settings are set in an html service box so they are reflected in LocalStorage and (via google.script.run) in UserProperties.
On start up, the UserProperties appear to be reset so is there a way I can access LocalStorage to get around this and retrieve the correct settings from a previous session?

A: Server side code on Apps SCript can't access LocalStorage on the user web browser as it runs on the Google Servers. You should use client side code.


text:
Q: Capturing events whenever a new thread starts or ends in C# I have a highly multithreaded application , where threads are started from multiple places and i would like to know if i can hook into the running process and just get alerted whenever a new Managed Thread is spawned. I should be able to get the following information

*

*The parent thread

*New thread

*the method from which the new thread is started like <className>.<methodName>
The application is in C# 3.5

A: As far as I know there is no way to detect when a thread starts. The best solution is probably not to create thread directly, but instead do it via a "thread manager" class that will raise an event when it starts a thread.

A: State should be handle within the thread processing logic.
I suggest you create a wrapper class which wraps the thread logic and reports it's status and other items as needed. I created such a class for a multi-threaded application where I could corral the status of the threads and pipe that information to the GUI in a standardized way.
Of course I had the luxury of designing it up front, to which, you may not have.


text:
Q: Extracting linear predictors from general linear model for panel data ( pglm ) I would like to extract linear predictors out of a pglm model.
With a basic glm model, it can be done simply using the command $linear.predictors
#For example

library(plm)
library(pglm)
data(UnionWage)  # from pglm-package
punions <- pdata.frame(UnionWage, c("id", "year"))
punions <- subset(punions, wage > 0)

glm.model <- glm(wage ~ exper + rural + married, data=punions, family = "poisson")
glm.model$linear.predictors

How can I extract or compute linear predictors from a pglm model like
pglm.model <- pglm(wage ~ exper + rural + married, data=punions, model="random", family="poisson")

I hope anybody can help!


text:
Q: Removing objects from an array(Java) I have an owner class, which has an array of owned dogs.
It looks like this:
public class Owner {

    private String ownerName;
    public Dog[] ownedDogs = new Dog[0];
    private int dogCount = -1;

    public Owner(String ownerName) {
        this.ownerName = ownerName;
    }

    public String getName(){
        return ownerName;
    }

    public void assignDog(Dog d) {

        Dog[] newOwnedDogs = new Dog[ownedDogs.length + 1];
        for (int i = 0; i < ownedDogs.length; i++) {
            newOwnedDogs[i] = ownedDogs[i];
        }
        ownedDogs = newOwnedDogs;

        this.ownedDogs[++dogCount] = d;
        makeOwner(this, d);
    }

   private void makeOwner(Owner o, Dog d) {

        if(d.owner !=o) {
            d.owner = o;
        }
    }

    public boolean ownerOfDog(Dog d){
        if (d.getOwner() == this){
            return true;
        } else {
            return false;
        }

    }

    public String toString(){
        return "Name: " + ownerName;
    }

And the dog class looks like this:
public class Dog{
    private String name;
    private String breed;
    private int age;
    private int weight;
    private double tailLength;
    public Owner owner;

    public Dog(String name, String breed, int age, int weight) {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.weight = weight;

    }

    public String getName() {
        return name;
    }

    public String getBreed() {
        return breed;
    }

    public void increaseAge() {
        age++;
    }

    public int getAge() {
        return age;
    }

    public int getWeight() {
        return weight;
    }

    public double getTailLength() {
        if (breed.equalsIgnoreCase("dachshund") || breed.equalsIgnoreCase("tax")) {
            return 3.7;
        } else {
            return weight * (age / 10.0);
        }
    }

    public Owner getOwner(){
        return owner;
    }

    public void setOwner(Owner o) {
        if(this.owner != o) {
            this.owner = o;
            o.assignDog(this);
        }
    }

    public String toString() {
        return "Name: " + name + " Breed: " + breed + " Age: " + age + " Weight: " + weight + " Tail length: " + getTailLength() + " owned by: " + owner;
    }
}

And I am trying to create a method to remove a dog from the array, this is what i currently have:
public void removeDog () {

        System.out.println("Enter the name of the dog?> ");
        String name = input.nextLine();

        Owner o = findOwner(name);
        Dog d = findDog(name);

        if(d == null) {
            System.out.println("Error: no such dog");

        } else {

            //Code to remove dog from o.ownedDogs

        }
            System.out.println(name + " is removed from the register");
    }

Is there a good way to remove objects from an array without manually entering the index of the element? I have seen examples using other data types, but I am a beginner in java, so I am having trouble applying it here.

A: The problem with using an array is removing an object it actually non-trivial, because you must:

*

*Create a new array of size 1 less than the current one

*Find the index of instance

*If not found, stop

*Copy all elements from the old to the new array up to the index

*Copy all elements from the old to the new up array after the index

*Swap out the old for the new array in your instance

That is all "too hard" compared with:
public List<Dog> ownedDogs = new ArrayList<>();

then
ownedDogs.remove(d);

You would need to implement equals() (and hashCode()) in the Dog class.
As a general rule, never use an array when you could use a Collection.

You should probably use Set<Dog> ownedDogs = new HashSet<>(); and make ownedDogs private and provide a getter for it.

A: From a functional perspective, and assuming that as in your example, the Dog's name is a unique identifier, you would produce a new array by filtering the initial array:
ownedDogs = Arrays.stream(ownedDogs)
.filter(dog -> !dog.name.equals(nameToRemove))
.toArray();

A: Arrylists would solve this, It could be implemented something like this
public ArrayList<Dog> ownedDogs=new ArrayList<>();

and use
ownedDogs.remove(index);

unlike regular arrays they can have no defined size and once you remove an object from them the index's will all shift accordingly


text:
Q: Displaying nominal data with a line graph Recently I stumbled across a line graph displaying a contingency table which I found was a very powerfull visualization. In my opinion it is very seldom that nominal data is displayed this way; usually plots like a bar plot, mosaic plot etc. are used (see here or here for example).
To illustrate I provide a) a bar plot, b) a mosaic plot and c) a line plot for the same data. The Titanic data shows the frequencies for the variables Survived (yes vs. no), Sex (males vs. females) and class (1st, 2nd, 3rd and crew). I only included adults in the plots.
a) Bar plot

b) Mosaic plot

c) Line plot

The line graph seems to clearly display what is going on, e.g. more males than females in total, class has a big effect on survival and so does sex, etc. Drawbacks of the line graph I can think of:

*

*The line goes through area were no category exists, e.g. there is nothing between first and second class. But: this seems to highlight what the changes between the categories are. It`s kind of like a piecewise regression which shows the slope between two adjacent categories.

*It is confusing if we would include confidence intervalls here because the ci must not follow the line. But: Mosaic plots can not display ci either.

What are other drawbacks of the line graph here? Considering the rare use of the line graph in this case I guess there must be more. Or am I wrong and line graphs are a legitim/ common way to display nominal data?

A: Remove the lines and make the shapes larger and you'd have a "dot plot". I'd say that is a common way of visualizing this type of data-- using the markers to show the points without the "area" of a bar plot potentially confusing the viewer-- but without the unnecessary (and potentially misleading) interpolation done by connecting it with lines.
Often, these would have the axes flipped (coord_flip() in ggplot2) and then you would sort the axis so that non-ordinal values were sorted in ascending or descending order, depending on what were emphasizing (putting the "most interesting" groups at the top of the Y axis).
A version of that with more pizzaz is the "lollipop" chart which is simply the dot plot with a thin line drawn from the axis to the dot. Those lines don't add anything except aesthetic value. They add "chart junk", decrease the "data-ink ratio" but they do look cool sometimes. For someone who hasn't seen my charts besides bar graphs it may help them intuitively understand how to read the dots. Here's an example that looks nice which was made in excel  (https://policyviz.com/2016/02/04/lollipop_graph_in_excel/).

A: Beforehand: 2 groups
For binary nominal variables the line plot provides a clear representation where the slope shows how the frequency changes if we go from one group to the other. Consider the following line plot for the frequencies of sex:

Here the slope shows the change of the frequency between males and females.
The problem: >2 groups
Consider the line plot for the nominal variable hair colour, which in the following data has four groups:

Here, the lines shows changes between two adjacent groups, e.g. the line goes up from Black to Brown, meaning that there are more people with black hair than with brown.
For a nominal variable with k groups there are (k^2 + k)/ 2 possible comparisons. But the line plot only depicts the changes between two adjacent groups, i.e. k-1 slopes. Since nominal data has no natural order, the placement of the groups on the x axis is arbitrary. Thus, depicting nominal data with a line plot means highlighting the k-1 changes which are arbitrary choosen from (k^2 +k)/ 2 possible group comparisons. We can see this in the second plot: The plot shows the frequency increasment while we go from black to brown hair colour but the plot does not display the slope between black and red neither the one between black and blonde hair colour.
We can connect all possible group combinations with the line graph to provide complete information of the data but this is quite overhelming:

To sum up
For ordinal, interval and ratio variables the line plot makes sense because it displays the trend of the data. For nominal data the location of the groups is arbitrary placed on the x axis and the lines of the line plot connect only two adjacent groups, i.e. groups that by coincidence lay next to each other. This is missleading. On the other hand, connecting all possible group comparisons results in an overhelming plot.


text:
Q: Show that $\mathbb{S}^{n+m}$ is not homeomorphic to a product of orientable manifolds I want to prove that the sphere $\mathbb{S}^{n+m}$ is not homeomorphic to the product  of N and M, orientable manifolfs with $\textit{dim}\;N=n$ and $\textit{dim}\;M=m$. I know that I have to use the de Rham cohomology of the sphere to prove it, but I don´t know how to do this. Any hint?

A: We want to find two closed forms $\omega_1$ and $\omega_2$ on $M \times N$ so that $\omega_1 \wedge \omega_2$ is a closed form of top degree with $\int \omega_1 \wedge \omega_2 \neq 0$. Therefore, $[\omega_1] \wedge [\omega_2]$ is nonzero in cohomology, and therefore each $[\omega_i]$ must have been as well.
Write $\omega_M$ for a volume form on $M$ - a nonvanishing top-dimensional form - which necessarily has $\int_M \omega_M \neq 0$. Similarly for $\omega_N$. Our desired forms are $\pi_M^* \omega_M$ and $\pi_N^* \omega_N$.
Now the Fubini theorem on integrals of functions on $\Bbb R^{n + m}$ of the form $f \cdot g$, where $f$ is a compactly supported function on $\Bbb R^n$ (respectively, $\Bbb R^m$) states that $$\int_{\Bbb R^{n+m}} fg = \int_{\Bbb R^n} f \cdot \int_{\Bbb R^m} g.$$
The usual argument to take a theorem about compactly supported integrals in $\Bbb R^n$ and make it into a theorem about integrals of differential forms is to apply a partition of unity to your atlas and them sum up the result. Nothing changes here (you should use two partitions of unity: one for $M$ and one for $N$), and you find that $$\int_{M\times N} \pi_M^*\omega_M \wedge \pi_N^* \omega_N = \int_M \omega_M \cdot \int_N \omega_N \neq 0,$$ as desired.


text:
Q: Chaining middleware in net/http golang I am trying to add context to Authorization middleware. The ContextHandler is a handler which will be passed to api handlers to take care of connections and config variables. A struct Method ServeHTTP also has been added to the ContextHandler so that it satisfies the net/Http interface for handling requests properly.
CheckAuth is the middle ware which takes in the request to check token validation etc, If token is valid, executes the ServeHTTP method and if not, Returns the appropriate error in the response.
Code compiles, but i am getting error in the ServeHTTP method.
type ContextHandler struct {
    *AppContext
     Handler func(*AppContext, http.ResponseWriter, *http.Request)(int, error)

}
type AppContext struct {
   Db    *mgo.Session
   Config *simplejson.Json
}

func (ah *ContextedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

status, err := ah.handler(ah.AppContext, w, r)
if err != nil {
     switch status {
    case http.StatusNotFound:
        http.NotFound(w, r)
      case http.StatusInternalServerError:
          http.Error(w, http.StatusText(status), status)
    default:
        http.Error(w, http.StatusText(405), 405)
    }}}

func CheckAuth(h http.Handler) http.Handler {
    log.Println("Entered in CheckAuth")
    f := func( w http.ResponseWriter, r *http.Request) {
    authorizationToken := r.Header.Get("Authorization")
    if authorizationToken != ""{
        secret := []byte("somejunk")
        var credentials authorization
        token, err := jwt.ParseWithClaims(authorizationToken, &credentials, func(t *jwt.Token) (interface{}, error) {
        return []byte(secret), nil
        })

        if err == nil && token.Valid {
            //If everything is fine serve the Http request
            h.ServeHTTP( w, r)
            return

            } else {
                  //Some response returned
                  json.NewEncoder(w).Encode(response)
                  return
                  }
        //Check if user exists in the database
        if dberr != nil {
           //SOmeresponse to be returned
          json.NewEncoder(w).Encode(response)
          return
        }
      }else{
          response := simplejson.New()
          //response authorization header is missing
          json.NewEncoder(w).Encode(response)
          return

        }
}
        return http.HandlerFunc(f)

}
func Initdb(configfile  *simplejson.Json) *mgo.Session {
   //return mongodbsession, copy and close while using it
}

In main.go file in the parent package
func main() {
      var FileUploadContextHandler *ContextedHandler = &ContextedHandler{&context, filesystem.FileUpload}
     router.Methods("POST").Path("/decentralizefilesystem/fileupload").Name("FileUpload").Handler(CheckAuth(FileUploadContextHandler))
  }

I am getting this error
    2018/07/08 20:45:38 http: panic serving 127.0.0.1:52732: runtime error: invalid memory address or nil pointer dereference
goroutine 35 [running]:
net/http.(*conn).serve.func1(0xc4202ce140)
    /usr/local/go/src/net/http/server.go:1726 +0xd0
panic(0x6fe680, 0x92cb10)
    /usr/local/go/src/runtime/panic.go:502 +0x229
gitlab.com/mesha/Gofeynmen/vendor/gopkg.in/mgo%2ev2.(*Session).Copy(0x0, 0x7ff9485fb060)
    /home/feynman/goworkspace/src/gitlab.com/mesha/Gofeynmen/vendor/gopkg.in/mgo.v2/session.go:1589 +0x22
gitlab.com/mesha/Gofeynmen/appsettings.CheckAuth.func1(0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /home/feynman/goworkspace/src/gitlab.com/mesha/Gofeynmen/appsettings/appsettings.go:115 +0x361
net/http.HandlerFunc.ServeHTTP(0xc420290180, 0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /usr/local/go/src/net/http/server.go:1947 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc42024a310, 0x7ff9485fb060, 0xc420276300, 0xc4202e4200)
    /home/feynman/goworkspace/src/github.com/gorilla/mux/mux.go:162 +0xed
github.com/gorilla/handlers.loggingHandler.ServeHTTP(0x7a8120, 0xc42000e018, 0x7a7b20, 0xc42024a310, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /home/feynman/goworkspace/src/github.com/gorilla/handlers/handlers.go:69 +0x123
github.com/gorilla/handlers.(*cors).ServeHTTP(0xc4202c4090, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /home/feynman/goworkspace/src/github.com/gorilla/handlers/cors.go:52 +0xa3b
net/http.serverHandler.ServeHTTP(0xc4202da0d0, 0x7aad60, 0xc4202f0000, 0xc4202e4000)
    /usr/local/go/src/net/http/server.go:2694 +0xbc
net/http.(*conn).serve(0xc4202ce140, 0x7ab120, 0xc42025e100)
    /usr/local/go/src/net/http/server.go:1830 +0x651
created by net/http.(*Server).Serve
    /usr/local/go/src/net/http/server.go:2795 +0x27b

A: It's likely an attempt to dereference ah from (ah *ContextedHandler), when ah is not a pointer to a ContextedHandler.
The types in this assignment don't match up:
var FileUploadContextHandler *ContextedHandler =
    ContextedHandler{&context, filesystem.FileUpload}

On the left side you have type *ContextedHandler.  On the right side you have type ContextedHandler.
Did you mean
var FileUploadContextHandler *ContextedHandler =
    &ContextedHandler{&context, filesystem.FileUpload}

Or did you mean
var FileUploadContextHandler ContextedHandler =
    ContextedHandler{&context, filesystem.FileUpload}

?

The argument passed to the CheckAuth function appears to not match the function signature either:
CheckAuth(FileUploadContextHandler)

FileUploadContextHandler is type *ContextedHandler.  The function signature is:
func CheckAuth(h contextHandlerFunc) contextHandlerFunc

The type definition of contextHandlerFunc does not appear to be part of the code you shared.

A problem with this line:
router.Methods("POST").Path("/decentralizefilesystem/fileupload").Name("FileUpload").Handler(CheckAuth(FileUploadContextHandler))

...would be easier to track down if you broke it up into variable assignments on several lines and then figured out which line the panic pointed to.


text:
Q: How to detect if specific pic from Media is used by any page Umbraco version 7.5.14
I have pic.jpg in a Media library (file in Media folder: inetpub\wwwroot...\Media\pic.jpg)
I want to find out if the file is OK to be deleted, if no page uses it. How?
(There are bunch of files to be deleted, I suspect they are not used)

A: This solution assumes you have access to the CMS database and know how to run SQL. If you do not know how to do these things I would not recommend this approach...
Since your version of Umbraco is a little older I've had to adapt my script - but this should hopefully do the trick.
DECLARE @MediaPath NVARCHAR(255) = '/media/pic.jpg'

 SELECT
    contentNode.id 'Content Id',
    contentNode.text 'Content Node Name',
    contentNode.path 'Content Node Path',
    mediaNode.id 'Media Id',
    mediaNode.text 'Media Name',
    cpt.Name 'Media Type',
    COALESCE(cpd.dataNtext, cpd.dataNvarchar) 'Media Properties'
FROM cmsPropertyData cpd WITH(NOLOCK)
INNER JOIN cmsPropertyType cpt WITH(NOLOCK) ON cpt.Alias = 'umbracoFile' AND cpd.propertytypeid = cpt.id
INNER JOIN umbracoNode mediaNode WITH(NOLOCK) ON mediaNode.id = cpd.contentNodeId
INNER JOIN cmsContentXml ccx WITH(NOLOCK) ON ccx.xml LIKE CONCAT('%umb://media/', LOWER(REPLACE(mediaNode.uniqueID,'-','')), '%')
INNER JOIN umbracoNode contentNode WITH(NOLOCK) ON ccx.nodeId = contentNode.id
WHERE COALESCE(cpd.dataNtext, cpd.dataNvarchar, '') LIKE CONCAT('%',@MediaPath,'%')

The output of this script will be a data table showing the content nodes where the image is in use. If the results set is empty - the image is not in the content XML.
In other versions of Umbraco (I cannot tell if Older or Newer) there might be a a cmsMedia table you can use - which is far faster
DECLARE @MediaPath NVARCHAR(255) = '/media/pic.jpg'

SELECT
    contentNode.id 'Content Id',
    contentNode.text 'Content Node Name',
    contentNode.path 'Content Node Path',
    mediaNode.id 'Media Id',
    mediaNode.text 'Media Name',
    cm.mediaPath
FROM cmsMedia cm
INNER JOIN umbraconode mediaNode ON mediaNode.id = cm.nodeId
INNER JOIN cmsContentXml ccx ON ccx.xml LIKE CONCAT('%umb://media/', LOWER(REPLACE(mediaNode.uniqueID,'-','')), '%')
INNER JOIN umbracoNode contentNode ON ccx.nodeId = contentNode.id
WHERE cm.mediaPath = @MediaPath


text:
Q: SSH to Amazon EC2 using instance ID only I would like to turn on/off some of my Amazon EC2 instance, but this causes the IP and all DNS names to change. Therefore when I boot my machine again, all my SSH configurations are lost since I was connecting using the previous DNS name.
Is there a simple way to resolve the dns of the target machine (with no or as low as possible cost) using only its instance-id (or any other parameter that do not change over shutdowns-restarts) ? Do I have to use the AWS-CLI ? What if I want to provide an access to an EC2 machine to someone who doesn't have AWS credentials ?
Not sure if tags like "service-discovery", "broker", or "proxy" would really make sense here, but for the sake of references I'm adding them in my post.
I do not want to pay for elastic IPs.

A: There are already Utils that do this, no need to roll your own: ec2ssh  is a python script to do it but  a google for ec2ssh will turn up numerous similar tools in multiple languages that will  do the job.
Personally, I setup a bastion with an EIP,  and jump from there to all the other hosts. This way you don't need to give your Instances public IPs  just for admin access. If your not transferring large files you can get away with a t2.nano as the bastion instance, which with a reservation costs you peanuts a month.
Ec2ssh has bastion support so the config overhead is minimal.

A: Building off of @jarmod 's comment, if you know the instance ID then you can use the awscli to get the IP like this:
aws ec2 describe-addresses --filters Name=instance-id,Values=i-xxxxxxxxxxxxxxxxx | grep PublicIp | awk -F\" '{print $4}'
That being said, I'm not sure why you think that Elastic IPs are expensive. Per the Pricing page, Elastic IPs are free when associated with running instances, and $0.005/hour when not associated with an instance.

A: EC2 elastic IP is exactly what you want. Instance will retain it's elastic IP (and associated DNS-name) during reboots and start/stop cycles.
https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses
Keep in mind: it only works with VPC EC2 instances. Old "classic" instances will lose their elastic IP and you will have to associate it manually again.

A: This tool should do what you're asking for: https://github.com/wagoodman/bridgy
bridgy ssh <some-instance-id>
If you have the ~/.aws creds/config defined as you would with the aws-cli as well as the following in ~/.bridgy/config.yml:
inventory:
    source: aws
    update_at_start: true
ssh:
    user: <your ssh user>
...

then it should work!
Disclosure: I'm the author.


text:
Q: Unable to locate php.ini file or paths to it on mac I've just starting working on a mac so this is probably very obvious.
I've installed php, pear, and lastly pecl.
My last command was sudo pecl install mongo and am prompted to add the line extension=mongo.so to php.ini configuration.
I am unable to locate the php.ini file.  I do a quick php --ini in the CL and am told the path is /etc, /etc/php/apache2/php.ini to be exact. I've tried to unhide files and well as searching via the finder but am told these directories don't exist, even though I believe my installations were done correctly.  How can I access this etc directory, as well as others like the php5 folder so I can edit my php.ini file? Thanks.  Using Yosemite 10.10.3 and latest php packages.

A: Just check the phpinfo output to locate the loaded php.ini file (Loaded Configuration File).


text:
Q: Moving Angular controller functions to a separate Typescript class I am working on an application using AngularJS and Typescript. Many requirements are being added to the application so I want to nail down the structure before the code gets out of hand.
I have an Angular controller with 1500 lines and I would like to move the functions to a separate file like so:
export class CtrlFunctions{
    private scope: any;

    constructor($scope) {
        this.scope = $scope;
    }

    updateHeader = header => {
        //more logic here
        this.scope.header = header;
    }
}

And I would access the values in the controller like this:
import { CtrlFunctions } from "../controller-functions/entry.ctrl.func";

namespace Entry {
    class EntryCtrl {
        private funcs: CtrlFunctions
        constructor(){
            this.funcs = new CtrlFunctions($scope);
        }
    }
}

Is this bad practice? Is there a better way to take advantage of the modularity provided by Typescript?


text:
Q: On Windows Phone 8 HTC, rotating a Bootstrap site from portrait to landscape creates a horizontal scroll bar This is the website: http://www.muddlingthru.ca/. We have ruled out the usual horizontal scroll-bar suspects.
Add meta tags.
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />

Use the Bootstrap div.container > div.row > div.col-md-* structure.
Check for conflicting width/margin/padding/border settings in our CSS.
No luck.
We have also isolated when the problem happens:

*

*only if we rotate from portrait to landscape on WinPhone8

*not if we start in landscape on page load

*not if we do a page refresh after the problem happens

*not if we rotate using web developer tools in FireFox

If you have any ideas why this happens and how to fix it, please let us know.

A: Are you applying the WP8 IE10 viewport fix recommended on http://getbootstrap.com/getting-started/#support-ie10-width ?
CSS:
@-webkit-viewport   { width: device-width; }
@-moz-viewport      { width: device-width; }
@-ms-viewport       { width: device-width; }
@-o-viewport        { width: device-width; }
@viewport           { width: device-width; }

JS:
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
  var msViewportStyle = document.createElement('style');
  msViewportStyle.appendChild(document.createTextNode('@-ms-viewport{width:auto!important}'));
  document.querySelector('head').appendChild(msViewportStyle);
}


text:
Q: Firebase Notification does not work with experimental gradle Fire Base messaging stops working with experimental gradle.
How to recreate the issue
Create a project to support firebase notifications
follow
https://firebase.google.com/docs/notifications/android/console-audience
Build and run. Works wonderfully well
Change the gradle to experimental build. Follow steps in Hello Jni example to change to experimental gradle. Forget adding C code for now just make the changes to support experimental gradle. Follow
https://codelabs.developers.google.com/codelabs/android-studio-jni/index.html?index=..%2F..%2Findex#0
Build and Run: Firebase cannot initialise any longer. See logs and search for firebase which indicate Firebase initialisation unsuccessful :(
Gradle version  (File -> Project Structure, Project): 2.10
Android Plugin Version  (File -> Project Structure, Project): None
SDK Version: "Android SDK Tools" Rev. (Tools -> Android -> SDK Manager) : 25.1.7
Module Compile Sdk Version  (File -> Project Structure, Your Module): 24.0.0
Module Build Tools Version  (File -> Project Structure, Your Module): 24.0.0
Any workaround please.
Thanks in advance
Thanks and Regards,
PB

A: I also faced the same problem and spend several days investigating and googling. The problem is that Google Services Gradle Plugin isn't compatible with gradle-experimental. However digging deeper I found out that this plugin doesn't do a lot, it just parses "google-services.json" and generates "app/build/generated/res/google-services/{build_type}/values/values.xml" out of it.
So I just manually generated that file "MyProject/src/main/res/values/google-services.xml"
<?xml version="1.0" encoding="utf-8"?>
<resources>
<! -- Present in all applications -->
<string name="google_app_id" translatable="false">1:1035469437089:android:73a4fb8297b2cd4f</string>
<! -- Present in applications with the appropriate services configured -->
<string name="gcm_defaultSenderId" translatable="false">1035469437089</string>
<string name="default_web_client_id" translatable="false">337894902146-e4uksm38sne0bqrj6uvkbo4oiu4hvigl.apps.googleusercontent.com</string>
<string name="ga_trackingId" translatable="false">UA-65557217-3</string>
<string name="firebase_database_url" translatable="false">https://example-url.firebaseio.com</string>
<string name="google_api_key" translatable="false">AIzbSyCILMsOuUKwN3qhtxrPq7FFemDJUAXTyZ8</string>
<string name="google_crash_reporting_api_key" translatable="false">AIzbSyCILMsOuUKwN3qhtxrPq7FFemDJUAXTyZ8</string>
</resources>

More info can be found: https://developers.google.com/android/guides/google-services-plugin
Hope this helps.

A: Just to add to xp-vit's answer (which was incredibly helpful to me) you can add another android client to your firebase project that doesn't use the experimental gradle to generate the XML for you and then you only have to change the "google_app_id" field. This is found under the {YOUR_CLIENT}/client_info/mobilesdk_app_id in the json file.
Might help avoid typos.

A: Faced the same issue. And it's a hard bug. You don't know that your Firebase events are not being sent until you turn Firebase log into Verbose mode.
For those who doesn't know how to enable Firebase logs:
In AndroidStudio in Terminal window execute the following:
adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

Thanks to that I found an error:
Missing google_app_id. Firebase Analytics disabled
I've double checked everything but then I found a ticket in Android bug tracker saying that experimental gradle interferes with Firebase Analytics.
In order to resolve this I've migrated from 'com.android.tools.build:gradle-experimental:0.8.3' to the latest stable regular Gradle plugin 'com.android.tools.build:gradle:2.2.3'.
And everything works like a charm.
So this is how you migrate from experimental gradle plugin to the latest stable plugin v. 2.2.3:
1. Update your gradle scripts.
http://tools.android.com/tech-docs/new-build-system/gradle-experimental/migrate-to-stable  In this article after you install everything in sdk mnager you need to do the following:
In your project-level build.gradle file, change the classpath dependency of the gradle plugin to 2.2.0 or higher
buildscript {
  repositories {...}
  dependencies {
      classpath 'com.android.tools.build:gradle:2.2.3'
  }
}

Switch to Stable Gradle DSL
You only need to follow the instructions in this section of the guide if you are migrating from experimental Gradle. Since the stable version of Gradle does not use the component model mechanism, you need to change some of the DSL in your module-level build.gradle file:

*

*At the top of your module-level build.gradle file, you need to apply the stable version of the plugin as follows:
apply plugin: 'com.android.application'
- also if you have any modules - the first line for them should be the following: apply plugin: 'com.android.library'

*Remove the model{} block, including its opening and closing curly braces. The android{} block should not be enclosed within any other DSL elements.

*Remove ".apiLevel" suffix from minSdkVersion and targetSdkVerion:
minSdkVersion 16
targetSdkVersion 23

*Change the proguardFiles DSL to the following:
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

*Remove create("...") from your productFlavor configurations. For example, use the following DSL to create a "flavor1" product flavor:
-I didn't have those
productFlavors {
    flavor1 {
        applicationId "com.app"
    }
    ...
}

*Only define abiFilters in the ndk{} block--comment out everything else in this block. The stable plugin uses a new externalNativeBuild{} DSL to link Gradle to your CMake or ndk-build project, and set toolchain arguments and compiler flags.
- here I commented out entire ndk{} block
2. Create a CMake build script. Easy
https://developer.android.com/studio/projects/add-native-code.html#create-cmake-script
Do exact how it is told here. Right click on our model in right Project side window. New file. Create it. Paste it. I had only one C++ class so I have a very simple CMakeLists.txt file:
cmake_minimum_required(VERSION 3.4.1)
add_library(
         lib-name

         SHARED

         my_cpp_class.cpp )

3. Link C++ Project with Gradle

*

*Open the Project pane from the left side of the IDE and select the Android view.

*Right-click on the module you would like to link to your native library, such as the app module, and select Link C++ Project with Gradle from the menu. You should see a dialog similar to the one shown below

*From the drop-down menu, select either CMake or ndk-build.
If you select CMake, use the field next to Project Path to specify the CMakeLists.txt script file for your external CMake project.

! Important: if you have any other modules - do these steps for every module in your project !
And that's it. Clean your project and build it again.
Now you can use Firebase Analytics.
Basically I didn't create or told anything new, so all credits to Google.
I just put together two articles of how to do it and wrote down the steps with my comments.
It's not hard and it will give you more benefits because experimental gradle may cause some problems anytime in the future.


text:
Q: PHP Zend2 bjyauthorize doctrine Where set default role if no identity is given I'm pretty new to Zend 2, Doctrine and Stuff
In my Project i would like to implement BjyAuthorize module from zend 2 via doctrine.
I already have done some stuff - i successfully implement and configured everything except the default role, if no identitiy is given (new user is visting, or after logout for example).
role and user classes are the blueprints from BjyAuthorize
this is my identity provider class which is defined in my bjyauthorize.global.php
'identity_provider' => 'Application\Provider\Identity\IdentityProvider',

code:

namespace Application\Provider\Identity;

use BjyAuthorize\Provider\Identity\ProviderInterface;
use Zend\Authentication\AuthenticationService;

class IdentityProvider implements ProviderInterface
{
//    public function getDefaultRole()
//    {
//        $aTest = "test";
//        return new Debug();
//    }

    public function getIdentityRoles()
    {
        $oIdentity = $this->getIdentity();

        $aRoles = [];
        if(!empty($oIdentity))
        {
            $aRoles = $oIdentity->getRoles();
        }

        return $aRoles;
    }

    protected $authService;

    public function __construct(AuthenticationService $authService)
    {
        $this->authService = $authService;
    }

    public function getAdapter()
    {
        return $this->authService->getAdapter();
    }

    public function getStorage()
    {
        return $this->authService->getStorage();
    }

    public function getIdentity()
    {
        return $this->authService->getIdentity();
    }

    public function clearIdentity()
    {
        return $this->authService->clearIdentity();
    }
}

the role provider is successfully set to
'role_providers' => [
    // this will load roles from
    // the 'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' service
    "BjyAuthorize\Provider\Role\ObjectRepositoryProvider" => [
        // class name of the entity representing the role
        'role_entity_class' => 'Application\Tables\Role',
        // service name of the object manager
        'object_manager'    => 'doctrine.entitymanager.orm_default',
    ],
],

The only thing is missing now is that i want to set a default role (from db, the role "guest") if a new user is visiting the page. after all reading and googling i can't find any hint where and how to set the default role.
I already tried the method "getDefaultRole" in my IdentityProvider, but this method seems not to be fired.
I only see now to fetch the default role in my "getIdentityRoles" if no identity is set.
But to archiv this i have to get the doctrine entity manager and more stuff to include - is this the only way?
edit:
In the "byauthorize.global.php" i can see following lines:
// set the 'guest' role as default (must be defined in a role provider)
'default_role' => 'guest',

but i do not know where i i have to define the default role in the role provider ... :-/
kindly regards

A: The 'default_role' setting is only used by the shipped AuthenticationIdentityProvider of BjyAuthorize (and its factory).
When implementing your own IdentityProvider, then you simply must implement BjyAuthorize\Provider\Identity\ProviderInterface#getIdentityRoles() so that it falls back to an identity of your choice when none is given.


text:
Q: Waiting untill a downloaded file is complete, not just File.exists() I am downloading a file from the net and then reading it using a BufferedReader. Currently I download the file using DownloadManager then have this code :
while (latestNumbersFile.exists() != true) {
            System.out.println("WAITING...");
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) {
        }

So that any following code does not execute until the file has finished downloading. This works but seams really dirty to me.
If I remove the Thread.sleep(5000); it seams that the file does indeed exist but is not quite ready to be read.
There has to be a better way of recognizing when a file not only exists but is actually complete and ready to have something preformed on it.
Any thoughts?? (sorry if this is a noobie question, I've searched high and low for an answer)

A: From Android developers when download completes, DownloadManager broadcasts an intent. You can capture this "event" and handle it like:
BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

             /** Do your coding here **/

            }
        }
    };

    registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Source from: Vogella
Please let me know if this helps you, if it doesn't we can try anything else :)

A: Busy-waiting is not recomended. You'd better use DownloadManager.
From Download a file with Android, and showing the progress in a ProgressDialog :

Use DownloadManager class (GingerBread and newer only)
  This method is awesome, you do not have to worry about downloading the file manually, handle threads, streams, etc. GingerBread brought a new feature: DownloadManager which allows you to download files easily and delegate the hard work to the system.


text:
Q: Confusion about estimation and prediction I have a very basic question, consider the following:
While learning to predict y from x, we are learning the joint distribution p(x,y). Now consider an estimation problem: suppose x follows a Gaussian distribution with unknown mu and known standard deviation, and mu follows a Poisson distribution with known parameters. So now if we want to estimate mu and then predict x, is it correct to say that we are learning the joint distribution of p(x,mu)?
Also, for learning to predict, are we actually learning p(x,y) or p(y|x)?

A:
While learning to predict y from x, we are learning the joint
  distribution p(x,y).

Yes and no. If you use statistical model, then you assume some distribution for your data. On another hand, not every statistical method assumes such model. Take as an example ordinary least squares regression, the only thing that it does it minimizes the squared error, we do not need any distributional assumptions for that. It can be even more clear for some machine learning algorithms, for example $k$-nearest neighbors simply looks for "similar" observations in your data given some distance measure. So you can also learn patterns and similarities instead of distributions.

Now consider an estimation problem: suppose x follows a Gaussian
  distribution with unknown mu and known standard deviation, and mu
  follows a Poisson distribution with known parameters. So now if we
  want to estimate mu and then predict x, is it correct to say that we
  are learning the joint distribution of p(x,mu)?

Making it a little bit formal: you assume a Bayesian model with normal likelihood $P(X\mid\mu)$, known $\sigma$ and assume Poisson prior for $\mu$. In such case indeed you are estimating a posterior distribution $P(\mu\mid X)$. Notice that if you want to estimate joint of conditional distribution of data and parameter, then you need to assume that your parameter is a random variable, so you need to use a Bayesian model. Otherwise parameter would need to be a fixed value and it wouldn't have a distribution. You can check this thread to learn more about difference between frequentist and Bayesian likelihood.

Also, for learning to predict, are we actually learning p(x,y) or
  p(y|x)?

It depends what you are actually learning... Moreover, if you know joint and marginal distributions, you can use them to obtain conditional probabilities and vice versa since
$$ P(A \cap B) = P(A\mid B) \;P(B) \quad \text{and} \quad P(A\mid B) = \frac{P(A \cap B)}{P(B)}$$


text:
Q: Insert PDF into SQL Server I would like to insert a PDF file into SQL Server.
I tried 2 different queries but still getting the same error:

Msg 4861, Level 16, State 1, Line 11
  Cannot bulk load because the file "C:\Users\XXX\Desktop\filename.pdf" could not be opened. Operating system error code 3(The system cannot find the path specified.).

My code:
INSERT INTO [Testing].[dbo].[table00](FileContent)
    SELECT BulkColumn
    FROM OPENROWSET(BULK N'C:\Users\XXX\Desktop\filename.pdf', SINGLE_BLOB) as TheFile

INSERT INTO [Testing].[dbo].[table00](FileContent, Blob)
    SELECT 0, *
    FROM OPENROWSET(BULK N'C:\Users\XXX\Desktop\filename.pdf', SINGLE_BLOB) rs

Any advice? How to solve this error? Thanks!
Background:
I am trying to insert a PDF file into this particular column FileContent with a datatype of Image in my table testing.dbo.table00.

A: Sounds like either the file doesn't exist or SQL Server doesn't have permission to access it.
Keep in mind that the path passed to OPENROWSET BULK is relative to the SQL Server, not to the computer from which you're executing the query (unless that computer is the SQL Server). So, in your case, C:\Users\XXX\Desktop\filename.pdf must exist on the SQL Server in order for your query to succeed.
If the file exists on the server and you still receive this error, it's possible that SQL Server does not have permission to access to the file. To check this, right-click on the file, choose properties, security, advanced, then check effective access for the SQL Server account. If the account does not have rights to access the file, assign the needed permissions.


text:
Q: Count number of rows from a different table using join on Laravel Eloquent How can I use eloquent to count rows of another table joined with the main table?
I have three tables:

*

*clients

*sms notification

*email notification

I want to join them by pulling the client list first, then count how many times they had notification from both SMS and email. Finally returning the count or 0 if no notification has been sent.

I found a sample:
Laravel Eloquent to join table and count related
I used this for emails:
<?php

$clients = Client::where('cl_delete_status', false)
    ->leftJoin('insura_communication_emails', 'insura_clients.cl_id', 'insura_communication_emails.cl_id')
    ->leftJoin('insura_communication_sms', 'insura_clients.cl_id', 'insura_communication_sms.cl_id')
    ->select('*', DB::raw('count(ice_id) as total'))
    ->groupBy('insura_clients.cl_client_id')
    ->orderBy('insura_clients.cl_id', 'desc')->get();

How can I put both tables that are email and SMS insura_communication_sms and in the code above? It skips those with 0 counts in the email notification.


text:
Q: How to search all emails for a string in Outlook? In the newer unversioned Outlook how do I search all emails for a string? Say I want to find all emails with the string "hello.world" how could I find all emails including that string?

A: Open Outlook.
Use the Top Bar to start Search or use the Search tab if your Outlook is set up that way. I start with the Top Bar.
By default "Advanced Search" (only will see the words "Advanced Search" if you hover) button has the text "Current Folder" so click "Current Folder" to open "Advanced Search".
Select All Mailboxes.
Then enter the the string in the Body section and enclose in Quotes if the string includes spaces.
Then Search.
Here is a screen shot with all the options shown.


text:
Q: Python Dataframe apply causing error "List index out of range" I have a dataframe that contains a bunch of urls to PDF files. I want to extract the filenames into a separate column. I tried it on a MWE and it works but my main dataset is giving me this error. Can someone please help me understand what the source of the error might be
MWE
my_dict = {"url": ["http://www.someting.com/file/file1.pdf", "http://www.someting.com/file/file37.pdf"]}
my_test_df = pd.DataFrame.from_dict(my_dict)

def get_filename_from_url(url):

    #Commenting out a bunch of stuff because my final goal is to do NLP on the extracted text
    #response = requests.get(url)
    #my_raw_data = response.content

    m = re.search('[^/]+$', url)
    if m is None:
        return None

    file_name = m.group(0)

    return file_name

my_test_df['File_name'] = my_test_df.apply(lambda row: get_filename_from_url(row['url']),axis=1)

This works, and my DF looks like what I expected it to.

But for my actual dataframe,

when I do this, it works:

But when I try apply to create a new column, I get an error.
my_main_df['File_name3'] = my_main_df.apply(lambda row: get_filename_from_url(row['PDF Links']),axis=1)

I get the following error. I don't understand which list's index is getting messed up:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-80-dd127df2eb83> in <module>
----> 1 my_main_df['File_name3'] = my_main_df.apply(lambda row: get_filename_from_url(row['PDF Links']),axis=1)

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3161         else:
   3162             # set column
-> 3163             self._set_item(key, value)
   3164
   3165     def _setitem_slice(self, key: slice, value):

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   3244         # value exception to occur first
   3245         if len(self):
-> 3246             self._check_setitem_copy()
   3247
   3248     def _set_value(self, index, col, value, takeable: bool = False):

~\Anaconda3\lib\site-packages\pandas\core\generic.py in _check_setitem_copy(self, stacklevel, t, force)
   3935             raise com.SettingWithCopyError(t)
   3936         elif value == "warn":
-> 3937             warnings.warn(t, com.SettingWithCopyWarning, stacklevel=stacklevel)
   3938
   3939     def __delitem__(self, key) -> None:

~\Anaconda3\lib\warnings.py in _showwarnmsg(msg)
    107                                 "function or method")
    108
--> 109             sw(msg.message, msg.category, msg.filename, msg.lineno,
    110                msg.file, msg.line)
    111             return

~\Anaconda3\lib\site-packages\PyPDF2\pdf.py in _showwarning(message, category, filename, lineno, file, line)
   1067                     file = sys.stderr
   1068                 try:
-> 1069                     file.write(formatWarning(message, category, filename, lineno, line))
   1070                 except IOError:
   1071                     pass

~\Anaconda3\lib\site-packages\PyPDF2\utils.py in formatWarning(message, category, filename, lineno, line)
     67 #custom implementation of warnings.formatwarning
     68 def formatWarning(message, category, filename, lineno, line=None):
---> 69     file = filename.replace("/", "\\").rsplit("\\", 1)[1] # find the file name
     70     return "%s: %s [%s:%s]\n" % (category.__name__, message, file, lineno)
     71

IndexError: list index out of range

Update:
When I use "head" to essentially extract all the rows of my main dataframe, the apply command works. Note that my main df only has 386 rows so head(400) basically catches all rows.

Commands in the screenshot above, copied here. I am so confused.
df2 = my_main_df.head(400)
df2['File_name_test'] = df2.apply(lambda row: get_filename_from_url(row['PDF Links']),axis=1)


text:
Q: Load data from csv file to oracle table from command line I tried with sql loader.The thing is the table needs to be empty for data loading.Is there any way to do data upload without truncating the table.The CSV data need to be appended in the table.i am using oracle 11g.

A: The SQL*Loader documentation says:

When you are loading a table, you can use the INTO TABLE clause to
  specify a table-specific loading method (INSERT, APPEND,
  REPLACE, or TRUNCATE) that applies only to that table. That method
  overrides the global table-loading method. The global table-loading
  method is INSERT, by default, unless a different method was
  specified before any INTO TABLE clauses.

So by default your table load will be in INSERT mode, which does require the table to be empty.
The documentation also explains how to load data into a non-empty table; in your case you want to preserve the existing data:

APPEND
  If data already exists in the table, then SQL*Loader appends the new rows to it.  If data does not already exist, then the
  new rows are simply loaded. You must have SELECT privilege to use the APPEND option.

So your control file will need to say something like this (as shown in their example):
LOAD DATA
INFILE 'my_file.dat'
BADFILE 'my_file.bad'
DISCARDFILE 'my_file.dsc'
APPEND
INTO TABLE my_table
...

You could also consider using the new CSV data as an external table and inserting to your real table from that, which might be a bit more flexible.


text:
Q: Getting `A value is trying to be set on a copy of a slice from a DataFrame.` when setting a column I know a value should not be set on a view of a pandas dataframe and I'm not doing that but I'm getting this error. I have a function like this:
def do_something(df):
    # id(df) is xxx240
    idx = get_skip_idx(df)  # another function that returns a boolean series
    if any(idx):
        df = df[~idx]
    # id(df) is xxx744, df is now a local variable which is a copy of the input argument
    assert not df._is_view  # This doesn't fail, I'm not having a view
    df['date_fixed'] = pd.to_datetime(df['old_date'].str[:10], format='%Y-%m-%d')
    # I'm getting the warning here which doesn't make any sense to me

I'm using pandas 1.4.1. This sounds like a bug to me, wanted to confirm I'm not missing anything before filing a ticket.

A: My understanding is that _is_view can return false negatives and that you are actually working on a view of the original dataframe.
One workaround is to replace df[~idx] with df[~idx].copy():
import pandas as pd

df = pd.DataFrame(
    {
        "value": [1, 2, 3],
        "old_date": ["2022-04-20 abcd", "2022-04-21 efgh", "2022-04-22 ijkl"],
    }
)

def do_something(df, idx):
    if any(idx):
        df = df[~idx].copy()
        df["date_fixed"] = pd.to_datetime(df["old_date"].str[:10], format="%Y-%m-%d")
    return df

print(do_something(df, pd.Series({0: True, 1: False, 2: False})))
# No warning
   value         old_date date_fixed
1      2  2022-04-21 efgh 2022-04-21
2      3  2022-04-22 ijkl 2022-04-22


text:
Q: Matrix exponential and rank Let $A$ be a square matrix. Invertibility of $\exp(A)$ follows easily from properties of the matrix exponential.
Is $\int_0^t \exp(A u)du$ also invertible? I believe it should be, and that the inverse should be $I - At/2 + A^2t^2/12 + ...$
This comes from expanding the real-valued function $x/(e^x - 1)$ in a power series about $x=0$. How should I approach a proof of this (or could I find it in a book somewhere?)
What about the more general case when $\Phi(t)$ is defined by
$\frac{dX}{dt} = A(t)X,\ \  X_0 = x_0 $
and
$X(t) = \Phi(t)x_0$? How might one show that $\int_0^t \Phi(u)du$ is invertible?

A: Try $A = \pmatrix{0 & 1\cr -1 & 0\cr}$ for which $\exp(Au) = \pmatrix{\cos(u) & \sin(u)\cr
-\sin(u) & \cos(u)\cr}$.  Then $\int_0^{2\pi} \exp(Au)\ du = 0$.
More generally, if $\lambda \ne 0$ is an eigenvalue of $A$ for eigenvector $v$, then $v$ is an eigenvector of $\int_0^t \exp(Au)\ du$ with eigenvalue $(1 - e^{t\lambda})/\lambda$, so if $e^{t\lambda} = 1$, $\int_0^t \exp(Au)\ du$ is not invertible.
On the other hand, if $e^{t\lambda} \ne 1$ for all nonzero eigenvalues $\lambda$ of $A$, then $\int_0^t \exp(Au)\ du$ is invertible.
For your more general case, if $A(t)$ don't all commute, closed-form  solutions may not be available, and I think it becomes harder to determine when the integral is invertible.


text:
Q: How to get TouchableOpacity Text String How to get number '1' of this TouchableOpacity?
numClick(){
    this.state.pressedNum = ?
}
render(){
    return (
        <TouchableOpacity style={styles.numButton} onPress={()=>this.numClick()}>
            <Text style={styles.numString}>1</Text>
        </TouchableOpacity>
}

A: Do you need to extract the value from the actual Text component? If not you can just pass it to the function as an argument. By the way, you should not mutate state directly, use setState() instead.
numClick(num) {
    this.setState({
        pressedNum: num
    });
}

render() {
    return (
        <TouchableOpacity style={styles.numButton} onPress={()=>this.numClick(1)}>
            <Text style={styles.numString}>1</Text>
        </TouchableOpacity>
    )
}


text:
Q: Ubuntu 18.04 freezes at login screen Ubuntu is installed on a VirtualBox VM. It freezes before I can login. I get the following error messages during boot:

*

*[FAILED] Failed to activate swap/swapfile. See 'systemctl status swapfile.swap' for details

*[DEPEND] Dependency failed for swap

*[FAILED] Failed to start Enable File System Quotas. See 'systemctl status quotaon.service' for details

I tried the following:

*

*Booting to the recovery menu and selecting "dpkg Repair broken packages" then "Resume normal boot". After that I can login successfully and update the software, but when I restart the system, it freezes again.

*I tried all the options in the recovery menu and also tried FSCK after booting with a recovery ISO.

A: I'd suggest you have no reason to care about the broken one.
Install a new one.
You're probably using the wrong method to install.

A: Here's the solution for anyone wondering. It seems it was not related to swaps or quotas.
https://unix.stackexchange.com/questions/502540/why-does-drmvmw-host-log-vmwgfx-error-failed-to-send-host-log-message-sh

*

*Try to change display setting and check.

*Essentially what it boiled down to was a lack of resources. I allocated 2 CPU's, 2 GB of memory, and 16 GB on the virtual hard drive for it to work. Also make sure you have virtualization enabled in the BIOS settings.


text:
Q: Return a List from List with an integer property? The end result is I want to use .Where(t => someIntList.Contains(t.ID)).ToList(). I'm struggling to create someIntList.
What I have so far: List<Person> people = people.Where(p => p.isActive).ToList(). How do I return just a List<int> of the p.ID property?
Or is there another way to do Contains (without writing a Comparer class as I already have one used for another purpose.

A: Well, producing the List<int> is easy, using Select to perform the projection:
List<int> activeIds = people.Where(p => p.IsActive)
                            .Select(p => p.ID)
                            .ToList();

However, rather than do that and then use Contains, I would perform a join:
var activePeople = people.Where(p => p.IsActive);
var query = from person in otherList
            join activePeople on person.ID equals activePeople.ID
            select person;

Or create a HashSet<int> instead of a List<int>, so that the Contains check is more efficient:
var activeIds = new HashSet<int>(people.Where(p => p.IsActive)
                                       .Select(p => p.ID));
var query = otherList.Where(t => activeIds.Contains(t.ID))
                     .ToList();

Both of these will give O(M + N) complexity for finding all matches, rather than O(M * N) that constructing a list and then using that for the Contains check would do.
Of course, that's assuming the Contains check is going to be done in-process. If this is actually going to be used in a LINQ to SQL query, then it could be that passing in a List<int> is fine - or it could be that the join allows you to do it all in the database. We really need more context to give you good advice - but don't just stop at "this is how I can build a List<T>, therefore I'm done."


text:
Q: Does Linux spin_lock_irqsave() disables ARM FIQ interrupt? I am writing a Linux device driver and need to serialize access to critical sections of the driver from tasks and interrupts. I am developing for ARM.
If I use spin_lock_irqsave() and spin_unlock_irqrestore() pair to protect my critical sections, is FIQ blocked while in these critical sections?
I tried looking at the implementations of these 2 functions, in particular spin_lock_irqsave(). My initial impression is that FIQ is not disabled. Just want to verify this with the experts out here.
Please enlighten me. Thanks!

A: I don't think Linux uses FIQ, so an FIQ will not conflict with a Linux ISR.  That said, I believe it uses:
cpsid i

This disables regular interrupts.  To also disable FIQs it would need to do
cpsid if

See: https://elixir.bootlin.com/linux/latest/source/arch/arm/include/asm/irqflags.h#L25


text:
Q: brew services start mongodb-community@4.0 fails - uninitialized constant I've followed the directions on the MongoDB docs to install MongoDB on Mac using homebrew:
brew tap mongodb/brew
brew install mongodb-community@4.0

Then I can run it in the foreground using:
mongod --config /usr/local/etc/mongod.conf

But, when trying to start it as a service using:
brew services start mongodb-community@4.0

I get this error:
Error: mongodb-community: uninitialized constant #<Class:0x00007ff189061008>::Gem

I also get this error when running brew doctor:
Warning: Some installed formulae are not readable:
  mongodb-community: uninitialized constant #<Class:0x00007ffd903152a0>::Gem

Why this is happening? How do I fix it?
Thank you!

A: I know it's not correct answer since we are talking about registering service using:
brew services start mongodb-community

But I've SOLVED service registration question this way:
sudo cp /usr/local/Cellar/mongodb-community/4.0.9/homebrew.mxcl.mongodb-community.plist /Library/LaunchAgents/

launchctl load -w /Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

launchctl start mongodb-community

A: This is an error with the mongodb-community formula. An issue has been filed with the maintainers, a solution found, and a pull request with the fix opened.
In the meantime, you can fix the error yourself. This line in the formula is throwing an exception:
Gem::Version.new(v['version'])

because the Gem class has not been imported. Adding the import:
require 'rubygems'

solves the problem. You can do this locally, by finding and editing the formula on your computer. It is probably in this file:
/usr/local/Homebrew/Library/Taps/mongodb/homebrew-brew/Formula/mongodb-community.rb

Update: A community contributor has fixed this upstream. If you are still experiencing this issue you might need to run brew update


text:
Q: Can you make mockito (1.10.17) work with default methods in interfaces? I am a big fan of mockito, unfortunately for one of my projects which uses Java 8, it fails on me...
Scenario:
public final class MockTest
{
    @Test
    public void testDefaultMethodsWithMocks()
    {
        final Foo foo = mock(Foo.class);

        //when(foo.bar()).thenCallRealMethod();

        assertThat(foo.bar()).isEqualTo(42);
    }

    @FunctionalInterface
    private interface Foo
    {
        int foo();

        default int bar()
        {
            return 42;
        }
    }
}

Unfortunately, the test fails and foo.bar() returns 0.
When I uncomment the when() line, I get a stack trace...
java.lang.NoSuchMethodError: java.lang.Object.bar()I
    at com.github.fge.lambdas.MockTest.testDefaultMethodsWithMocks(MockTest.java:18)

This is the latest stable version available on maven; googling around didn't tell me much about the status of mockito with regards to this new functionality in Java 8...
Can you make it work in some other way than implementing interfaces and spy() on them (this works)?

A: Mockito (this works on version 3) can use default methods. Here's the example code rewritten with JUnit 5 so it should work:
@ExtendWith(MockitoExtension.class)
class MockTest {
    @Mock(answer = Answers.CALLS_REAL_METHODS)
    private Foo foo;

    @Test
    void testDefaultMethodsWithMocks() {
        assertThat(foo.bar()).isEqualTo(42);
    }

    @FunctionalInterface
    private interface Foo {
        int foo();

        default int bar() {
            return 42;
        }
    }
}

The calls real methods answer DOES work in the latest Mockito. As a general rule, the extensions make the creation of mocks more declarative, but the mock method also provides an overload which supports the default answer as shown in the @Mock annotation above: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#mock-java.lang.Class-org.mockito.stubbing.Answer-

A: You can get around this limitation by implementing the interface (tested in Mockito 1.10.19):
public class TestClass {
  @Mock ImplementsIntWithDefaultMethods someObject;

  @Test public void test() throws Exception {
    // calling default method on mocked subtype works
    someObject.callDefaultMethod();
  }

  /* Type that implements the interface */
  static class ImplementsIntWithDefaultMethods implements IntWithDefaultMethod { }

  /* Interface you need mocked */
  interface IntWithDefaultMethod {
    default void callDefaultMethod { }
  }
}

A: I just ran into the same issue with Mockito (org.mockito:mockito-core:1.10.19). Problem is: I'm not able to change the Mockito version (2.7.22 would work) because of dependencies to org.springframework.boot:spring-boot-starter-test:1.4.3.RELEASE which we are using (Spring, Mockito issue).
The easiest solution I found is to implement the interface with a private abstract class within my test class and mocking that one (also compare to the solution of @Mihai Bojin). Doing it like this keeps you away from the hassle to also "implement" all methods required by the interface(s).
MWE:
public interface InterfaceWithDefaults implements SomeOtherInterface {
    default int someConstantWithoutSense() {
        return 11;
    }
}

public class SomeTest {
    private abstract class Dummy implements InterfaceWithDefaults {}

    @Test
    public void testConstant() {
        InterfaceWithDefaults iwd = Mockito.mock(Dummy.class);

        Assert.assertEquals(11, iwd.someConstantWithoutSense());
    }
}

A: With mockito 2.x, JDK 8 default methods are supported.
With mockito 1.x it's not possible,

Old answer
Unfortunately it's not yet possible (mockito 1.10.19), from the README.md on the github'page

JDK8 status
Mockito should work fine with JDK8 if you stay away from default methods (aka defender methods). Lambda usage may work just as good for Answers. We're unsure about every JDK8 features at the moment, like serializing a mock that uses a lambda. Error report and pull request are welcome though (contributing guide).

EDIT 1: defender methods and default methods are different names for the same thing.
I hope for a mockmaker replacement that will handle java 8 opcodes properly for such cases as some opcodes have a different semantic in Java 8.
EDIT 2: Updated the mockito readme, and this quote accordingly

A: I just tried Mockito 2.0.38-beta, and it already works in that version. But Mockito must be told explicitly to call the default implementation.
Foo foo = mock(Foo.class);
assertThat(foo.bar()).isEqualTo(0);

when(foo.bar()).thenCallRealMethod();
assertThat(foo.bar()).isEqualTo(42);

A: Another solution would be to use a Spy as described here: https://stackoverflow.com/a/54915791/3636822

A: Just a litte side note that especially functional interfaces can be easily created without mocking. If you need to call some verify methods afterwards, you may wrap the instance into a spy.
public final class MockTest
{
    @Test
    public void testDefaultMethodsWithMocks()
    {
        final Foo foo = () -> 0;

        assertThat(foo.bar()).isEqualTo(42);
    }

    @FunctionalInterface
    private interface Foo
    {
        int foo();

        default int bar()
        {
            return 42;
        }
    }
}

Sometimes we are so used to work with these frameworks that we easily forget about the obvious solutions.


text:
Q: Start new Android activity from JNI I managed to call a java method from JNI, but if from JNI I call a java method where there is startActivityForResult (), the activity does not start and I always have a black screen.
In JNI that method is called inside the onMessage method.
I have implemented a socket in c++ with boost.

Can you help me?
This is my JNI method
jclass clazz = env->FindClass("com/example/SDKCallsActivity");
        jmethodID sendHandshake = env->GetMethodID(clazz, "socketOpen", "()V");
        phase = phase + 1;
        env->CallVoidMethod(obj, sendHandshake);

This is my Java method
@Override
    public void socketOpen() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingDialog.dismiss();
            }
        });

        startActivityForResult(callingIntent, 1001);
    }

UPDATE 2022/05/29
I solved the problem. The cause was that the C++ websocket in boost starts a loop and the call does not arrive at that point. In fact, by stopping the web socket, I can start the activity.
So I had to create a thread and connect the websocket in c++ in this thread. The startActivity() I do it before the creation of the thread.


text:
Q: Windows device coordinates vs virtual coordinates I've tried to find an answer for this on MSDN, but I'm not getting a clear picture of how this is intended to work.  All of my work is on Windows 8.1.
Here is my issue.  I am working on a Laptop with a high resolution monitor, 3200x1800.  I've been using EnumDisplayMonitors to get the bounding rectangle of my screen.
This seems to work fine if my display settings are default.  But I've noticed that when I change the Window display settings to provide larger text, the resolution returned by EnumDisplayMonitor changes.  Rather than getting 3200x1800 I will get 2133x1200.
I'm guessing since I asked for larger text, Windows chooses to represent the screen as a smaller resolution.
It seems that if I look at the virtual screen properties, everything is represented in the actual coordinates of my screen, i.e. 3200x1800.  But the APIs for getting the window and monitor rectangles seem to operate on this "other" coordinate space.
Is there any documentation/Windows APIs to handle the conversion between these "other coordinates" and the "virtual coordinates"?  i.e. if I want EnumDisplayMonitor or GetMonitorInfo to give me the true screen coordinates, how could I convert 2133x1200 to 3200x1800?

A: You have increased the DPI of the video adapter to 150% (144 dots per inch) to keep text readable and avoid having windows the size of a postage stamp.  Quite necessary on such high resolution displays.  But you haven't told Windows that your program knows how to deal with it.
So it assumes your program is an old one that was never designed to run on such monitors.  It helps and lies to you.  It gets your program to render its output to a memory buffer, then takes that output, rescales it by 150% and copies it to the video adapter.  This is something you can see, text looks fuzzier if you put your program's output next to a program that doesn't ask for this kind of scaling, like Notepad.
And of course, it lies to you when you ask for the size of the screen.  It tells you that it is 150% smaller than it really is.  So that, after rescaling, a window you create will fill the screen.
Which is all just fine but of course not ideal, your program doesn't look as good as it should.  You have to tell Windows that you know how to deal with the higher resolution.  Do beware that this looks easier than it is in practice.  Getting text to look crisp is trivial, it is bitmaps that are problematic.  And in general a fertile source of bugs, even the big companies can get this wrong.

A: Before I start with an answer, let me ask: what are you really trying to do ?  Or more specific - why do you need to know the monitor resolution ?  The standard way to do this is to call GetWindowRect(GetDesktopWindow(), &rect)  I'm not sure if the screen coordinates change based on DPI settings - but you should try that instead of GetMonitorInfo as the latter is for more advanced stuff.  And if GetWindowRect still returns back a scaled rect, just call DPtoLP, LPtoDP or other mapping coordinate function as appropriate.
When you adjust the display settings as you described, you are actually changing the DPI settings of the screen. As such, certain APIs go into compatibility mode so that they allow the app to create larger elements and windows without knowing anything about this setting.
Why do you need to know the actual screen resolution since most of the windowing APIs will behave accordingly when the DPI scaling changes?
I suspect you could call SetProcessDPIAware or the manifest file equivalent. But do read this MSDN article first to understand DPI scaling.


text:
Q: Problem uploading multiple images to firebase I am trying to upload multiple images to firebase but could not get it working.
This is array I am getting after putting all the images in to image input
 ['blob:http://localhost:3000/dbc79d01-d608-46a2-a808-dcf47a4317a0', 'blob:http://localhost:3000/c26ae24b-6066-432f-8f67-5b7f38439bec', 'blob:http://localhost:3000/9e0f4db4-50c2-42d9-a468-4e21db531de3']
This is the code for single image upload which is working but not for these blobs. I am getting blobs not image files. Should I convert them into files before uploading?  If yes how?
If I change const uploadTask = uploadBytes(imageRef, imageUpload[0]) still does not work.
const uploadImage = async () => {
try {
  if (imageUpload == null) return;
  const imageRef = storageref(
    storage,
    `images/${uuid}`
    // + ${imageUpload.name}
  );
  const uploadTask = uploadBytes(imageRef, imageUpload);
  uploadTask.on(
    "state_changed",
    (snapshot) => {
      // progrss function ....
      const progress =
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log("Upload is " + progress.toFixed() + "% done");
    },
    (error) => {
      // error function ....
      console.log(error);
    },
    () => {
      // complete function ....
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log(downloadURL);
      });
    }
  );
} catch (error) {
  throw error;
}