text:
Q: Pre-populating Room using Koin and DB Browser I need to pre-populate a table in Room using a .csv file.
I saw in https://developer.android.com/training/data-storage/room/prepopulate that I needed a .db file instead so I used DB Browser to import my .csv and create a .db file.
I added my .db file to folder /assets and created an abstract class for my database, a dao and a data class, then added it in Koin using .createFromAsset.
It's not creating anything though (I am checking in App Inspection). Not throwing any errors. Nothing.
The .csv has around 20k entries.
This is my abstract class
@Database(entities = [PlantInfo::class], version = 1)
abstract class PlantInfoDB: RoomDatabase(){
    abstract fun plantInfoDao(): PlantInfoDao
}

This is my DAO

@Dao
interface PlantInfoDao {
    @Query("SELECT * FROM PlantInfo")
    fun getAllPlantInfo(): List<PlantInfo>
}

This is my Data Class
@Parcelize
@Entity(tableName = "PlantInfo")
data class PlantInfo(
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "scientificName") val scientificName: String,
    @ColumnInfo(name = "commonName") val commonName: String,
    @ColumnInfo(name = "family") val family: String,
    @ColumnInfo(name = "description") val description: String,
    @ColumnInfo(name = "cultivation") val cultivation: String,
    @ColumnInfo(name = "light") val light: Int,
    @ColumnInfo(name = "water") val water: Int,
    @ColumnInfo(name = "disease") val disease: String,
    @ColumnInfo(name = "img") val img: String
) : Parcelable

My KoinGraph
object KoinGraph {

    val mainModule = module {

        single {
            Room.databaseBuilder(get(), PlantInfoDB::class.java, "PlantInfo")
            .createFromAsset("plants_db.db")
            .build()
        }

      single {
            Room.databaseBuilder(get(), AppDB::class.java, "AppDB")
                .build()
        }

        single { get<AppDB>().waterDao() }
        single { get<AppDB>().plantDao() }
        single { get<PlantInfoDB>().plantInfoDao() }
        factory { WaterAlarm(get()) }
        single { WaterRepository() }
        single { PlantIdRepository() }
        single { RandomQuotesRepository() }
        viewModel { SearchByPictureViewModel(get()) }
        viewModel { AddPlantPictureViewModel() }
        viewModel { HomePlantViewModel(get(), get()) }
        viewModel { PlantFormViewModel(get()) }
    }
}

This is my DB Browser file structure
CREATE TABLE "PlantInfo" (
    "id"    INTEGER NOT NULL UNIQUE,
    "scientificName"    TEXT,
    "commonName"    TEXT,
    "family"    TEXT,
    "description"   TEXT,
    "cultivation"   TEXT,
    "light" INTEGER,
    "water" INTEGER,
    "disease"   TEXT,
    "img"   TEXT,
    PRIMARY KEY("id")
)

Any help appreciated.


text:
Q: How to verify if props is valid element OR functional component? I've some problem to verify if props passing to CustomComponent is a valid react jsx especially in React Native
Let say my CustomComponent is:
import React from 'react';
import {View, Text} from 'react-native';

export default CustomComponent = props => {
  const RenderHeader = () => {
    if (React.isValidElement(props.headerComponent))
      return props.headerComponent;
    else return null;
  };

  return (
    <View style={{ flex: 1, ...props.style }}>
      <RenderHeader />
    </View>
  );
};

I want to use my CustomComponent something like this:
const Header = () => {
  return <Text style={{ textAlign: "center" }}>What is your birthday?</Text>;
};
/**  rendered */
1. <CustomComponent headerComponent={} />

/**  not render */
2. <CustomComponent headerComponent={()=> } />

/** Header not render */
3. <CustomComponent headerComponent={Header} />

How to let my CustomComponent accept two more syntax above and render properly?

A: try this :

const CustomComponent = props => {
  const RenderHeader = () => {
      return props.headerComponent instanceof Function ? props.headerComponent() : props.headerComponent
  };

  return (

      <RenderHeader />

  );
};

const Header = () => {
  return
What is your birthday?
;
};

const Example = () => {
    return (

          <CustomComponent headerComponent={} />
          <CustomComponent headerComponent={()=> } />
          <CustomComponent headerComponent={Header} />

    );
};

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <Example />
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: rails: change image on click when image url is dynamic I use Rails 4 and have a page with one large image and 6 thumbnails.
When a user clicks on one of the thumbnails then the large image should change to the one of the clicked thumbnails.
in my app/views/products/show.html.erb:

     <%= image_tag product_image_url(@product, type: :three_quarter, color: colors.first), itemprop: "image", class: 'teaser' %>

        <% type_map.except(:thumb, :reversiblefront).each_with_index do |type, index| %>

      <%= image_tag product_image_url(@product, type: type, color: colors.first), itemprop: "image", class: 'thumbnail' %>

        <% end %>

I used to have image files in app/assets/images and implemented this feature with jQuery.
In app/assets/javascripts/application.js:
// change teaserimage on thumbnail-click
$(function() {
  var images = [
    "/assets/Nile_1_16_0119.jpg", "/assets/Nile_1_16_0095.jpg",
    "/assets/Nile_1_16_0131.jpg", "/assets/Nile_1_16_0144.jpg",
    "/assets/thumb_midnight.jpg", "/assets/back_midnight.jpg"
  ];

  $(".thumbnail").click(function() {
    var index = $(this).parent().index();
    $('img.teaser').attr('src', images[index]);
    $(this).parent().siblings().removeClass('active');
    $(this).parent().addClass('active');
  });
});

How can I achieve that when the image Urls are dynamic?
app/helpers/products_helpers.rb:
module ProductsHelper
  def product_image_url(product, type:, color:)
    source = URI.escape "#{product_image_base_url}/#{collection_folder(product)}/"\
                        "#{product_number(product)}_#{product_type(type)}"\
                        "_#{format_color_name(color.name)}.jpg"
    image_exist?(source, product) ? source : false
  end

  def product_image_base_url
    ENV['PRODUCT_IMAGE_BASE_URL']
  end

  def product_number(product)
    product.number.strip.upcase
  end

  def product_type(type)
    type_map.fetch(type)
  end

  def type_map
    @type_map ||= {
      full: "01",
      three_quarter: "02",
      medium: "03",
      close_up: "04",
      front: :front,
      back: :back,
      thumb: :thumb,
      reversiblefront: :reversiblefront
    }
  end
end

A: Like Hardik suggested i could just replace in my js-code the images array with the thumbnail image urls:
var productImages = $("img.thumbnail").map(function() {
    return this.src;
}).get();

I had misleadingly something with precompiled assets in mind when i was asking. Thanks Hardik for guiding me to the right direction!


text:
Q: Exponential in Excel 2007 How to find exponential calculation for [1-(1+0.025)^-2] in Ms-Excel 2007.
When i do this in calculator i got 0.048185604 as result.
I already tried like this in excel
=1-((1+0.025)*EXP(-2)) .

I got 0.861281335 as result.
I didn't get expected result.
Kindly help me.

A: Enter it in Excel, preceded with an equal sign:
=1-(1+0.025)^-2

Result:  0.0481856038072576


text:
Q: Row dissapears when checkbox in header is checked in Datatables I'm using jquery Datatables and have a problem: when I'm checking checkbox in header, rows below disappears and I receive "No matching records found" message. There are no js functions attached to this checkbox. I've tried to create checkbox in html, then I've tried to declare it in jquery:
"aoColumnDefs": [ { "sTitle": "<input type='checkbox' id='APP_CHECK_ALL'></input>","aTargets": [0] }]

both variants are not working. Did anybody have this problem?


text:
Q: Can't obtain variable I'm trying to prove the following simple theorem I've come up with, that:

A point is on the boundary iff any small enough ball around that point contains points both in S and out of S.

Below I've managed to do the forward direction but I'm stuck on the backwards direction.
Using the same approach fails on the last step, the goal is close but not quite there, and I'm not sure what to do here:
lemma frontier_ball: "x ∈ frontier S ⟷
  (∃r>0. (∀δ>0. δ<r ⟶ ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})))"
  (is "?lhs = ?rhs")
proof
  {
    assume "?lhs"
    hence "x ∉ interior S ∧ x ∉ interior (-S)" by (auto simp: frontier_def interior_complement)
    hence "∀δ>0. ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})" by (auto simp: mem_interior)
    then have "?rhs" by (simp add: Orderings.no_top_class.gt_ex)
  }
  {
    assume "¬?lhs"
    hence "x ∈ interior S ∨ x ∈ interior (-S)" by (auto simp: frontier_def interior_complement)
    hence "∃δ>0. ball x δ ∩ S = {} ∨ ball x δ ∩ -S = {}" by (auto simp: mem_interior)
    then have "¬?rhs" by (simp add: subset_ball)
  }
qed

I tried to tell isabelle how to obtain such a delta but it's stuck on the obtain step:
lemma frontier_ball: "x ∈ frontier S ⟷
  (∃r>0. (∀δ>0. δ<r ⟶ ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})))"
  (is "?lhs = ?rhs")
proof
  {
    assume "?lhs"
    hence "x ∉ interior S ∧ x ∉ interior (-S)" by (auto simp: frontier_def interior_complement)
    hence "∀δ>0. ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})" by (auto simp: mem_interior)
    then have "?rhs" by (simp add: Orderings.no_top_class.gt_ex)
  }
  {
    fix r::real
    assume "¬?lhs ∧ r>0"
    hence "x ∈ interior S ∨ x ∈ interior (-S)" by (auto simp: frontier_def interior_complement)
    then obtain r2 where "r2>0" and "ball x r2 ∩ S = {} ∨ ball x r2 ∩ -S = {}" by (auto simp: mem_interior)
    then obtain δ where "δ>0 ∧ δ<r ∧ δ<r2" by auto

  }
qed

Any pointers would be great!

A: Well, you can just construct such a δ. If you have r > 0 and r2 > 0 you want some δ that fulfils 0 < δ ≤ r2 and 0 < δ < r, why not just use min r2 (r/2)? You can define δ to be that and then you can prove the properties you want:
    def δ ≡ "min r2 (r/2)"
    with r2 A have δ: "δ > 0" "δ < r" "δ ≤ r2" by auto
    with r2 have δ': "ball x δ ∩ S = {} ∨ ball x r2 ∩ -S = {}" using subset_ball[OF δ(3)] by auto

Or, a bit more direct:
lemma frontier_ball: "(x :: 'a :: {metric_space}) ∈ frontier S ⟷
  (∃r>0. (∀δ>0. δ<r ⟶ ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})))"
  (is "?lhs = ?rhs")
proof -
  {
    assume "?lhs"
    hence "x ∉ interior S ∧ x ∉ interior (-S)" by (auto simp: frontier_def interior_complement)
    hence "∀δ>0. ((ball x δ) ∩ S ≠ {} ∧ (ball x δ) ∩ -S ≠ {})" by (auto simp: mem_interior)
    then have "?rhs" by (simp add: Orderings.no_top_class.gt_ex)
  }
  moreover
  {
    assume lhs: "¬?lhs"
    {
      fix r :: real assume r: "r > 0"
      from lhs have "x ∈ interior S ∨ x ∈ interior (-S)"
        by (auto simp: frontier_def interior_complement)
      then obtain δ where "δ > 0" "ball x δ ∩ S = {} ∨ ball x δ ∩ -S = {}"
        by (auto simp: mem_interior)
      with r have "min δ (r/2) > 0" "min δ (r/2) < r"
        "ball x (min δ (r/2)) ∩ S = {} ∨ ball x (min δ (r/2)) ∩ -S = {}" using subset_ball by auto
      hence "∃δ>0. δ < r ∧ (ball x δ ∩ S = {} ∨ ball x δ ∩ -S = {})" by blast
    }
    hence "¬?rhs" by blast
  }
  ultimately show ?thesis by blast
qed

For the record, I would avoid doing things like assume "A ∧ B". Do assume "A" "B" instead. That gives you two facts that you can work with directly, instead of having them wrapped up with a HOL conjunction in one fact.


text:
Q: Organizing .html.erb and .js.erb files within a view directory I have a view directory called blogs.  Within that directory you can find all the standard, conventional html view templates:
# html files within the app/views/blogs directory
  _form.html.erb
  edit.html.erb
  index.html.erb
  new.html.erb
  show.html.erb

However: I also have some ajax views that dynamically change content on pages (mostly just content on the form).  currently they are all all mixed in with the .html.erb files which feels kind of cluttered and unorganized:
# now showing the html AND js files within the app/views/blogs directory
  _form.html.erb
  add_foobar.js.erb
  add_barbazz.js.erb
  edit.html.erb
  filter_by_team.js.erb
  filter_by_city.js.erb
  filter_by_state.js.erb
  index.html.erb
  new.html.erb
  show.html.erb

I think it would make sense to seperate the .html.erb files from the js.erb files, though I am not sure how to do this because they all belong within the blogs directory.
How can I organize the .js.erb and .html.erb files within this directory?

A: Why don't you place the .js files in another directory and use content_for to inject them. like this -
http://www.railscook.com/recipes/how-to-organize-page-specific-javascript/

A: You could say to your action where exactly template is
respond_to do |format|
  format.js { render "blogs/js/filter_by_team" }
end

And place js template into views/blogs/js


text:
Q: How do I fix broken networking in cloned virtual machines? I've set up a virtual machine configured with bridge networking. After making eight clones of it, the new machines can't connect to the network.
I've instructed VirtualBox to re-generate the machines' mac-addresses.

A: Refresh your MAC address using Virtual Box machine settings and
remove the kernel's networking interface rules file so that it can be regenerated:
sudo rm -f /etc/udev/rules.d/70-persistent-net.rules
sudo reboot

It will work for your clone VM.

A: I was dealing with the same problem for months and today I decided I would find a better fix.  Here is what I did on the machine I was using as a Template.
For good administration practices back up both files before editing.
You have two offending/target files:

*

*/etc/sysconfig/network-scripts/ifcfg-eth0

*/etc/udev/rules.d/70-persistent-net.rules
This will work for a static or dhcp address:
Open /etc/sysconfig/network-scripts/ifcfg-eth0
Delete the MAC Address line:  HWADDR=XX:11:22:XX:33:XX
Save the file.
Delete the file /etc/udev/rules.d/70-persistent-net.rules "it will be recreated after you restart the VM"
sudo rm -f /etc/udev/rules.d/70-persistent-net.rules

You can now clone your box and every clone will correctly deploy and display eth0.
If you do not use a template, you may complete these procedures on the actual VM just remember to re-initialize the NIC your in the VM software before you restart the machine.

A: There are udev rules preventing the new interface from being brought up.
In the Master machine, just delete them before you clone the new machines:
sudo rm -f /etc/udev/rules.d/70-persistent-net.rules

(source)

A: I encountered the same problem on a previous version of VirtualBox and I read somewhere that there was a bug which rendered the "generate new MAC address" tick box useless.
I'm now using Ubuntu 12.04 with VirtualBox 4.2.10. I noticed now that when I created the clone, there was no tick box to "generate new MAC address."
This gave me some problems even if I deleted 70-persistent-net.rules because the system would automatically generate the file on startup with the same MAC address as the original, which made it fail to connect.
But I discovered that in VirtualBox Manager, you can select the clone, go to Settings>Networking>Advanced and generate a new MAC address by ticking the box.
So what I did was to delete 70-persistent-net.rules first, shut down, generate new MAC address and start again, and now it works.
Alternatively, you can delete the file first before you clone. Then generate MAC address, then start the clone. That ought to work as well.

A: I am building parallel computing environment that needs interconnection between the virtual machine through ip network.
I think there is something related to the re-generate the machines' mac-addresses.
I had faced the similar problem before.
The original virtual machine has eth0 and eth1. But due to the regenerating process,
in my case, the new cloned machine has eth2 and eth3. you can check it by this following command:
ifconfig -a | grep eth

You can check with ifconfig command that in the new cloned machine has only lo registered. Generally, you should have lo, eth0, and eth1 when you type ifconfig command.
That is due to MAC regeneration that in the clone machine, there are eth2 and eth3 Ethernet interfaces instead of eth0 and eth1 in the original machine. You can also check the /etc/network/interfaces in the original machine that in my case will appears like:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet static

address 192.168.xxx.xxx
netmask 255.xxx.xxx.0
network 192.168.xxx.0
broadcast 192.168.xxx.255
gateway 10.0.x.xx

May be you can modify your /etc/network/interfaces file and change the eth0 and eth1 with eth2 and eth3, which more or less like this:
auto lo
iface lo inet loopback

auto eth2
iface eth2 inet dhcp

auto eth3
iface eth3 inet static

address 192.168.xxx.xxx
netmask 255.xxx.xxx.0
network 192.168.xxx.0
broadcast 192.168.xxx.255
gateway 10.0.x.xx

So, good luck guys!

A: I deleted 70-persitent-net.rules file but it wasn't re-created after reboot. Then, re-installing guest additions module and rebooting the VM worked for me.

A: I have problem with same ip-address after cloning 3 VMs with Virtual BOX (4.3). SO I have power off the machines and regenerated new mac address and restarted it worked for me.
steps => switch off the cloned VM and then settings => network => advanced => click on refresh MAC address => clik OK. then start VM.

A: I was facing the same issue after cloning ubuntu-server-20.x image. I was using nat-service. What worked for me was the following.

*

*Refresh the mac by going to network setting (small refresh icon next to mac address).

*On guest machine, run the following two commands to force refresh ip address from DHCP server.

sudo dhclient -r eth0
sudo dhclient eth0


text:
Q: Find all possible combinations of compatible elements I have set
{A,B,C,D,E}

And I have a map (someMapWithSets in the code example) of sets which indicates if elements are compatible:
A: B,C - (means A is compatible with B and C and etc)
B: A,E,C
C: A,B
D: E
E: B,D

I need to have a map of sets where all possible combinations of compatible elements are present (largest set possible) with values like (don't care about key):
A,B,C
B,E
D,E

So as I part of the solution I thought I could create a method that retains only compatible elements for the given set and chosen element.
public static Map<String, Set<String>> defineCompatibility(Set<String> set) {
    if (set.isEmpty()) {
        return new HashMap<>();
    }
    Map<String, Set<String>> finalResult = new HashMap<>();
    Set<String> elementsToDefine = new HashSet<>(set);
    while (!elementsToDefine.isEmpty()) {
        String currentElement = elementsToDefine.stream().findFirst().get();
        Set<String> definedSet = defineForElement(set, currentElement);
        finalResult.put(currentElement, definedSet);
        elementsToDefine.remove(currentElement);
    }
    return finalResult;
}

private static Set<String> defineForElement(Set<String> set, String rootElement) {
    Set<String> result = someMapWithSets.get(rootElement);
    result.retainAll(set);
    result.add(rootElement);
    Set<String> tmpHolder = new HashSet<>(result);
    for (String next : tmpHolder) {
        if (!result.contains(next)) {
            break;
        }
        Set<String> strings = someMapWithSets.get(next);
        strings.add(next);
        result.retainAll(strings);
    }
    return result;
}

But this code does not work properly because it is not capable to define all possible combinations, only a few of them. I've tried to store data about elements that were not processed but the code became very complex to be understandable.
I am stuck with implementation. Please help. Maybe there is some well-known algorithm for this task? Thank you.

A: Bron-Kerbosch is used in result.
https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm
https://iq.opengenus.org/bron-kerbosch-algorithm/
Brute force code looks like this
private static void define(Set<String> r, Set<String> p, Set<String> x) {

    if (p.isEmpty() && x.isEmpty()) {
        System.out.println("Here is maximal clique: " + r);
        return;
    }

    Set<String> p1 = new HashSet<>(p);

    for (String v : p) {
        r.add(v);
        define(r, intersect(p1, someMapWithSets.get(v)), intersect(x, someMapWithSets.get(v)));
        r.remove(v);
        p1.remove(v);
        x.add(v);
    }
}

    private static Set<String> intersect(Set<String> first, Set<String> second) {
    Set<String> holder = new HashSet<>(first);
    holder.retainAll(second);
    return holder;
}


text:
Q: How to give everyone access to a office@companyname address and let everyone see what messages were answered This should be simple (because I assume everyone has this problem) but googling and searching of serverfault didn't help much.
I'd like all messages sent to our "office@companyname" to be visible by everyone and I'd like anyone to be able to respond. I also need everyone to at least SEE that a given message has already been answered (the ability to see the actual response would be nice).
I tried using an shared folder for this but it fails miserably because replying to emails leaves no trace, not even for the user that actually sent the message.
I'm open to any kind of solution, even commercial add-on solutions.
EDIT: Upgrading to Outlook 2010 or Exchange 2010 are not viable options because of cost.

A: You could try this with Exchange 2007:

*

*Create a user with a mailbox called: Office with office@domain.com email address.

*Create a group of people who have full access and send on behalf permissions for said Office mailbox.

*Add your end users to the group.

*Have the users in the group (In their Outlook clients) have access to this mailbox via File -> Open -> Other Users Mailbox OR a setup in their email accounts area (Tools -> Email Accounts).

*When one of your end users responds to an email sent to office@domain.com, get them to set the From field to office@domain.com so that the corespondent can easily reply back to the office@domain.com address. You can enable this option when sending an email with View -> From field.

I'm making a few assumptions here about your network but this is a method that we used to use before we switched to our helpdesk@domain.com mailbox to a distribution group called Helpdesk for various reasons.

A: Probably best solution currently around:

*

*Drop the shared folder. Go with a shared mailbox

*Upgrade to Office 2010, possibly exchange 2010, but I Think it should work without.

Outlook 2010 allow one to open multiple mailbxes at the same level - so you give everyone rights to the office mailbox, and everyone interested can open the office mailbox as second mailbox (I currently have three open). THen answers etc. go into the office mailbox, too.
Pre Outlook 2010 support for that was sluggish at best (and that is the nice way to say it). Handling mulötiple mailboxes was simply only painfull. Not it is doable.


text:
Q: Audio input for Apple MacBook Air M1 There is no input on my Apple MacBook Air M1. From sound it only has internal mic with no external option. Tried recording to Garage Band but cannot record.

A: You could use a Bluetooth audio adaper, or, as suggested in comments, a USB-to-audio adapter.
That said, some users of the MacBook Air M1 have found Bluetooth connectivity issues.


text:
Q: Help with SEM modeling (OpenMx, polycor) I have lots of problem with one data set to which I am trying to apply SEM.
We suppose the existence of 5 latent factors A, B, C, D, E, with indicators resp. A1 to A5 (ordered factors), B1 to B3 (quantitative), C1, D1, E1 (all last three ordered factors, with only 2 levels for E1. We are interested in covariances between all factors.
I tried to use OpenMx to do so. Here are a few of my attempts:

*

*I first tried to use thresholds matrices for all the ordered factors, but the convergence failed.

*I decided to use polychoric/polyserial correlations instead of raw data, with the function hetcor from the library polycor (I planned to bootstrap the sample to get confidence intervals). It also fails to converge!

*I tried to restrict to individuals with complete data, it fails too!
My first question is: is there a natural way to interpret these failures?
My second question is: what should I do???
Edit: for future readers who may encounter the same problem, after going through the code of the functions in polycor... the solution is simply to use hetcor() with the option std.err=FALSE. This gives estimates very similar to those StasK gave. I lack time now to understand better what's going on here! The questions below have been pretty well answered by StasK.
I have other questions, but before anything, here is a url with a RData file containing a data frame L1 containing only the complete data: data_sem.RData
Here a few lines of codes showing the failure of hetcor.
> require("OpenMx")
> require("polycor")
> load("data_sem.RData")
> hetcor(L1)
Erreur dans cut.default(scale(x), c(-Inf, row.cuts, Inf)) :
  'breaks' are not unique
De plus : Il y a eu 11 avis (utilisez warnings() pour les visionner)
> head(L1)
   A1 A2 A3 A4 A5       B1       B2       B3 C1 D1 E1
1   4  5  4  5  7 -0.82759  0.01884 -3.34641  4  6  1
4   7  5  0  4  6 -0.18103  0.14364  0.35730  0  1  0
7   7  5  7  6  9 -0.61207 -0.18914  0.13943  0  0  0
10  5  5 10  7  3 -1.47414  0.10204  0.13943  2  0  0
11  7  5  8  9  9 -0.61207  0.06044 -0.73203  0  2  0
12  5  5  9 10  5  0.25000 -0.52192  1.44662  0  0  0

But I can still compute a correlation or a covariance matrix in a very dirty way, considering my ordered factors as quantitative variables:
> Cor0 <- cor(data.frame(lapply(L1, as.numeric)))

Here is a piece of OpenMx code together with my next question: is the following model correct? Not too much free parameters?
manif <- c("A1","A2","A3","A4","A5", "B1","B2","B3", "C1", "D1", "E1");

model1 <- mxModel(type="RAM",
        manifestVars=manif, latentVars=c("A","B","C","D","E"),
        # factor variance
        mxPath(from=c("A","B","C","D","E"), arrows=2, free=FALSE, values = 1),
        # factor covariance
        mxPath(from="A", to="B",  arrows=2, values=0.5),
        mxPath(from="A", to="C",  arrows=2, values=0.5),
        mxPath(from="A", to="D",  arrows=2, values=0.5),
        mxPath(from="A", to="E",  arrows=2, values=0.5),
        mxPath(from="B", to="C",  arrows=2, values=0.5),
        mxPath(from="B", to="D",  arrows=2, values=0.5),
        mxPath(from="B", to="E",  arrows=2, values=0.5),
        mxPath(from="C", to="D",  arrows=2, values=0.5),
        mxPath(from="C", to="E",  arrows=2, values=0.5),
        mxPath(from="D", to="E",  arrows=2, values=0.5),
        # factors → manifest vars
        mxPath(from="A", to=c("A1","A2","A3","A4","A5"), free=TRUE, values=1),
        mxPath(from="B", to=c("B1","B2","B3"), free=TRUE, values=1),
        mxPath(from="C", to=c("C1"), free=TRUE, values=1),
        mxPath(from="D", to=c("D1"), free=TRUE, values=1),
        mxPath(from="E", to=c("E1"), free=TRUE, values=1),
        # error terms
        mxPath(from=manif, arrows=2, values=1, free=TRUE),
        # data
        mxData(Cor0, type="cor",numObs=dim(L1)[1])
       );

And one last question. With this model (let's forget for a moment the inappropriate way the correlation matrix is computed), I run OpenMx:
> mxRun(model1) -> fit1
Running untitled1
> summary(fit1)

among the summary, this:
observed statistics:  55
estimated parameters:  32
degrees of freedom:  23
-2 log likelihood:  543.5287
saturated -2 log likelihood:  476.945
number of observations:  62
chi-square:  66.58374
p:  4.048787e-06

The fit seems very bad, despite the huge number of parameters. What does that mean? Does that mean that we should add covariances between manifest variables?
Many thanks in advance for all your answers, I am slowly becoming insane...

A: You must have uncovered a bug in polycor, which you would want to report to the John Fox. Everything runs fine in Stata using my polychoric package:
    . polychoric *

    Polychoric correlation matrix

               A1          A2          A3          A4          A5          B1          B2          B3          C1          D1          E1
   A1           1
   A2   .34544812           1
   A3   .39920225   .19641726           1
   A4   .09468652   .04343741   .31995685           1
   A5   .30728339   -.0600463   .24367634   .18099061           1
   B1   .01998441  -.29765985   .13740987   .21810968   .14069473           1
   B2  -.19808738   .17745687  -.29049459  -.21054867   .02824307  -.57600551          1
   B3   .17807109  -.18042045   .44605383   .40447746   .18369998   .49883132  -.50906364           1
   C1  -.35973454  -.33099295  -.19920454  -.14631621  -.36058235   .00066762  -.05129489  -.11907687           1
   D1   -.3934594  -.21234022  -.39764587  -.30230591  -.04982743  -.09899428   .14494953   -.5400759   .05427906           1
   E1  -.13284936   .17703745  -.30631236  -.23069382  -.49212315  -.26670382   .24678619  -.47247566    .2956692   .28645516           1

For the latent variables that are measured with a single indicator (C, D, E), you need to fix the variance of the indicator in the continuous version of it, as otherwise the scale of the latent variable is not identified. Given that with binary/ordinal responses, it is fixed anyway to 1 with (ordinal) probit-type links, it probably means that you would have to postulate that your latent is equivalent to the observed indicator, or you have to postulate the standardized loading. This essentially makes your model equivalent to a CFA model where you have latent factors A and B measured with {A1-A5, C1, D1, E1} and {B1-B3, C1, D1, E1}, respectively.


text:
Q: Mule adding element to XML message I'm trying to do what i think should be a very simple task.
In a mule flow, read in an xml file, add a xml element at a particular location. and then write the xml to another file.
XSLT would be a pretty good tool here, however for my test i'm trying to avoid using xslt. I've thought about using a java or groovy transformer and a XML parser to do this and i can fall back on that if needed. however the simplest approach that i can think of
XML-to-maps, then a script to update the value then maps-to-xml returns a completely empty record.
How can i do this without using xslt and preferably not using jaxb or another xml parser outside of what's built into mule?
EDIT: I've played with the data mapper a bit, but for xml-xml mapping it requires a schema, and i won't know this at run time

A: The simplest approach will be XSLT, for example http://bushorn.com/xml-to-xml-transformation-in-mule/
But however if you want to avoid XSLT for any reason, yes, Groovy will be good enough
XML Mapping in Mule
http://www.sixtree.com.au/articles/2013/data-mapping-with-groovy-part-1/
Custom Java class will also help you to do this


text:
Q: Android OpenGL camera2 texture resolution Intro
I'm using CaptureRequest.Builder and provide two surfaces as a target: a SurfaceTexture for drawing GL and an ImageReader (getSurface()) for processing frame.
I set desired resolution 640x480 by setting surfaceTexture.setDefaultBufferSize and by creating ImageReader.newInstance.
The problem
It appears that SurfaceTexture OpenGL texture is getting image that is of different aspect ration than 640x480 (4:3), more like 2560x1440 (16:9)(SurfaceTexture occupying full screen, see IMG 3). It has to be noted that both phones have same resolution aspect ratio 16:9. (Texture offset from the sides is left intentionally).
Below you can see IMG 1 displayed on a monitor screen, and IMG 2 and IMG 3 are phone screen captures where current activity view is showing camera preview.
The question
How to correctly force SurfaceTexture or GLSurfaceView.Renderer to get specific (4:3 in this case) aspect ratio texture image from camera for arbitrary size View?
Relevant
It has to be noted that there is an app that addresses issue, but for that they change the view size to correspond to desired aspect ratio.
See also:

*

*GitHub repo.

*Relevant source code.

*Related post

*Related post
IMG 1 - Displayed source image:

IMG 2 - Good aspect ratio (Google Nexus 5 - Android 6.0.1):

IMG 3 - Bad texture aspect ratio (LG-D855 - Android 5.0)

A: "Fixed" the issue by updating LG phone to Android 6.0.


text:
Q: Pipes do not connect to each other - geometric network I have created a geometric network in ArcGIS for Desktop. Some of the pipes are not logically connecting to each other even though they appear to geometrically intersect.
Can anyone tell me how to solve this?
For example, I have used "Find connected" at the flag in the figure below. You can see that the pipe is geometrically connected to the intersecting pipe.

I have zoomed into the intersection as much as possible and they seem to be connected.

The figure below show the configuration of the geometric network and the feature dataset.

A: The connection needs to be exact: the end point of one line must touch another end point or a line. When you draw a new line, you should therefore activate the snapping environment to make sure that it is accurately located. If your lines already exist, you could use "planarize line" tool to split lines at each intersection so that they connect. But then you only correct overshoots, not undershoots, and you need to remove the small extra line segments. For undershoots, you could use the "extend line" tool. Alternatively, it is possible to use the "integrate" tool to move neighbor feature locations within a given tolerance, but this tool should be used carefully because it potentially modifies all vertices. Finally, for a large network, you should use the topology tools (rule must not have dangle), but this is more complex.


text:
Q: What do you call a combination of date and time? Those who know programming simply call this as DateTime. For example, "2015-12-22 03:11:25".
Instead of referring it to simply DateTime, is there any other suitable name?

A: Though perhaps awkward in some contexts, timestamp does fit your desired meaning.

The date and time at which an event occurs or occurred, usually indicated in human-readable form, especially when used in a log to track events.

A: I use "time" as it may include both date and time, but if you use just "date", the time is not necessarily included.


text:
Q: If $\phi(f)=2$ then $f$ is the exponent of exactly $2$ numbers
If $f$ is the exponent of a number $a$ ($\mod p$) and $\phi(f)=2$ then, $a$ and its reciprocal are the only numbers, which belong to this exponent.

$\phi$ is the euler-phi function
Nothing written about $p$ (whether it is prime or not)
$a^f\equiv1\mod p$, such that $f$ is minimal called the exponent of $a$
I mean it is clear that $a$ and $a^{-1}$ have the same exponent, but how to bring $\phi(f)$ into play ?
It is written in the first $6$ lines of the paper below (On the Representation of an Integer as the Sum of Consecutive Integers by Mason, Thomas E.)

A: Let $f$ be the exponent of $a$. Let $G_f$ denote the set of all classes modulo $p$ with exponent $f$ and let $H_f$ be the classes with exponent a divisor of $f$ that is $b^f \equiv 1 \pmod{p}$.
Then group of invertible classes modulo $p$ is cyclic (when $p$ is prime) of order $p-1$. And $H_f$ is a subgroup with  $f$ elements. The number of elements of maximal order is $\phi(f)$. Thus if $\phi(f)=2$, there are exactly two such elements. Since $a$ and $a^{-1}$ are such elements they are those $2$. (Note the two elements are different, as $f$ is not $2$, since $\phi(f)=2$.)
The claim is in general not true for general $p$, though the condition prime could be weakened. But it seems certain it is intended.


text:
Q: it is possible to use an if without executing its condition so im trying to make an if statement to tell me if an sftp connection was sucessfull or failed, and if its a sucess i want to run a piece of code that automates an sftp download that ive already made.
My problem is that this if statement executes this sftp connection, and then prompts me for a password and stalls the rest of the code.
i wanted to do something like this
if ( sftp -oPort=23 user@server )
then
expect <<-EOF
spawn sftp -oPort=23 user@server
.....

I want to know if its possible for me to make the if statement not execute the sftp connection and  then not prompt me , maybe execute it on the background or something.
I would appreciate if someone could tell me if what im asking is possible, or propose a better solution to what im trying to do, thanks

A: You cannot not-execute a command and then react on the return value of the executed command (because this is what you really want to do: check if you can run sftp successful, and if so do a "proper" run; but you'll never know whether it can run successfull without running it).
So the main question is, what it is what you actually want to test.
If you want to test whether you can do a full sftp connection (with all the handshaking and what not), you could try running sftp in batch-mode (which is handily non-interactive).
E.g. the following runs an sftp session, only to terminate it immediately with a bye command:
if echo bye | sftp -b - -oPort=23 user@server ; then
  echo "sftp succeeded"
fi

This will only succeed if the entire sftp session works (that is: you pass any key checks; you can authenticate, ...).
If the server asks you for a password, it will fail to authenticate (being non-interactive), and you won't enter the then body.
If you only want to check whether something is listening on port 23, you can use netcat for this:
if netcat -z server 23; then
  echo "port:32 is open"
fi

This will succeed whenever it can successfully bind to port 23 on the server. It doesn't care whether there's an sftp daemon running, or (more likely) a telnet daemon.
You could also do some minimal test whether the remote server looks like an SSH/SFTP server: ssh servers usually greet you with a string indicating that they indeed speak ssh: something like "SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.4".
With this information you can then run:
if echo QUIT | netcat server 23 | grep SSH; then
 echo "found an ssh server"
fi


text:
Q: Cellular Automata Checking Neighbors I have a pretty simple problem but I cant seem to figure it out. I believe it is a logic error having to do with the checking of neighbors in cellular automata. Here is my code that runs once a second for growing and checking neighbors:
public void grow(){
    Cell[][] next = new Cell[100][100];
    for(int row = 0; row < (SIZE_X/SIZE); row++){
        for(int col = 0; col < (SIZE_Y/SIZE); col++){
            Cell cell = grid[row][col];
            Cell nCell = grid[row][col]; // gets

            if(cell != null){
                int amount = neighbors(row, col); // find out how many neighbors are ALIVE/ON

                if(cell.isOn() == true && amount != 3) // if the current cell is on but doesnt have 3 alive neighbors, it gets turned off
                    nCell.onOff(false);
                else if(cell.isOn() == false && (amount >= 1 && amount <= 4)) // if it is off and has 1-5 alive neighbors it gets turned on
                    nCell.onOff(true);

                next[row][col] = nCell;
            }
        }
    }
    grid = next;
}

public int neighbors(int row, int col){ // checks the amount of neighbors that are ALIVE/ON
    int amount = 0;

    for(int r = row-1; r <= row+1; r++){ // stepping through a 3x3 area of the grid, which surrounds the selected block
        for(int c = col-1; c <= col+1; c++){

            // clamp
            if((r > 0 && r < 99) && (c > 0 && c < 99)){
                if(grid[r][c].isOn() == true && (r != row && c != col)) // checks if the current neighbor is ALIVE/ON
                    amount++; // if it is then add one to the count
            }
        }
    }
    return amount;
}

Im using a simple 12345/3(Survival/Birth) rule in my Cellular Automata.
The problem currently is I have a 100x100 grid with a 10x10 space of ALIVE/ON cells in the center. After my code runs once, all the cells die.
If anyone needs more information, feel free to ask. Thanks in advance!

A: There are some problems but I'm not sure how everything is dead as result.
First problem:
if(cell.isOn() == true && amount != 3) // if the current cell is on but doesnt have 3 alive neighbors, it gets turned off
  cell.onOff(false);
if(cell.isOn() == false && (amount >=1 && amount <= 5)) // if it is off and has 1-5 alive neighbors it gets turned on
  cell.onOff(true);

Let's assume the cell have 1 live neighbour. Then first clause turns it off and then second one turns it back on. So "death" rule doesn't work. Solution: use else if.
Second problem:
You check everything in the same place. For example the field is:
**.
*.*

We check cell (0,0) and then field is:
    .*.
    .
Then after all first row is checked the field is:
    ...
    .
Then everyone dies. :)
Solution: first check neighbour number for each cell and store it in each cell. Only after that switch them on and off by the rules.
And third problem: on field edges some neighbours are checked twice. For example cell (0,0) is on and we check neighbours for cell (0,1). First we try (-1, 0) that is changed to (0,0) and added to amount. Later (0,0) is checked again as left neihbour and added to amount again.

A: if(grid[r][c].isOn() == true && (r != row && c != col))

Here you will only consider neighbors that aren't on the same row AND column than your center cell. As a result, youŕe considering 4 cells instead of 8.
You probably meant this:
if(grid[r][c].isOn() == true && (r != row || c != col)

A:
So I implemented some changed which solved the problems you talked
  about. Another problem has popped up though, which is now it makes a
  massive pyramid to the right of the starting blocks and slowly grows
  out with seemingly no rhyme or reason. Iv updated my code

Is Cell a class? Because you assign nCell directly from the grid. If you do this by reference, you also change the value of the cell in the old gridview. Doing this will create patterns which have a tendency to spread to the bottom-right corner of the grid.
EDIT: Just realized this is Java, and the above may not be true there. Disregard this if it is the case.
EDIT2: Also:
                 if(cell.isOn() == true && amount != 3) // if the current cell is on but doesnt have 3 alive neighbors, it gets turned
 off
                     nCell.onOff(false);
                 else if(cell.isOn() == false && (amount >= 1 && amount <= 4)) // if it is off and has 1-5 alive neighbors it gets turned on
                    nCell.onOff(true);

This doesn't mesh with 1-5 survival 3 birth rule.


text:
Q: Neo4j Best Practice for Index on Relationship Property? I'm trying to migrate a PostgreSQL database to Neo4j and have the following m-n relationship in PostgreSQL:
user-(blocked)-user
So in PostgreSQL I have an extra table "blocked" that has the following columns: userid1, userid2, blockedsince, blockeduntil
I also have an index on blocked.blockeduntil to search for rows that eventually must be removed when the blocking is over.
How can I build this relationship including the index in Neo4j?
I already included all user-rows in a node type "user" in Neo4j.
Next step would have been to create a relationship called "blocked" from user to user.
So basically like this: (user)-[:blocked]->(user)
I would have added the 2 relationship properties "blockeduntil" and "blockedsince" to the relationship. But it does not seem to be possible to create an index on the relationship property blocked.blockeduntil
Original code for PostgreSQL:
CREATE TABLE user (
   UserId bigserial NOT NULL PRIMARY KEY,
   ...
);
CREATE TABLE blocked(
   UserId1 bigint NOT NULL references user(UserId),
   UserId2 bigint NOT NULL references user(UserId),
   BlockedSince timestamp NOT NULL,
   BlockedUntil timestamp NOT NULL,
   PRIMARY KEY (UserId1, UserId2)
);
CREATE INDEX "IdxBlocked" on blocked(blockeduntil);

My first approach in Neo4j:
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///blocked.csv" AS row
MATCH (u1:user {userid: toInteger(row.userid1)})
MATCH (u2:user {userid: toInteger(row.userid2)})
MERGE (u1)-[b:BLOCKED]->(u2)
ON CREATE SET b.blockedsince = localdatetime(replace(row.blockedsince, " ", "T")), b.blockeduntil = localdatetime(replace(row.blockeduntil, " ", "T"));

What is the best practice to achieve this relationship including the index on blockeduntil? Would it be better to create a new node type called "blocked" like this?
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///blocked.csv" AS row
CREATE (:blocked{userid1: toInteger(row.userid1), userid2: toInteger(row.userid2), blockedsince: localdatetime(replace(row.blockedsince, " ", "T")),
                      blockeduntil: localdatetime(replace(row.blockeduntil, " ", "T"))});

And then create an index on blocked.blockeduntil like this?
CREATE INDEX ON :blocked(blockeduntil);

During my research I stumbled upon explicit indexes Explicit Indexes but they seem to be deprecated. Also I'm not sure if Full Text Indexes are the right choice here.

A: Ok, it seems that I found an official answer from a Neo4J staff member.
https://community.neo4j.com/t/how-can-i-use-index-in-relationship/1627/2
From the post:

We instead recommend refactoring your model. If you need to perform an index lookup of something, that usually suggests that thing would be better modeled as a node. As a node you are able to create the indexes and constraints you need for quick lookup.

So I will model "blocked" as a node and create an index on blocked.blockeduntil.


text:
Q: Bidirectional bind between a boolean property and two RadioButtons I have a class, Person, with a boolean property named 'genre' whose value will
be true for a boy or false for a girl.
I need to create a bidirectional bind between Person.genre and two RadioButtons
so that when I person object is populated with data from a data source the
RadioButtons will be set accordingly (Male RadioButton checked if Person.genre
is true, Female RadioButton checked if Person.genre is false) or if user clicks
Male RadioButton Person.genre will be set as true, if user clicks Female
RadioButton Person.genre will be set as false.
Please, help me in getting the most appropriate practice with that: should
I use Bindings API, RadioButton.bindBidirectional method with
Person.genreProperty() or the opposite, or even use a change listener???
Best regards,
Romualdo.

A: Simple:
person.genreProperty().bindBidirectional(male.selectedProperty());

The other radio button will be synced with the ToggleGroup.


text:
Q: Get selected rows of a table with SWT.MULTI I have a Table table with SWT.MULTI. Now I want to get the selected rows.
Till now I had a single selection and got the selected row with a selection listener. But how do I get the selected rows of the SWT.Multi table?
Can anyone help me?

A: table.getSelection() returns an array of TableItems.


text:
Q: how to change the css of button based on menustrip item click windows application I have five button and a menu strip, I want to apply the color on button based on the menustip click.
Suppose I have btn1, btn2, btn3, and menu stip which items are Test1, Test2, and Test3.
When I click on Test1 then btn1 color should become orange, when I click Test2 and btn1 color become white and btn2 color become orange, same as Test3.
some one please help me.

A: Define the events of your Menu strip Items and you can do the following to change the color of buttons...
private void Test1ItemClick(object sender, EventArgs e)
{
    btn1.BackColor = Color.Orange;
}

private void Test2ItemClick(object sender, EventArgs e)
{
    btn1.BackColor = Color.White;
    btn2.BackColor = Color.Orange;
}

Remember There is no css for buttons in win forms.
Updated:
void ChangeColor(string menuItem)
{
  switch(menuItem)
  {
    case "Test1":
      btn1.BackColor = Color.Orange;
      break;
    case "Test2":
      btn1.BackColor = Color.White;
      btn2.BackColor = Color.Orange;
      break;
     // and so on
  }
}


text:
Q: how to work with variables in files instead of memory in c#(like pagefile) I have written a program that I have to save large data in the variables.
how can I use files instead of memory? like virtual memory (page file)

A: You can leverage Memory Mapped Files for this. In .NET Framework this nice feature is available since version 4.0.
See Non-persisted memory-mapped files

Non-persisted files are memory-mapped files that are not associated
  with a file on a disk. When the last process has finished working with
  the file, the data is lost and the file is reclaimed by garbage
  collection. These files are suitable for creating shared memory for
  inter-process communications (IPC).


text:
Q: Weird behaviour of LDAP_MATCHING_RULE_IN_CHAIN / 1.2.840.113556.1.4.1941 we have a weird behaviour we cannot explain.
We have a query like this

(memberOf:1.2.840.113556.1.4.1941:=CN=Backup Operators,CN=Builtin,DC=test,DC=env)

To get all members of a group. E.g. we configured the Backup Operators group (Test env) to have the following members:

The query will only find Authenticated users and Leea. This is, for some reason the behaviour every time. All Foreign Security Principals except the "Authenticated Users" one are never picked up by the query and we can't figure out why.
Any ideas?

A: You are searching your domain for users where the memberOf attribute contains that group, or a group nested inside of that group.
The problem is that those objects do not have their memberOf attribute populated. If you open those accounts in AD Users and Computers, you'll that the Member Of tab is blank.
I can't really say why, since Authenticated Users looks like the same type of object, but it does have the memberOf attribute populated.
In general, memberOf can be spotty. For various reasons, you won't always find every member of a group by searching memberOf. To get every member of a group, you need to look at the member attribute of the group itself.


text:
Q: white space after the footer, only in firefox There seems to be random white space after the footer at the bottom of the site, but it only shows up in Firefox. The site pulls up fine in Safari and Chrome. When I try to use inspect element, the white space doesn't seem to fall under any tags. It doesn't seem tied to any footer tags either as removing them didn't change anything.
I'm using Ryan Fait's Sticky Footer solution for my footer. It seems to work fine on Chrome and Safari, but doesn't seem to work on Firefox.
You can test it at: http://www.edmhunters.com/martin-garrix/
Any ideas what I'm doing wrong?

A: If you add
overflow:hidden

To the footer element, it seems to fix the problem in firefox. I got this idea from this question, so it's probably the same or a similar issue (collapsing margins).

A: Both answers already provided do not help the situation...

© EDM Hunters 2014

Is located in your footer its placement is wrong. It isn't showing like it is in Chrome.. You need to move your menu over to the left a bit. I'll provide css when I get the exact styles.
In global.min.***.css on line 12, remove all your css add:
bottom: -102px;
position: relative;

This should be for .footer-copyright. Do not use overflow:hidden because that is for someone who doesn't know what is happening. Now... Right this second I need to check in Chrome, but this should be fine. I'll fix edit in a minute if it is not.
Final edit:
To work in Chrome add with the two styles above:
display: block;
float: left;

A: This is an issue with clearfix on firefox since... forever. If you remove clearfix and add either float:left; width:100% or overflow:hidden to the footer, it should be good in all browsers.

Also, you don't really use the clearfix correctly. Instead of adding an empty element like

, you should just add the class to the container of the floated elements:


text:
Q: [javascript ]how can I pickup object-like string from my String using regex There is a string like this :
"{tagName=input, type=radio,}, {}, {tagName=input, type=radio, labelName=option31}"

How can I pickup 3 objects in that ?
thank you for help !

A: you can split this text like this:
var text = "{tagName=input, type=radio,}, {}, {tagName=input, type=radio, labelName=option31}";
text = text.replace(/}/g,"}}");
var res = text.split("},");

First line is used for add a "}" at the end of each object you want for do the split without problems like the comma at the end of the first object you want.
Then, in res you have an array with the three objects you want
Regards.


text:
Q: For loop issue with Bluetooth devices I'm trying to connect my phone to a HN-06 Bluetooth Module for Arduino.
I'm using a for loop to add every bonded device to a ListView:
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set pairedDevices = mBtAdapter.getBondedDevices();

if (pairedDevices.size() > 0){
    for (BluetoothDevice device : pairedDevices) {
        mPairedDevicesArrayAdapter.add(device.getName() + "\n" +
        device.getAddress());
    }
}

But when I do this I get an error in the BluetoothDevice device telling me they are

Incompatible types, Required: Object, Found: Bluetooth Device.

How can I solve this?
Pd. mBtAdapter is declared right under the class in the following way:
private BluetoothAdapter mBtAdapter;

A: You need to define the type of object for your Set
Set<BluetoothDevice> pairedDevices

You can also remove the if (pairedDevices.size() > 0){ since the loop takes care of that


text:
Q: Ubuntu 15.04 - ADB Fastboot impossible to install I try to install android-tools-fastboot with
sudo apt-get install android-tools-adb android-tools-fastboot

and the terminal says
Package android-tools-fastboot is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'android-tools-fastboot' has no installation candidate

Any idea ?
Regards.

A: Today there was no problem installing android-tools.
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install android-tools-adb android-tools-fastboot

A: After updating to 15.04 I found many issues simply related to the repositories used by Ubuntu.
Essentially what happens when you add a new ppa to your system it will by default look for repositories labeled as your distro version (in this case vivid vervet, 15.04). The android tools repository is only under utopic (14.04) and presumably earlier.
SOLUTION:

*

*Open up Software & Updates

*Open up "Other Software" Tab

*In that list look for anything with "http://ppa.launchpad.net/phablet-team/tools/ubuntu"

*Note that those items look for the "vivid" distribution. Click edit and replace "vivid" with "utopic" for each.

*Click close, this will call an apt-get update (you may get a pop up with a "Reload" button, click it).

*Try running your original command and everything should install successfully!


text:
Q: How to check if ObjectResult<> contains a value How do I check to see if the ObjectResult<> has a value or not? Right now it's returning values but will it throw an exception is there is nothing to return?
This is the section of code that I need to check so I do not have to depend on a try catch block

iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();

public static Task<IProjectInfo> GetProjectInfo(int projectID)
{
    return Task.Run(() =>
      {
          using (var db = new StorefrontSystemEntities())
          {
              IProjectInfo iProjInfo = db.proc_GetProject_ForDrawings(projectID).Single<IProjectInfo>();

              try
              {
                  iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
              }
              catch (Exception ex)
              {

              }
              return iProjInfo;
          };
      });
}

A: As long as the stored procedure is getting executed and returning a result set; even if it is empty (no records returned by the stored procedure), you can be sure of an empty list being returned.


text:
Q: How to write a Select Case condition for an interval of integers? I'm trying to read the values of every row in an Excel sheet in a certain column and set a text in another column depending on the numeric value.
I'm facing an overflow error using CInt function. I want to be certain the value I get is used as an Integer. The greatest value I have in that column is 43803 so Integer should be enough. However, I read I need to use Long for referring to columns/rows in code, so I changed CInt to CLng. Now the overflow error is gone but ALL rows are considered Category B.
My lowest numeric value in the column is 329.
Sub insertColumnCategory()
    Dim cellValue As Long
    Dim lastColumn As Long
    Dim lastRow As Long
    Dim i As Long

    lastColumn = ActiveSheet.Range("A1").CurrentRegion.Columns.Count + 1

    Columns(lastColumn).Insert
    ActiveSheet.Columns(lastColumn).NumberFormat = "General"

    With ActiveSheet
       lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    For i = 2 To lastRow
        cellValue = CLng(Cells(i, 21).Value)

        Select Case cellValue
        Case Is <= 0
            Cells(i, 22).Value = "Category A"
        Case Is >= 1, Is <= 30
            Cells(i, 22).Value = "Category B"
        Case Is >= 31, Is <= 60
            Cells(i, 22).Value = "Category C"
        Case Is >= 61, Is <= 90
            Cells(i, 22).Value = "Category D"
        Case Is >= 91, Is <= 180
            Cells(i, 22).Value = "Category E"
        Case Is >= 181, Is <= 365
            Cells(i, 22).Value = "Category F"
        Case Is > 365
            Cells(i, 22).Value = "Category G"
        End Select
    Next i

End Sub

A: You Case evaluation ends as soon as the first test passes.
For example:
Sub Tester()

    Dim a As Long

    a = 20

    Select Case a
        Case Is <= 0: Debug.Print "zero or less"
        Case Is >= v1, Is <= v15: Debug.Print "1-15"
        Case Is >= 16, Is <= 30: Debug.Print "16-30"
    End Select
End Sub

Function v1()
    Debug.Print "Called v1"
    v1 = 1
End Function

Function v15()
    Debug.Print "Called v15"
    v15 = 15
End Function

Output:
Called v1
1-15

So v15 is never called because that test is skipped.


text:
Q: Validate radio buttons with jQuery on submit I want to validate my form using jQuery.
It has groups of radio buttons.
I have found multiple solutions for a single group of radio-buttons or solutions, where you have to specifically say what group-names there are.
Like here:
Validate radio buttons with jquery?
The problem is, that the form is being generated at run-time.
The questions are saved in a txt file (don't ask, it's a school exercise).
The generated HTML-Code looks something like this:

What's your gender?

<input type="radio" name="gender" value="m" />Male
<input type="radio" name="gender" value="f" />Female

How satisfied are you with out support?
<input type="radio" name="satisfaction" value="0%" />Not at all
<input type="radio" name="satisfaction" value="25%" />Not very much
<input type="radio" name="satisfaction" value="75%" />It was ok
<input type="radio" name="satisfaction" value="100% />It was very satisfying

The js file is being generated using Twig, so it would be possible to loop through all the radio button groups, but I would like to avoid this if that's possible.

A: You would need to add all the groups first (page load would be fine, but make sure the group array is in global scope), then validate each group individually when your form is submitted/button click
var groups = [];
$(function() {
    $("input[type=radio][name]").each(function() {
      // Add the unique group name to the array
      groups[$(this).attr("name")] = true;
    });
});
$("button").click(function() {
    $.each(groups, function(i, o) {
      // For each group, check at least one is checked
      var isValid = $("input[name='"+i+"']:checked").length;
      alert(i + ": " + isValid);
    });
});

A: I got it working like this
var groups = [];
$(function() {
    $("input[type=radio][name]").each(function() {
      // Add the unique group name to the array
      if (groups[groups.length - 1] != $(this).attr("name")) groups.push($(this).attr("name"));
    });
});
$('form').submit(function () {
    var isValid = true;

    $.each(groups, function(i, o) {
      // For each group, check at least one is checked
      if (isValid) isValid = $("input[name='"+o+"']:checked").length;
    });

    if (!isValid) return false;

    return true;
});

Thanks to Blade0rz!


text:
Q: MP3 player mpman TS300 not recognized I just received a mpman ts300 mp3 player for Christmas. But when I try to connect it to ubuntu (10.10) through usb it doesn't seem to be recognized.
I searched for a linuxdriver but came up with nothing. I even tried installing mpman manager from the software center, but still the same problem...
Has anybody got any ideas about how to fix this?
Thank you
edit: some additional information
When I plug it in, it doesn't show up under /dev. And it is not listed in the result of 'lsusb'
This is the output of 'dmesg'

[19571.732541] usb 1-4: new high speed USB device using ehci_hcd and address 2
[19571.889154] scsi7 : usb-storage 1-4:1.0
[19572.883155] scsi 7:0:0:0: Direct-Access     TS300    USB DISK         1.00 PQ: 0 ANSI: 0
[19572.885856] sd 7:0:0:0: Attached scsi generic sg2 type 0
[19572.887266] sd 7:0:0:0: [sdb] 7868416 512-byte logical blocks: (4.02 GB/3.75 GiB)
[19573.012547] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19573.292550] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19573.572565] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19573.725019] sd 7:0:0:0: [sdb] Test WP failed, assume Write Enabled
[19573.725024] sd 7:0:0:0: [sdb] Assuming drive cache: write through
[19573.728521] sd 7:0:0:0: [sdb] Attached SCSI removable disk
[19575.333015] sd 7:0:0:0: [sdb] 7868416 512-byte logical blocks: (4.02 GB/3.75 GiB)
[19575.452547] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19580.603253] usb 1-4: device descriptor read/all, error -110
[19580.722560] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19595.842579] usb 1-4: device descriptor read/64, error -110
[19611.072656] usb 1-4: device descriptor read/64, error -110
[19611.302540] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19616.332568] usb 1-4: device descriptor read/8, error -110
[19621.462692] usb 1-4: device descriptor read/8, error -110
[19621.692551] usb 1-4: reset high speed USB device using ehci_hcd and address 2
[19626.722567] usb 1-4: device descriptor read/8, error -110
[19631.852802] usb 1-4: device descriptor read/8, error -110
[19631.962587] usb 1-4: USB disconnect, address 2
[19631.962587] sd 7:0:0:0: Device offlined - not ready after error recovery
[19631.962840] sd 7:0:0:0: [sdb] Assuming drive cache: write through
[19631.965104] sd 7:0:0:0: [sdb] READ CAPACITY failed
[19631.965109] sd 7:0:0:0: [sdb] Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
[19631.965112] sd 7:0:0:0: [sdb] Sense not available.
[19631.965125] sd 7:0:0:0: [sdb] Assuming drive cache: write through
[19631.965130] sdb: detected capacity change from 4028628992 to 0
[19632.130042] usb 1-4: new high speed USB device using ehci_hcd and address 3
[19647.242550] usb 1-4: device descriptor read/64, error -110
[19662.472560] usb 1-4: device descriptor read/64, error -110
[19662.702566] usb 1-4: new high speed USB device using ehci_hcd and address 4
[19677.822587] usb 1-4: device descriptor read/64, error -110
[19693.052575] usb 1-4: device descriptor read/64, error -110
[19693.282582] usb 1-4: new high speed USB device using ehci_hcd and address 5
[19698.312600] usb 1-4: device descriptor read/8, error -110
[19703.442594] usb 1-4: device descriptor read/8, error -110
[19703.672548] usb 1-4: new high speed USB device using ehci_hcd and address 6
[19708.702581] usb 1-4: device descriptor read/8, error -110
[19713.840077] usb 1-4: device descriptor read/8, error -110
[19713.942555] hub 1-0:1.0: unable to enumerate USB device on port 4
[19714.262545] usb 4-2: new full speed USB device using uhci_hcd and address 2
[19729.382549] usb 4-2: device descriptor read/64, error -110
[19744.612534] usb 4-2: device descriptor read/64, error -110
[19744.842543] usb 4-2: new full speed USB device using uhci_hcd and address 3
[19759.962714] usb 4-2: device descriptor read/64, error -110
[19775.200047] usb 4-2: device descriptor read/64, error -110
[19775.422630] usb 4-2: new full speed USB device using uhci_hcd and address 4
[19780.444498] usb 4-2: device descriptor read/8, error -110
[19785.574491] usb 4-2: device descriptor read/8, error -110
[19785.802547] usb 4-2: new full speed USB device using uhci_hcd and address 5
[19790.824490] usb 4-2: device descriptor read/8, error -110
[19795.961473] usb 4-2: device descriptor read/8, error -110
[19796.062556] hub 4-0:1.0: unable to enumerate USB device on port 2

A: Nick. Are you still facing the problem? I stumbled upon your question when searching for some solution for exactly the same problem, but with a Sony Ericsson W580i.
Well, it happens I found this page on http://ubuntuforums.org/archive/index.php/t-797789.html and there are some hints that seem to work there. The first one did the job for me. Not immediately, but it took about 60 seconds for Ubuntu to tell me I got a "wired network disconnected" (probably usb0, as I could see later in syslog).

A: It looks like you're getting a lot of errors. Try a different cable and/or a different USB port on your computer. If you're plugging into a hub...try a direct-to-computer connection.


text:
Q: Parametrization of $x^2-y^2=1$; Why does the following only cover the "right-hand side"? I have the parabola $x^2-y^2=1$. I am asked to first show that $\cosh(t)=x,\sinh(t)=y$ parameterizes the curve.
This, I have done; substituting to the implicit function expression gives $1$.
But I guess I am missing something from the concept as I cannot understand the following statement.

This parametrization covers only the right-hand side of $x^2-y^2=1$ because $\cosh(t)$ is always positive.

I don't see how $\cosh(t)$ always positive $=$ "covers only right-hand side of the function(graph)".
Can someone explain to me why? I simply don't understand why not cover the entire parabola with this particular parametrization.


text:
Q: Creating Gradle Tasks in IntelliJ I'm new to both tools, but why is it that sometimes I can see the tasks from the gradle.build file under the "Run Tasks" section in IntlliJ, and other times I can't?
In other words why does gradle not always identify my tasks?
Thank you.

A: You have to refresh all gradle projects for new tasks to be recognised. This can be done by pressing this button in the Gradle projects view:

Once this is done, you should see your new tasks in the list.


text:
Q: Tengo problemas para guardar una cookie en javascript Mi problema es que intento crear una cookie para saber cual es el usuario que esta utilizando la web, el sistema que quiero intentar es bastante sencillo, simplemente quiero crear la cookie a partir del correo de la persona que quiera iniciar sesion, la cookie deberia crearse aunque el correo sea incorrecto -Esto da igual ya que la web no tiene información sensible y el formulario de login no dejará entrar al usuario si proporciona los datos incorrectos -.
Pero resulta que por algún motivo javascript no agrega la cookie , ¿me podéis ayudar?
<script>

  var identiu = function(){
        document.cookie = "identi=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/127.0.0.1";
        var name = identi;
        var value = document.getElementById("emailusuario");
       document.cookie = name + "=" + value + ";path=/127.0.0.1";
   }
    </script>

A: Intenta de esta manera:
<script>

  var identiu = function(){
        document.cookie = "identi=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
        var name = identi;
        var value = document.getElementById("emailusuario");
       document.cookie = name + "=" + value + "; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
   }
</script>

Ademas como te dicen nunca trates de crear las cookies desde el cliente, trata de hacerlo desde el mismo PHP.


text:
Q: Copy object at specific index of mutable array to the end of another array I have a mutable array that has a range of numbers (that are changed dynamically later on if that helps), I grab a random number's index from that array and want to stick it in another array (also mutable). I'm not sure how to grab the object at a certain index and copy it.
Here's what I tried to do:
[btnRange addObject:@"12"];
[btnRange addObject:@"13"];
[btnRange addObject:@"14"];
[btnRange addObject:@"17"];
[btnRange addObject:@"18"];
[btnRange addObject:@"19"];
//start randomising and adding to btnOrder Array

for (NSInteger i=0; i <= 5; i++) {
     id nxt = btnRange[arc4random_uniform([btnRange count])];
     [btnOrder addObject:(@"%@", nxt];
     //[btnOrder addObject[btnRange(nxt)]; --didn't work
     //[btnOrder addObjectsFromArray:(btnRange. nxt]; --didn't work
     //[btnOrder addObject:nxt]; --didn't work (I'm pretty new to this)
}

How can I take the object at a specific index of the first array and copy it over at the end of the second array?

A: You can get the object from NSMutableArray using [arrayName objectAtIndex:index]
and add object in NSMutableArray using [arrayName addObejct:object]
[arrayName objectAtIndex:index] return object

[btnRange addObject:@"12"];
            [btnRange addObject:@"13"];
            [btnRange addObject:@"14"];
            [btnRange addObject:@"17"];
            [btnRange addObject:@"18"];
            [btnRange addObject:@"19"];
            //start randomising and adding to btnOrder Array

            for (NSInteger i=0; i <= 5; i++) {
                NSString *nxt = [btnRange objectAtIndex:arc4random()%[btnRange count]];
                [btnOrder addObject:nxt];
            }

A: I'm not sure how to close this, but the suggested thread had the answer I was looking for!
This was my end code if anyone is interested:
[btnRange addObject:@"12"];
[btnRange addObject:@"13"];
[btnRange addObject:@"14"];
[btnRange addObject:@"17"];
[btnRange addObject:@"18"];
[btnRange addObject:@"19"];
//start ordering
for (NSInteger i=0; i <= 5; i++) {
    id nxt = btnRange[arc4random_uniform([btnRange count])];
    btnOrder[i] = nxt;
    [btnRange removeObject:nxt];
}


text:
Q: Can my server integrate Firebase Authentication? So I'm all new to Firebase and took a look at the features they offer. I'm planning to build a react-native app that will access the Firebase API through a Node.js server I will create.
What I'll need is the realtime database, cloud messaging, storage and authentication (It'll be some sort of messenger).
Because the mobile apps won't be written in Swift or Java, I'm confused as to whether things will/should happen in the react-native app using the Firebase npm package, or using a Node.js server in between that does everything.
Let's say I want to use cloud messaging to send notifications to people programmatically. It's obvious this has to happen on a server. However, if the authentication happens in the react-native app using the npm package, how can my server know if the user is authenticated?
You might see I don't have a clue how to organise things here. I mentioned the 4 things I need to do, and that I'll build react-native apps as the front end.
How would you do it? Is a server required at all, and if yes, could it do everything and just "forward" actions from the apps to Firebase, including the authentication part?
Thanks


text:
Q: Python: Can't insert list values into a mysql column I have an int list list = [1, 2, 3]
And a mysql table with an empty second column:
key value
a
b
c

I want to populate the value column with values from my list so as to make the table look like this:
key value
a   1
b   2
c   3

But I am always getting a TypeError: 'int' object is not iterable
My python code is:
conn = MySQLdb.connect(host="localhost", user="root", passwd="root")
cursor = conn.cursor()
list = [1, 2, 3]
cursor.executemany("INSERT INTO my_table (value) VALUES %d", list)

How am I to solve the issue and get the empty column populated?
Thanks!
P.S.: this is just a sample. In reality, the list and the table are much bigger.

A: You need a list of lists or tuples.
my_list = [[1], [2], [3]]

(Also, don't overwrite the built-in list() type with your own variable.)


text:
Q: Interface Método GET e POST com Angular + Node.js Estou com algumas dúvidas de iniciante e queria a ajudar de vocês.
Criei uma Automação Residencial, baseada em Microcontrolador + Node.js + Angular.js.
A comunicação do Angular.js com o Microcontrolador está OK.
Porém, também farei o inverso. No qual o MIC irá enviar um comando POST para o Node.js, mais ou menos com esse parametro:
router.post('/Saidas', function(req,res) {
    saida = req.body.atuador;
    estado = req.body.estado;
    final = saida + estado;
    res.send('Enviado = Saida: ' + saida + '; Estado: ' + estado);
});

E posteriormente irei enviar para o site em HTML, via Angular.js com esse comando:
router.get('/SaidasSite', function(req,res){
    res.send(final);
});

**Acima está no código caminhos.js para o Node.js.
Porém, no meu Angular.js, fiz o seguinte código:
<script>
    var app = angular.module('Saidas',[]);
    app.controller('Status', function($scope, $http, $interval) {
        $interval(function(){
            var request = $http.get('/SaidasSite');
            request.success(function(data) {
                if (data='QTD1LEDON') {
                    $('#QTD1LAMP').bootstrapToggle('on');
                } else (data='QTDLEDOFF'){
                    $('#QTD1LAMP').bootstrapToggle('off');
                } else (data='QTD2LEDON'){
                    $('#QTD2LAMP').bootstrapToggle('on')
                } else { $('#QTD1LAMP').bootstrapToggle('on'); }
            })
            .error(function(data){
                console.log('Error: ' + data);
            });
        }, 5000);

        /* O segundo parâmetro "5000", diz que a função deve ser repetida a cada
           5000 milisegundos (5 segundos) */
    });
</script>

A minha idéia é a seguinte: Quando eu enviar o comando "QTD1LEDON" para o comando POST /Saidas, ele enviar o comando para o Node.js e posteriomente o site irá receber o comando GET com esse valor (GET /SaidasSite) e acionar um botão conforme a string que recebeu.
Ex: Botão QTD1LED ON acionado -> QTDLEDON -> Ativa Botão "Bootstrap Toogle".
Não estou encontrando o melhor jeito para fazer isso. Esse processo não está funcionando. Nesse código, ele sempre aciona o "QTD1LEDON".
Teria algum jeito melhor para arrumar esse código ou implantar outro processo? Obrigado!

A: Fala Luiz, boa tarde.
No seu código em JavaScript, nos ifs, você deve utilizar o operador == ou o operador === para verificar se a constante é igual a variável (como é string sugiro o === pois é mais performático).
O operador = é operador de atribuição, então no primeiro if, ele atribui "QTD1LEDON" à variável data e como ela é uma variável definida ele entra no if. Por isso está entrando no primeiro if sempre.
Sugiro colocar também um console.log('data = ', data) no começo da function de callback de success para você poder ver o que veio de resposta do nodejs.
Outra coisa também é o else - quando você tem outra condição ele deve ser else if( condição ).
Espero ter ajudado.


text:
Q: Swift / Xcode - Unwrapping an Optional value When I try to unwrap "var window" using "!" it shows the Optional value is nil.
Fatal error: Unexpectedly found nil while unwrapping an Optional value
var window: UIWindow?

// image to be animated
let backgroundImg = UIImageView()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // creating imageView to store background image "mainbg.jpg"
    backgroundImg.frame = CGRect(x: 0, y: 0, width: 1000, height: 1000)
    backgroundImg.image = UIImage(named: "mainbg.jpg")
    self.window!.addSubview(backgroundImg)

    return true
}

Has anyone else faced this problem and managed to fix it?
I'm using XCODE Version 11.3.1 with SWIFT 5. This

A: You have to understand what an Optional type is. An optional type basically means that the variable can be nil .
To get the value from your variable if it is optional, you have to unwrap it. This just means putting an exclamation point at the end.

A: As already mentioned in the comments, your UIWindow optional variable has not been assigned, so is still nil by default.  You probably need a different project template that will set up the window for you.
As for the "!" operator, usually you should try to avoid using it, because if your optional is unassigned or nil, it will always throw an exception.  Read about Optionals in the Swift Manual.

A: The problem is the force unwrap on window, when you're trying to add the backgroundImg as subview. In the code that you shared, you don't set the window value before use that, so there is nil.
To fix it, you have to create a new window instance before adding the subview.
window = UIWindow()
self.window!.addSubview(backgroundImg)


text: Q: Bigquery - which table are affected by another table I want to delete a table in bigquery. But before that, I want to know which tables are being linked to the table I'm about to delete. Is there a query to extract all linked tables?


text:
Q: Microsoft Graph Api -No permission acces token when asking for Me.Photo I made sure I have all permissions to get user profile photo when using Microsoft graph api, but I get 'no permission Token' error, every time. It doesn't make sens as I can retrive all the other info like DirectReports an Manager - using the same Token.
I have tried Different endpoints and different call like Me.Photo.Content and Users[id].Photo - but still no luck
ProfilePhoto GetAvatarForCurrentUser(GraphServiceClient  _graphServiceClient)
    {

        using (var task = Task.Run(async () => await _graphServiceClient.Me.Photo.Request().GetAsync()))
        {
            while (!task.IsCompleted)
                Thread.Sleep(1000);

            var avatar = task.Result;
            return avatar;
        }
    }

public ProfilePhoto GetAvatar()
    {
        var accessToken = GetAppTokenForAvatar();
        var graphserviceClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
        (requestMessage) =>
     {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            return Task.FromResult(0);
        }));

        var userAvatar = GetAvatarForCurrentUser(graphserviceClient);

        return userAvatar as Microsoft.Graph.ProfilePhoto;
     }

public string GetAppTokenForAvatar()
     {
        AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[app-id]/");

        ClientCredential clientCred = new ClientCredential(Config.AdClientID, Config.AdClientKey);
        AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCred).Result;
        return authenticationResult.AccessToken;
     }

I Expect to recive my own profile avatar, and like I said I have no problem to get Menager or other related data.

A: The AuthenticationContext is not correct. When you use the wrong AuthenticationContext, you will encounter such error.

Replace
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[app-id]/");

with
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/[tenant-id]/");

Based on your code, you are using client credentials, you should use Users[id].Photo. And make sure you grant admin consent for application permission.


text:
Q: Assert - 2 Exact Same String Comparing Returns Error I am comparing two strings using this code:
    Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));

Both String outputs are exactly the same in the output:
    Merci ! Votre commande a été envoyée.
    Merci ! Votre commande a été envoyée.

Tests does run many times, and it always worked until this one situation.
There are no spaces inside the strings.
Special characters does not cause problems in any other cases.
Any Thoughts? Thank you!
UPDATE:
I am getting the same error when comparing these strings, maybe have something in common that breaks the test:
Merci ! Votre commande a été envoyée.
Merci ! Votre commande a été envoyée.

Référence de la commande : {0}
Référence de la commande : {0}

Contactez-moi !
Contactez-moi !

Quelle est la probabilité que vous recommandiez nous à un ami ou un collègue ?
Quelle est la probabilité que vous recommandiez nous à un ami ou un collègue ?

I noticed there is a space before symbol in each case (_! / _? / _:). This (the space before symbol) never occurs in other passing assertions. I am testing like 500 of them. May be the cause?

A: My guess is, that whitespace around the text are trimmed or added at getText.
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));

Probably disregard this difference:
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().trim()
    .equals(text.trim()));

An other property of Unicode is that é can be either one char or two (e + accent). And java internally uses Unicode for text. Actually one should normalize text before comparing.
s = Normalizer.normalize(s, Normalizer.Form.NFKC); // Most compact

By the way instead of assertTrue the method assertEquals with expected and actual values will give better error messages.

A: Let us see whats happening in your code. You have used :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));

Within Assert.assertTrue you are comparing 2 values. The first value is driver.findElement(By.cssSelector(cssSelector)).getText() which can return text (w/out white space characters) or NULL. The second value is a pure text.
Now, if you look at the javadoc of equals it is defined as :
boolean java.lang.String.equals(Object anObject)
//Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

This is the root case of your failure. This will return True only if the given object represents a String equivalent to this string
Again, if you look at the javadoc of assertTrue it is defined as :
void org.testng.Assert.assertTrue(boolean condition)
//Asserts that a condition is true. If it isn't, an AssertionError is thrown.

Solution:
The solution would be to use either contains, equalsIgnoreCase or contentEquals instead of equals as follows :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().contains(text));
//OR
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equalsIgnoreCase(text));
//OR
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().contentEquals(text));

Update 1:
I will suggest use getAttribute("innerHTML") instead of getText() as follows :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").contains(text));
//OR
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").equalsIgnoreCase(text));
//OR
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").contentEquals(text));

Update 2:
As your test is still failing, I would suggest you to reduce the expected string to something substantial instead of the entire string. Example:
String text = "Votre commande a été";

Update 3:
As a last resort, you should be able to expand the expected string as follows :
String text = "Merci ! Votre commande a été envoyée.";

And perform your Test successfully.

A: Use trim and remove empty space and check it.
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText()trim().equals(text.trim()));

A: Change your code to
Old:
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));

New:
Assert.assertTrue(text.equals(driver.findElement(By.cssSelector(cssSelector)).getText()));


text:
Q: How can I have access to each building in building layer of google earth? I am thinking about making an application that discriminates between buildings based on some attributes using google earth's API.let's say highlighting those with a specific architecture style. the problem is that I don't know how to access each building in the building layer.some say it is not possible.is that true?
as an alternative solution I tried to import 3D model of each building from 3D warehouse. now I need to be able to highlight them and make them clickable. could you tell me how is that possible?

A: Right now, it doesn't appear that there is a way to publicly access the building footprint data that's used by Google Maps. There are some alternatives, as discussed in StackExchange GIS: "Where can I find building footprint data?".
You should be able to access these through the OpenStreetMap building outline dataset.


text:
Q: Why GitHub C++ Core Guideline says that global object better than singleton? The Github C++ Core Guidelines say:

A global object is often better than a singleton.

I always thought the opposite. Something has changed since then in the C++?
Or may be it's just another typo?

A: This is the rationale for avoiding singletons from the same guideline collection:

I.3: Avoid singletons
Reason
Singletons are basically complicated global objects in disguise.
Example

class Singleton {
    // ... lots of stuff to ensure that only one Singleton object is created,
    // that it is initialized properly, etc.
};

There are many variants of the singleton idea. That's part of the problem.

My analysis of the intentions of the author:
Simpler is better. If disguising global objects in singletons doesn't solve the problems of global objects - like the guideline above implies - then there is no use in complicating the code by the use of the disguise.


text:
Q: SELECT between semi colons I'm using SQL Server 2014.  I have 1 field that contains a string value like this
ADGA;BADF;CASD;DFAD;SADAF;gNDG;asDD;dADA;zzz;SDFS;SFGG;SSFG;DFGF

How do I SELECT to return the string between the 10th and 11th ; ?
The values between the semi colon's is always 4 characters in length.
So from the above, I need to return:
SFGG


text:
Q: Why are busy indicators not displayed when sending requests? I have some slow OData calls which need to present some sort of visual indicator to the user that something is happening.
I've read the API reference and seen functions like attachRequestSent(), setBusy(), BusyDialog, BusyIndicator, etc.
I tried using them accordingly but did not work for me. The problem seems to be oModel.create causing the whole app to hang while it executes. No loading indicators or anything can run since the app is frozen until the create function has returned.

Edit: I have set up an asynchronous batch read OData call. I have then wrapped the code for handling the received data in a function and called that function inside the success function in the batch call.
This works; the view loads and I see a busy indicator before the fields are populated with the data
oModel.submitBatch(/*fnSuccess*/);

Is this a good way to do it, or is there a better way which is more standard?

A: Before the Odata call, display the busy indicator (locks the entire app screen). with
sap.ui.core.BusyIndicator.show(0);

Then, in both the success and failure handlers of the odata call, hide it with
sap.ui.core.BusyIndicator.hide();

It does not work with implicit calls (when for instance you bind to an odata model), for this you can use the request sent events, but the idea is the same.
Edit: You also need to give a small delay to allow the indicator to appear, then use setTimeout to call your odata after a small delay.
doStuffWithIndicator: function(){
        sap.ui.core.BusyIndicator.show(0);
        setTimeout(function(){
            doStuff();
            sap.ui.core.BusyIndicator.hide();
        }, 20);

    },

A: checkout this thread: SAPUI5 Wait for an Deferred-Object // wait for .done() function
Javascript is asynchrone, this means the code will be processed further no matter if you make an call (which might take longer). Therefore before calling an OData Service you need to tell your JS to wait for it (make it synchrone) via an deferred object.

A:
The main problem seems to be oModel.create causing the whole app to hang while it executes. No loading indicators or anything can run since the app is frozen until the create function has returned.

Sounds like you've been using the now-deprecated sap.ui.model.odata.ODataModel the whole time, which sends mostly synchronous XHRs. Synchronous XHRs block the main thread (== UI thread) until the browser receives the response. The browser isn't then able to update the DOM to display the busy indicator during the round trip.
If anyone reading this has the same issue, please migrate to the newer equivalent model: sap/ui/model/odata/v2/ODataModel. It sends only asynchronous requests (AJAX), allowing the UI thread to handle other tasks (such as adding the busy indicator to the DOM) while the browser waits for the response.


text:
Q: How to get password for sudo I'm trying to use the command sudo -i -u postgres for PostgreSQL, and the Google Compute Engine VM is asking me for my password for my account (not root).
As I never issued a password, and I always login to my server via SSH key, I'm not sure what the password is, how I can reset it, or where it can be found.
Please tell me where I can get my password?

A: Per https://cloud.google.com/compute/docs/instances ,

The instance creator and any users that were added using the metadata
  sshKeys value are automatically administrators to the account, with
  the ability to run sudo without requiring a password.

So you don't need that non-existent password -- you need to be "added using the metadata sshKeys value"!  The canonic way to do that, and I quote from that same page:
$ echo user1:$(cat ~/.ssh/key1.pub) > /tmp/a
$ echo user2:$(cat ~/.ssh/key2.pub) >> /tmp/a
$ gcloud compute project-info add-metadata --metadata-from-file sshKeys=/tmp/a

or you can use the Google Developers Console for similar purposes, see https://cloud.google.com/compute/docs/console#sshkeys if you'd prefer that.

A: To become another non-root user on a GCE VM, first become root via password-less sudo (since that's how sudo is configured on GCE VM images):
sudo su -

and then switch to the user you want to become or run a command as another use, e.g., in your case, that's:
sudo -i -u postgres

A: Summary
While creating the VM, specify the ssh user in the "Enter the entire key data" box.
Details

*

*generate the ssh key pair and identify the public key:

*

*if ssh-keygen, a file ending with ".pub"

*if PuTTYgen, the text in box "Public key for pasting ..."

Notice the fields, all one one line, separated by spaces: "protocol key-blob username".
For username, you may find your Windows user name or a string like "rsa-key-20191106". You will replace that string with your choice of Linux user name.

*Paste the public key info into the "Enter the entire key data" box.

*Change the 3rd field to the actual user that you want to create on the VM. If, for example, "gcpuser", then:
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAjUIG3Z8wKWf+TZQ7nVQzB4s8U5rKGVE8NAt/LxlUzEjJrhPI5m+8llLWYY2PH4atZzuIYvYR0CVWhZvZQzLQc33vDOjQohxV9Lg26MwSqK+bj6tsr9ZkMs2zqNbS4b2blGnr37+dnwz+FF7Es9gReqyPxL9bn5PU/+mK0zWMHoZSEfUkXBrgqKoMQTsYzbMERluByEpZm9nRJ6ypvr9gufft9MsWC2LPhEx0O9YDahgrCsL/yiQVL+3x00DO9sBOXxi8kI81Mv2Rl4JSyswh1mzGAsT1s4q6fxtlUl5Ooz6La693IjUZO/AjN8sZPh03H9WiyewowkhMfS0H06rtGQ== gcpuser

*create your VM. (Debian, for example)

*Connect to the VM

*

*directly from ssh or PuTTY (not browser window)

*use the private key

*specify the user

*Notice that your public key is present:
gcpuser@instance-1:~/.ssh$ cat authorized_keys
# Added by Google
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAjUIG3Z8wKWf+TZQ7nVQzB4s8U5rKGVE8NAt/LxlUzEjJrhPI5m+8llLWYY2PH4atZzuIYvYR0CVWhZvZQzLQc33vDOjQohxV9Lg26MwSqK+bj6tsr9ZkMs2zqNbS4b2blGnr37+dnwz+FF7Es9gReqyPxL9bn5PU/+mK0zWMHoZSEfUkXBrgqKoMQTsYzbMERluByEpZm9nRJ6ypvr9gufft9MsWC2LPhEx0O9YDahgrCsL/yiQVL+3x00DO9sBOXxi8kI81Mv2Rl4JSyswh1mzGAsT1s4q6fxtlUl5Ooz6La693IjUZO/AjN8sZPh03H9WiyewowkhMfS0H06rtGQ== gcpuser

*Notice that you are in group google-sudoers
gcpuser@instance-1:~/.ssh$ id
uid=1000(gcpuser) gid=1001(gcpuser) groups=1001(gcpuser),4(adm),30(dip),44(video),46(plugdev),1000(google-sudoers)

*sudo to root with no password
gcpuser@instance-1:~$ sudo -i -u root
root@instance-1:~#

*Notice the sudoers file:
root@instance-1:~# cat /etc/sudoers.d/google_sudoers
%google-sudoers ALL=(ALL:ALL) NOPASSWD:ALL

Conclusion
Specifying the username in "Enter the entire key data" has these results:

*

*creating the user in the virtual machine.

*uploading the key to ~/.ssh

*membership in a passwordless sudo group


text:
Q: How to Submit a Form With Action Page in a Different Folder? I am not been able to submit a form if its action is on a page in a  different folder. I tried the following code:
<form action="model/insert_resident.php" onsubmit="return formvalidate()" method="POST">

    Name:Enter Name
      <input type="text" class="form-control" id="name" name="name" placeholder="Name">

    Flat Id:
      <input type="text" class="form-control" id="flatid" name="flatid">

    Email:
      <input type="text" class="form-control" id="email" name="email">

    Phone:
      <input type="number" id="phone" class="form-control"  name="phone">
      <input type="hidden" id="date" class="form-control" name="date" value="<?php echo date("Y-m-d"); ?>">

     <input class="btn btn-primary" type="submit"  onClick="formvalidate()" name="insert" value="Add">

   </form>

A: As you have given us following in the form tag:
action="model/insert_resident.php

we assume that your file called insert_resident.php is in the sub-directory model. Have you tried opening this page with the direct URL in the browser?
You should also try to prefix with a / or ./ to mean current directory.
action="./model/insert_resident.php


text:
Q: how to reduce page faults in this program? I'm gating more then 1000 page faults in this program.
can i reduce them to some smaller value or even to zero ?
or even any other changes can speed up the execution
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
  register unsigned  int u, v,i;
  register unsigned int arr_size=0;
  register unsigned int b_size=0;
  register unsigned  int c;
  register unsigned  int *b;
  FILE *file;
  register unsigned int *arr;
  file=fopen(argv[1],"r");
  arr=(unsigned int *)malloc(4*10000000);
  while(!feof(file)){
    ++arr_size;
    fscanf(file,"%u\n",&arr[arr_size-1]);
  }
  fclose(file);
  b=(unsigned int *)malloc(arr_size*4);
  if (arr_size!=0)
  {
    ++b_size;
    b[b_size-1]=0;

    for (i = 1; i < arr_size; ++i)
    {
      if (arr[b[b_size-1]] < arr[i])
      {
        ++b_size;
        b[b_size-1]=i;
        continue;
      }
      for (u = 0, v = b_size-1; u < v;)
      {
        c = (u + v) / 2;
        if (arr[b[c]] < arr[i]) u=c+1; else v=c;
      }
      if (arr[i] < arr[b[u]])
      {
        b[u] = i;
      }
      if(i>arr_size)break;
    }
  }
  free(arr);
  free(b);
  printf("%u\n", b_size);
  return 0;
}

A: The line:
arr=(unsigned int *)malloc(4*10000000);
is not a good programming style. Are you sure that your file is as big as 40MBs? try not to allocate the whole memory in the first lines of your program.


text:
Q: Handle entire row on TableCellRenderer I'm implementing TableCellRenderer to make a visible diference if the last value is or not certain value.
So, the code of these implementation is:
    TableColumnModel tcm = table.getColumnModel();
    TableColumn col = tcm.getColumn(column);

    JLabel cellComponent = new JLabel();
    if (value != null)
    {
        cellComponent.setText( String.valueOf( value ) );
    }else
        cellComponent.setText( "-" );

    String colName = (String) col.getHeaderValue();
    if (colName.startsWith("Vigencia") && !cellComponent.getText().equals("-"))
    {
        long dias = Long.valueOf(cellComponent.getText());
        if (dias <0)
        {
            dias = dias -(dias*2); //Le resto (dias x 2) para sacarle el negativo...

            cellComponent.setText( String.valueOf(dias) );
            cellComponent.setBorder( BorderFactory.createLineBorder(Color.RED));
        }
    }

to populate my table I have a Class that extends from JTable and have this method to populate the table:
public void setData(LinkedList<T> list)
{
    if (list.size() == 0)
    {
        cleanTableData();
        return;
    }

    int index = 0;
    Object[][] o = new Object[list.size()][_columnNames.length];
    for (T obj : list)
    {
        Object[] data = obj.toStringReporte();
        o[index++] = data;
    }
    _tableModel = new DefaultTableModel( o, _columnNames );
    setModel(_tableModel);
    setColumnWidths();
}

toStringReporte method is this one:
public Object[] toStringReporte()
{
    String planName = "-";
    if (getPlanID() != null)
    {
        Plan plan = Adapter.getInstance().getElement(getPlanID(), new Plan());
        planName = plan.getNombre();
    }

    return new Object[]{getID(),
                        getNombre(),
                        getApellido(),
                        getDni(),
                        (getEstado().equals("A") ? "Activo" : "Inactivo"),
                        (getSexo().equals("M") ? "Masculino" : "Femenino"),
                        (getFichaMedica() != null ? new SimpleDateFormat(Defines.DATE_FORMAT).format(new Date(getFichaMedica())) : "-"),
                        planName,
                        (getFechaVencimiento() != null ? SGGDateUtils.diferenceInDaysBetweenTwoDatesMS(getFechaVencimiento(), new Date().getTime()) : "-")};
}

My problem is that (as Class name tells) the only change is cell border. I want to change entire row border.
Some body know how to change the border of entire row?

A: Table Row Rendering shows how you might render a row level border.

A: You cannot do this with just a TableCellRenderer, as it works independently on each cell.
If you want to apply an effect to an entire row, you will likely need to override the prepareRenderer method of JTable.