Q: Google Domain Shared Contacts API Using OAuth 2.0 for Server to Server Applications - Credential params I'm trying to get the "Google Domain Shared Contacts API" described here:
https://developers.google.com/admin-sdk/domain-shared-contacts/
Working using "OAuth 2.0 for Server to Server Applications" described here:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount
The recommendation from the OAuth page is to use the provided Google client library... I'm using the Java library. But the Shared-Contacts API doesn't have an example that uses this library, and I'm having trouble figuring out how to use the library with the Shared-Contacts API.
I am able to make the example for the OAuth to work for me... It uses Google Cloud Storage. Here's a snippet of the code:
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
try {
          try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      String p12Content = Files.readFirstLine(new File(keyFile), Charset.defaultCharset());
      // Build service account credential.
      GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
          .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
          .setServiceAccountPrivateKeyFromP12File(new File(keyFile))
          .build();

      // Set up and execute Google Cloud Storage request.
      String URI;

      URI = "https://storage.googleapis.com/" + BUCKET_NAME;
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
      GenericUrl url = new GenericUrl(URI);
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse response = request.execute();
      content = response.parseAsString();
          } catch (IOException e) {
              System.err.println(e.getMessage());
            }
          } catch (Throwable t) {
            t.printStackTrace();
          }
      return content;

It's a request to get a listing of what's in a certain bucket on GCS. It calls a specific URL using the Credentials object, where the Credentials object does the work of the OAuth, using a key file I downloaded. There's other steps involved for getting it to work (setting the service account email, etc), which I did. It returns an xml string containing what is inside the bucket, and it works fine for me.
I then tried changing the URI to this string:
URI = "https://www.google.com/m8/feeds/contacts/myGoogleAppsDomain.com/full";
and I changed the STORAGE_SCOPE variable to be this string:
STORAGE_SCOPE = "http://www.google.com/m8/feeds/";
Hoping it would then return an xml-string of the shared-contacts. But instead, it returns this error:
403 Cannot request contacts belonging to another domain
I believe I'm getting this error because I'm not specifying the "hd" parameter when I do the authentication request... However, I'm unsure how I can specify the "hd" parameter using the GoogleCredential object (or the other parameters, except for "scope")... Can someone help me with that?

A: I think the issue here is that you are not specifying which user you want to impersonate in the domain (and you haven't configured the security settings in your domain to authorize the service account to impersonate users in the domain).
The doubleclick API auth documentation has good examples on how to do this. You can use their sample and replace the scopes and API endpoint:
https://developers.google.com/doubleclick-publishers/docs/service_accounts#benefits


Q: Data Studio SYSTEM_ERROR Code 13 with SQL query SELECT user_leads.id,
       first_name                              AS 'Nombres',
       last_name                               AS 'Apellidos',
       ip                                      AS 'IP o número de telefono',
       city                                    AS 'Ciudad',
       state                                   AS 'Estado',
       From_unixtime(user_leads.timestamp)     AS 'Fecha',
       Count(wadmin.id)                        AS 'Total Grupos de Whatsapp (Admin)',
       Coalesce(Group_concat(wadmin.name), '') AS 'Grupos de Whatsapp (Admin)',
       lead_sources.name                       AS 'Fuente',
       lead_statuses.name                      AS 'Status',
       dw.session_id
FROM   user_leads
       LEFT JOIN dialogflow_sessions AS dw
              ON dw.lead_id = user_leads.id
       LEFT JOIN user_lead_global_fields AS gf_ans
              ON gf_ans.leadid = user_leads.id
       LEFT JOIN lead_sources
              ON lead_sources.id = sourceid
       LEFT JOIN lead_statuses
              ON lead_statuses.id = user_leads.statusid
       LEFT JOIN whatsapp_groups AS wadmin
              ON wadmin.admin_lead_id = user_leads.id
GROUP  BY user_leads.id
ORDER  BY user_leads.id DESC

Im currently using that query, here is what I tried

*

*Removing special characters

*Removing "as *" statements

*clearing cache

*changing sql data source and double checked my connection yet nothing

Has anyone faced this issue?

A: Found it. Data Studio doesn't like spaces in column aliases, yet it won't show any error for them. The working is the same with all spaces in aliases replaced by underscore


Q: Multiple Actions (Forms) on one Page - How not to lose master data, after editing detail data? I've got a form where users can edit members of a group.
So they have the possibilty to add members or remove existing members. So the Url goes like
".../Group/Edit/4"  Where 4 is the id of the group.
the view looks like this
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("AddUser", "Group")) %>
    <%{%>
        User
        <%=Html.TextBox("username")%>
        <input type="submit" value="Add"/>

    <%}%>

    <% using (Html.BeginForm("RemoveUser", "Group")) %>
    <%{%>

        Bestehende Mitglieder
        <%= Html.ListBox("groupMember", from g in Model.GetMembers() select new SelectListItem(){Text = g}) %>
        <input type="submit" value="Remove" />

    <%}%>
</asp:Content>

The problem is that after adding or removing one user i lose the id of the group. What is the best solution for solving this kind of problem?
Should I use hidden fields to save the group id?
Thanks in advance.

A: Hidden fields are a good way of persisting the id during posts.

A: You could use a hidden field or you could just parse the value into your route.  I'm not sure how you're parsing the group id to the view but it would look something like:
<% using (Html.BeginForm("AddUser", "Group", new { groupId = Model.GroupID })) { %>

Then your controller will look something like this using the PRG pattern
[HttpGet]
public ViewResult Edit(int groupId) {
  //your logic here

  var model = new MyModel() {
    GroupID = groupId
  };
  return View("Edit", model);
}

[HttpPost]
public ActionResult AddUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

[HttpPost]
public ActionResult RemoveUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

The advantage to this method is that it's more RESTful


Q: A book about a world cut off, heiress raised as a pleasure girl, and broken A.I Got the title from a list of fairly new authors about 6 years ago (around 2010ish). The main character is raised to be a prostitute/geisha as an orphan. Turns out she is the last person left of a "noble" house. The Houses are all derived from their function to the original colony and her ancestors were the techs in charge of the A.I. and they damaged it to help the others stage a coup for control of their area. She is being hunted to prevent her from messing with the status quo as the colony is cut off from the rest of the galaxy by the sabotaged A.I. Part of what makes the Houses able to keep power is that their abilities are programmed into their genes, and that is why she is a threat, as she could still repair the damaged A.I. just by being what she is.

A: The book is called Palace by Katherine Kerr and Mark Kreighbaum
Thanks everyone for your help. I didn't remember the author because I associate her with fantasy not sci fi.


Q: How to properly continue tasks when a given parameter is different I'm facing tasks right now and I have doubts. After an email/pass registration, I had to update the user's profile. So I first tried this:
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
    .continueWithTask(new Continuation<AuthResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(fullname)
                .build();
            return t.getResult().getUser().updateProfile(profileUpdates);
        }
    })
    .addOnFailureListener(this, mOnSignInFailureListener)
    .addOnSuccessListener(this, mOnSignInSuccessListener); // <- problem!

The problem is in the last line my listener waits for an AuthResult parameter but updateProfile task sends a Void. I handled that situation like bellow but it seems too messy. Tell me if there is another better way to do this:
final Task<AuthResult> mainTask;
mainTask = FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
mainTask
    .continueWithTask(new Continuation<AuthResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(fullname)
                .build();
            return t.getResult().getUser().updateProfile(profileUpdates);
        }
    })
    .continueWithTask(new Continuation<Void, Task<AuthResult>>() {
        @Override
        public Task<AuthResult> then(@NonNull Task<Void> t) throws Exception {
            return mainTask;
        }
    })
    .addOnFailureListener(this, mOnSignInFailureListener)
    .addOnSuccessListener(this, mOnSignInSuccessListener);

A: It looks like you're expecting an AuthResult to get passed directly to mOnSignInSuccessListener.  In this particular case, in my opinion, it's not worthwhile to try to coerce an extra Continuation to return the value you're looking for.
Instead of trying to arrange for the AuthResult to be passed to that listener as a parameter, the listener can simply reach directly into mainTask.getResult(), or you can save the AuthResult in a member variable and access it that way.  Either way, it's safe because the mOnSignInSuccessListener will only be invoked after mainTask completes, which ensures the AuthResult is ready.


Q: How to check if it's null? I retrieve data from database like below. How do I check whether the value retrieved from database is null?
Private Function GetBatch() As DataSet
        Dim dataset As New DataSet
        Dim adapter As Data.SqlClient.SqlDataAdapter
        Dim cn As New System.Data.SqlClient.SqlConnection(connectionstring())
        GetBatchCommand.Connection = cn
        adapter = New Data.SqlClient.SqlDataAdapter(GetBatchCommand)
        adapter.Fill(dataset)
        Return dataset
End Function

Dim dataset As New DataSet
            dataset = GetBatch()

With dataset.Tables(0)

Dim PersonID As String = .Rows(int).Item("personId")

I'd like to check whether personID is null. How do do that?

A: Try DataRow's IsNull method to check null values :
Dim isPersonIDNull As Boolean = .Rows(0).IsNull("personId")

Or use IsDBNull method :
Dim isPersonIDNull As Boolean = IsDBNull(.Rows(int).Item("personId"))

Or manually Check if the value equals DBNull :
Dim isPersonIDNull As Boolean = .Rows(int).Item("personId").Equals(DBNull.Value)

A: If DBNull.Value.Equal(.Rows(int).Item("personId")) Then
...

DBNull

A: You can also use the Convert.DbNull constant.

A: You have to check if the value is null before you assign it to PersonID
like:
if .Rows(int).Item("personId") = DBNull.Value Then
  ' Assign some Dummy Value
  PersonID = ""
else
  PersonID = .Rows(int).Item("personId")
end if

I would recommend to extract that piece of code into a helper method which gets either the value or a default for a given column.

A: This situation can occur if table with no rows, that time ds.Table(0).Rows(int).Item("personId") will return null reference exception
so you have to use two conditions
Dim PersonID As String =""
if(ds.tables.count>0) Then
 if(ds.tables(0).Rows.Count>0) Then
   if(NOT DBNull.Value.Equal((ds.tables(0).Rows(int).Item("PersonID"))) Then
              PersonID = ds.tables(0).Rows(int).Item("PersonID")

I think It will solve your issue..just minor syntax variation may be present


Q: Concatenating char variables I tried making a small program using the libraries "iostream" and "String" to display a given string backwardly as the output on the command prompt. I used a recursive returning-value (string) function to perform the whole process of getting the given string in backward and returning it to the main function to be displayed on screen, as you can see below:
#include <iostream>
#include <string>
using namespace std;
string rev(string, int);

int main() {
    string let;
    cout << "Enter your string: ";
    cin >> let;
    cout << "The string in reverse is: " << rev(let, let.length());
    cout << endl;
    return 0;
}

string rev(string x, int y) {
    if (y != 0 )
        return x[y - 1] + rev(x, y - 1);
    else
        return "\0";
}

What I don't get about the process, is that while the concatenation performed on the rev function, recursively, and with the char variables works correctly and returns the string in backward to the main function, trying to concatenate the char variables normally like this gives rubbish as the output:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string hd;
    string ah = "foo";
    hd = ah[2] + ah[1] + ah[0];
    cout << hd << endl;
    return 0;
}

And even if I add to the "hd" chain "\0", it still gives rubbish.

A: Your first example implicitly converts characters to strings and uses appropriate operator +
While your second example is adding up characters
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
returns reference to character at position

A: Writing instead
hd = ""s + ah[2] + ah[1] + ah[0];

will, informally speaking, put + into a "concatenation mode", achieving what you want. ""s is a C++14 user-defined literal of type std::string, and that tells the compiler to use the overloaded + operator on the std::string class on subsequent terms in the expression. (An overloaded + operator is also called in the first example you present.)
Otherwise, ah[2] + ah[1] + ah[0] is an arithmetic sum over char values (each one converted to an int due to implicit conversion rules), with the potential hazard of signed overflow on assignment to hd.

A: How about making use of everything that's already available?
string rev(const string &x) { return string{x.rbegin(), x.rend()}; }

Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.


Q: SQL - Average Quarter-Hour Persons (AQH) In radio broadcasting there is a term called, "Average Quarter-Hour Persons" aka (AQH), which can be defined as...as the average number of persons listening to a particular station for at least five minutes during a 15-minute period.
I am not quite sure how to start this in SQL as the listening sessions span between the different 15-minute buckets.
The 15-minute buckets are 0-15, 15-30, 30-45, and 45-60.
Here is an example from the creator of the metric, "For example, 1:00-1:05, 1:00-1:10 or 1:00-1:15 each equal one quarter-hour of listening. But, 1:11-1:19 is
not a quarter-hour of listening (there is not five minutes in either clock quarter-hour, 1:00-1:15 or 1:15-1:30)."
Let's assume I have the following table where each row contains the radio station, the time a user started listening and the time the user stopped listening.  For sake of simplicity I am not including any sort of User ID, etc.
radio_station varchar
session_start time
session_stop time
How would I write the SQL to calculate said metric per hour?

A: This query work in sql server. Only question is how to handle those sessions that span or end at midnight, how they are represented.
Set up sample data:
declare @t table(session_start time, session_stop time)
insert @t values ('1:00','1:05'),('1:00','1:10'),('1:00','1:15'),('1:11','1:19')

Query based on a CTE. Create the time buckets. If CTEs are not available, create a table containing these entries instead., and rest of the query is unchanged.
;with valid_times as (
select convert(time,'00:00') as valid_start, convert(time,'00:15') as valid_end
union all
select dateadd(minute,15,valid_start), dateadd(minute,15,valid_end)
from valid_times
where valid_start<='23:30'
)
select valid_start, valid_end,
    sum(case when datediff(minute,
        case when session_start<valid_start then valid_start else session_start end,
        case when session_stop>valid_end then valid_end else session_stop end
        )>=5 then 1 else 0 end) as AQH
from valid_times
left join @t t on valid_end>=session_start and valid_start<=session_stop
group by valid_start, valid_end


Q: Add foreign key constraint to an existing table column, referencing a column in a newly created table Let's say I have one table defined as this
CREATE TABLE sales (
    agent_id   integer references agents(agent_id),
    sale_date  date,
    amout      numeric(10,2)
);

Then an ETL process fills this table with data
INSERT INTO sales VALUES
    (1, '2019-01-01', 1031.11),
    (1, '2019-01-02', 525.44),
    (1, '2019-01-03', 323.99);

But later, I need to add a table with actual processed dates, such as
CREATE TABLE dates (
    date_idx   date primary key,
    year       integer not null,
    month      integer not null,
    day        integer not null
);

and want to add a foreign key constraint on the old table:
ALTER TABLE sales
    ADD CONSTRAINT sales_date_fk FOREIGN KEY (sale_date)
    REFERENCES dates (date_idx);

Naturally, I get the following error:

ERROR: insert or update on table "sales" violates foreign key constraint "sales_date_fk" Detail: Key (sale_date)=(2019-01-01) is not present in table "dates".

I know I can work around this by deleting/truncating all data in sales or prefilling dates before adding the constraint, but I would prefer not to if I can avoid it.
Is there any way to accomplish this?
I'm using Postgres 11, but this fiddle running 9.6 shows what I've tried to explain here.

A: You can use the NOT VALID modifier when creating a foreign key to stop it verifying existing data. For instance:
ALTER TABLE sales
ADD CONSTRAINT sales_date_fk FOREIGN KEY (sale_date)
REFERENCES dates (date_idx) NOT VALID;

I would not recommend this though, unless something prevents you from populating the new child table so you have no choice.
This is postgres specific syntax, for instance the equivalent in SQL Server is WITH NOCHECK, and some others may not support the option at all, so take care if trying to support multiple database backends.

A: Select all distinct date from sales tables and insert data into the dates tables. After populating data into that table try to create the foreign key constraint.


Q: Create a new column in excel with a condition I want to create a new column called Book in which I take data from a column called Exposure. If the value from the exposure column is 0, I want it to return 100, else I want to retain the same value.
This is what I've already tried:
df['Book'] = np.where(df['Exposure']==0,100,)

how do I get it to return the same value if it's not zero?

A: Try this :
df['Book'] = df['Exposure'].replace(0, 100)


Q: Are concepts and properties studied in a category all preserved by morphisms? When study a category, are we only interested in those concepts and properties preserved by the morphisms, not those which cannot be preserved?
For example, in Terry Tao's blog

We say that one probability space ${(\Omega',{\mathcal B}', {\mathcal P}')} $ extends another ${(\Omega,{\mathcal B}, {\mathcal P})}$ if there is a surjective map ${\pi: \Omega' \rightarrow \Omega}$ which is measurable (i.e. ${\pi^{-1}(E) \in {\mathcal B}'}$ for every ${E \in {\mathcal B}}$) and probability preserving (i.e. ${{\bf P}'(\pi^{-1}(E)) = {\bf P}(E)}$ for every ${E \in {\mathcal B}}$).
...
In order to have the freedom to perform extensions every time we need to introduce a new source of randomness, we will try to adhere to the following important dogma: probability theory is only “allowed” to study concepts and perform operations which are preserved with respect to extension of the underlying sample space. (This is analogous to how differential geometry is only “allowed” to study concepts and perform operations that are preserved with respect to coordinate change, or how graph theory is only “allowed” to study concepts and perform operations that are preserved with respect to relabeling of the vertices, etc..)

A side question, do the probability spaces and the extension mappings form a category, so that my question at the beginning of this post can apply?
Thanks!
A somewhat related question is here, about the meaning of preserving mathematical structures.

A: I first answer your latter question. This is clearly a category: the extendability is reflexive - just use the identity map, and transitivity you can easily show using the composition map.
W.r.t. your primary question, my knowledge of CT is very basic, e.g. I didn't have a chance to go beyond the first 4 chapters of Awodey, thus I am not sure whether I can give a complete answer. I'll try though. As Awodey mentions,

Let me begin with some remarks about category-theoretical definitions. By
  this I mean characterizations of properties of objects and arrows in a category
  in terms of other objects and arrows only, i.e. in the language of category
  theory. Such definitions may be said to be abstract, structural, operational,
  relational, or external (as opposed to internal). The idea is that objects
  and arrows are determined by the role they play in the category, by their
  relations to other objects and arrows, thus by their position in a structure,
  and not by what they "are" or "are made of" in some absolute sense. We'll
  see many more examples of this kind of thing later; for now we start with
  some very simple ones. Let me call them abstract characterizations. We'll
  see that one of the basic ways of giving such an abstract characterization is
  via a Universal Mapping Property or UMP.

As far as I understand this, it means that if you study categories, then you shall consider those statements that hold for all categories satisfying certain properties e.g. having finite products (which are defined only through morphisms and objects, not through the internal structure of categories). Alike in topology, the topological property of a topological space shall hold for all homeomorphic spaces.
However, if you study a particular category -- say topological spaces, besides of applying purely categorial results which concern morphisms (e.g. UMP of products), you are also interested in certain topics which are relevant to this particular category. E.g. when the map is not only continuous, but is also open or closed.
Hope, it helps


Q: Does it matter which algorithm you use for Multiple Imputation by Chained Equations (MICE) I have seen MICE implemented with different types of algorithms e.g. RandomForest or Stochastic Regression etc.
My question is that does it matter which type of algorithm i.e. does one perform the best? Is there any empirical evidence?
I am struggling to find any info on the web
Thank you

A: Yes, (depending on your task) it can matter quite a lot, which algorithm you choose.
You also can be sure, the mice developers wouldn't out effort into providing different algorithms, if there was one algorithm that anyway always performs best. Because, of course like in machine learning the "No free lunch theorem" is also relevant for imputation.
In general you can say, that the default settings of mice are often a good choice.
Look at this example from the miceRanger Vignette to see, how far imputations can differ for different algorithms. (the real distribution is marked in red, the respective multiple imputations in black)

The Predictive Mean Matching (pmm) algorithm e.g. makes sure that only imputed values appear, that were really in the dataset. This is for example useful, where only integer values like 0,1,2,3 appear in the data (and no values in between). Other algorithms won't do this, so while doing their regression they will also provide interpolated values like on the picture to the right ( so they will provide imputations that are e.g. 1.1, 1.3, ...) Both solutions can come with certain drawbacks.
That is why it is important to actually assess imputation performance afterwards. There are several diagnostic plots in mice to do this.


Q: Set value of jtable column using setValueAt() I am trying to set the value of a jtable column using setValueAt() in netbeans and it is not working.
following is what i have set using 'customize code' option.
The columns showing null are of type boolean ie they can be checked and unchecked.
I want to read values from the database and set the column values accordingly.
pref_table = new javax.swing.JTable();

pref_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
    {"MONDAY", null, null, null, null},
    {"TUESDAY", null, null, null, null},
    {"WEDNESDAY", null, null, null, null},
    {"THURSDAY", null, null, null, null},
    {"FRIDAY", null, null, null, null},
    {"SATURDAY", null, null, null, null}
},
new String [] {
    "DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
}
) {
    Class[] types = new Class [] {
    java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
};

public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
}
});

As the frame containing the jtable(pref_table) is initialised,the column values are either set to true or false by calling the following function but it does not seem to work.
public void set_tab_val(boolean x,int r,int c)
{
  pref_table.setValueAt(true,r,c);
}

A: I have added a button to the frame and called the method which you wrote and it worked fine for me.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class TableSetEx
{

    static JTable pref_table;

    public static void main(String[] args) {
        pref_table = new javax.swing.JTable();

        pref_table.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"MONDAY", null, null, null, null},
            {"TUESDAY", null, null, null, null},
            {"WEDNESDAY", null, null, null, null},
            {"THURSDAY", null, null, null, null},
            {"FRIDAY", null, null, null, null},
            {"SATURDAY", null, null, null, null}
        },
        new String [] {
            "DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
        }
        ) {
            Class[] types = new Class [] {
            java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
        });

        JButton button = new JButton("Click");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                // Some hardceded cell.
                set_tab_val(true,2,3);
            }
        });

        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(pref_table), BorderLayout.NORTH);
        frame.add(button, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void set_tab_val(boolean x,int r,int c)
    {
      pref_table.setValueAt(true,r,c);
    }
}


Q: Two classes inheriting from the same base to see each other I have a program with a lot of classes. I want classes in the program to be visible to each other. For that, I am following a trick such that all classes are inherited from a base class, which holds pointers to every class. But I hit an error in doing so. Below is a piece of code produces the error I am after:
#include <iostream>
using namespace std;

class AClass;
class BClass;

class RoofClass {
 public:
  RoofClass();
  AClass* a_class;
  BClass* b_class;
};

class BaseClass {
 public:
  BaseClass(RoofClass* roof_class) {
   a_class = roof_class->a_class;
   b_class = roof_class->b_class;
  }
  AClass* a_class;
  BClass* b_class;
};

class AClass : public BaseClass {
 public:
  AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Afunction();
  int Aint = 1;
};

class BClass : public BaseClass {
 public:
  BClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Bfunction();
  int Bint = 2;
};

void AClass::Afunction() {
  cout << b_class->Bint << endl;
}

void BClass::Bfunction() {
  cout << a_class->Aint << endl;
}

RoofClass::RoofClass() {
  a_class = new AClass(this);
  b_class = new BClass(this);
}

int main(int argc, char **argv) {
  RoofClass roof_class;
  cout << "b calls a" << endl;
  roof_class.b_class->Bfunction();
  cout << "a calls b" << endl;
  roof_class.a_class->Afunction();
}

Roof is the top level class which consists of classes A and B. I want A and B visible to each other. To achieve that, as I said, they both inherit from the Base class. My problem, in particular, is that while B sees A, A does not see B. The reason for this is probably due to the fact that A is initialized before B in constructor of Roof. So, why can I solve this issue?

A: When RoofClass constructor creates an instance of AClass, it passes a pointer to itself, with uninitialized members a_class and b_class. AClass constructor then copies those values and returns. When RoofClass constructor sets a_class to point to the newly constructed object, the pointers inside AClass are still pointing to nothing.
You probably want BaseClass to store a pointer to RoofClass instead:
class BaseClass {
 public:
  BaseClass(RoofClass* roof_class) {
   r_class = roof_class;
  }
  RoofClass* r_class;
};
class AClass : public BaseClass {
 public:
  AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Afunction();
  int Aint = 1;
  // access class B as r_class->b_class
};

A: I actually solved the question. It is like this:
In its constructor, the RoofClass creates a and b objects, in order. It first initializes a object by going into its constructor (which actually is the constructor of BaseClass due to inheritance) and setting a's a and b objects to roof's a and b. But the problem is that, roof's b is not constructed yet. That is why, a's b is initialized to a value of 00000000. When the RoofClass goes to b object's constructor for initialization, this time both roof's a and b are in place so that b's a and b's b are properly initialized. That is why, b can have a proper a but not vice versa.
The solution is introducing an InitPointer function to the base class, which acts after the roof objects constructs all a and b objects. This way, InitPointer sets pointers of a and b objects to already constructed a and b objects. Here is the working code:
#include <iostream>

using namespace std;

class AClass;
class BClass;

class RoofClass {
 public:
  RoofClass();
  AClass* a_class;
  BClass* b_class;
};

class BaseClass {
 public:
  BaseClass() {}
  void InitPointer(RoofClass* roof_class) {
    a_class = roof_class->a_class;
    b_class = roof_class->b_class;
  }
  AClass* a_class;
  BClass* b_class;
};

class AClass : public BaseClass {
 public:
  AClass() : BaseClass() {}
  void Afunction();
  int Aint = 1;
};

class BClass : public BaseClass {
 public:
  BClass() : BaseClass() {}
  void Bfunction();
  int Bint = 2;
};

void AClass::Afunction() {
  cout << b_class->Bint << endl;
}

void BClass::Bfunction() {
  cout << a_class->Aint << endl;
}

RoofClass::RoofClass() {
  a_class = new AClass();
  b_class = new BClass();
  a_class->InitPointer(this);
  b_class->InitPointer(this);
}

int main(int argc, char **argv) {
  RoofClass roof_class;
  cout << "b calls a" << endl;
  roof_class.b_class->Bfunction();
  cout << "a calls b" << endl;
  roof_class.a_class->Afunction();
}

Thanks for the all discussion!


Q: Uniqueness of function $f(x)$ Problem :
let $f\colon[0, 1]\to (0,\infty)$ is continuous function and satisfies :
$$\int_0^1(f(x))^3dx=2,\quad \int_0^12x^2f(x)dx=1$$
Find $f(x)$ and prove/disprove that $f$ is unique or not.

My Attempt:
From AM-GM,
$$f(x)^3 + 8x^3+8x^3\ge 3(64x^6f(x)^3)^\frac{1}{3}=12x^2f(x)$$
and integrate both side
$$ \int_0^1 f(x)^3dx + 4 = 6 \ge 6\int_0^12x^2f(x)dx=6$$
Since equality holds, $f(x)^3=8x^3\quad\Rightarrow\quad f(x)=2x.$

*

*Is this method valid?

*Does this ensure the uniqueness of $f$?

A: Hint
Take $f_k(x)=kx$ and $g_m(x)=mx^2$ and try to find $k$ and $m$ postive s.t. $$\frac{1}{2}\int_0^1 f_k(x)^3\,\mathrm d x=\int_0^1 2x^2f_k(x)\,\mathrm d x$$ and $$\frac{1}{2}\int_0^1 g_m(x)^3\,\mathrm d x=\int_0^1 2x^2g_m(x)\,\mathrm d x.$$


Q: wcf configuration maxStringContentLength does not seem to be working We're trying to send a large xml string to a service method in WCF and we're getting the error

The maximum string content length
  quota (8192) has been exceeded while
  reading XML data.

The error suggests increasing the maxstringcontentlength although we weren't sure if we were supposed to do this on the client side or the server side or both. We've tried putting in on both but we still seem to get the error. I'm going to post the client and service configs below. I'm assuming there is a problem with one or both of them preventing this from working.
Any suggestions?
Client:
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_ITESTService"
                closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false"
                hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288"
                maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8"
                transferMode="Buffered" useDefaultWebProxy="true">
               <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
                    maxArrayLength="2147483647" maxBytesPerRead="4096"
                    maxNameTableCharCount="2147483647" />
               <security mode="None" />
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint name="BasicHttpBinding_ITESTService"
            address="http://localhost/TESTService.svc"
            binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_ITESTService"
            contract="TESTService.ITESTService" />
    </client>
</system.serviceModel>

Server:
<system.serviceModel>
   <bindings>
      <basicHttpBinding>
          <binding
              name="BasicHttpBinding_Service1"
              maxBufferSize="2147483647"
              maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32"
              maxStringContentLength="2147483647" maxArrayLength="2147483647"
              maxBytesPerRead="4096" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
       <service name="TESTService">
          <endpoint name="BasicHttpBinding_Service1"
              address="http://localhost/TESTService.svc"
              binding="basicHttpBinding"
              bindingConfiguration="BasicHttpBinding_Service1"
              contract="ITESTService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

A: Try adding a 'default' binding (without any name specified).
Add the readerQuota settings to this binding.
You can then even remove the readerQuota settings from the named binding you are actually using.
This worked for me (although I'm not sure why the readerQuotas on the correct named binding are ignored by WCF)

A: 'default' binding option worked for me. I was trying customize maxStringContentLength value in named WebHttpBinding but for some reason it did not picked up by WCF. finally I followed the D.Tiemstra work around then it started working.
    <webHttpBinding>
    <binding  maxReceivedMessageSize="2147483647" >
      <readerQuotas maxDepth="2147483647"
       maxStringContentLength="2147483647"
       maxArrayLength="2147483647"
       maxBytesPerRead="2147483647"
       maxNameTableCharCount="2147483647" />
    </binding>
  </webHttpBinding>

A: This thread explains in detail how to specify the binding settings on server and client correctly in order to change the MaxStringContentLength.
This other thread also provides a clear and efficient answer on using the readerQuotas.

A: I would use this values for the WCF configuration (programmatically):
Security = { Mode = SecurityMode.None},
CloseTimeout = TimeSpan.MaxValue,
OpenTimeout = TimeSpan.MaxValue,
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxBufferSize = 2147483647,
MaxBufferPoolSize = 524288,
MaxReceivedMessageSize = 2147483647,
ReaderQuotas = new XmlDictionaryReaderQuotas
{
   MaxDepth = 32,
   MaxStringContentLength = 8192,
   MaxArrayLength = 16384,
   MaxBytesPerRead = 4096,
   MaxNameTableCharCount =1638
}


Q: find element that doesn't equal a string in xpath Need help in finding element that doesn't equal to a string, Here is my XML:
<collection >
<device>
    <name>Test</name>
    <dcs>
        <dc>
            <nodes>
                <node>
                    <name>Host1</name>
                </node>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
        <dc>
            <nodes>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
    </dcs>
</device>

XPath I have tried:
/collection/device/dcs/dc/nodes/node[not(contains(name,'test'))]

O/p:
 <node>
    <name>Host1</name>
</node>

Expected O/p:
<node>
      <name>Host1</name>
</node>
<node>
      <name>testing</name>
</node>

Actual output is ignoring testing also but that I need in output.
Can anyone help me?
Thanks in advance.

A: To filter out nodes having inner text exactly equals certain value, use = operator wrapped in not() instead of using contains() in the same way  :
/collection/device/dcs/dc/nodes/node[not(name='test')]


Q: MediaPlayer.OnCompletionListener and View.OnClickListener? I  am currently trying:
extends Activity implements MediaPlayer.OnCompletionListener
extends Activity implements View.OnClickListener

at the same time and its not working or rather im not sure how to implement it...how would I go about doing this?
edit: maybe it will help if I show you guys what I have now and its not working:
package com.vamp6x6x6x.rusty;

import java.io.IOException;

import com.vamp6x6x6x.rusty.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

public class rustyactivity extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener {
    /** Called when the activity is first created. */

    ImageView display;
    int toPhone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        display = (ImageView) findViewById(R.id.IVDisplay);
        ImageView image1 = (ImageView) findViewById(R.id.IVimage1);
        ImageView image2 = (ImageView) findViewById(R.id.IVimage2);
        ImageView image3 = (ImageView) findViewById(R.id.IVimage3);
        ImageView image4 = (ImageView) findViewById(R.id.IVimage4);
        ImageView image5 = (ImageView) findViewById(R.id.IVimage5);
         Button setWall = (Button) findViewById(R.id.bSetWallpaper);

        toPhone = R.drawable.guy1;

        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
        image4.setOnClickListener(this);
        image5.setOnClickListener(this);
        setWall.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.IVimage1:
        display.setImageResource(R.drawable.guy1);
        toPhone = R.drawable.guy1;
        break;
        case R.id.IVimage2:
            display.setImageResource(R.drawable.guy2);
            toPhone = R.drawable.guy2;
            break;
        case R.id.IVimage3:
            display.setImageResource(R.drawable.guy3);
            toPhone = R.drawable.guy3;
            break;
        case R.id.IVimage4:
            display.setImageResource(R.drawable.guy4);
            toPhone = R.drawable.guy4;
            break;
        case R.id.IVimage5:
            display.setImageResource(R.drawable.guy5);
            toPhone = R.drawable.guy5;
            break;

        case R.id.bSetWallpaper:

            Bitmap whatever = BitmapFactory.decodeStream(getResources().openRawResource(toPhone));
               try{
                   getApplicationContext().setWallpaper(whatever);
               }catch(IOException e){
                   e.printStackTrace();
               }
        }

        Button ending = (Button) findViewById(R.id.theme);
        ending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSound(R.raw.theme);
            }
 });
    }
        private void playSound(int resId) {
            MediaPlayer mp = MediaPlayer.create(this, resId);
            mp.setOnCompletionListener(this);
            mp.start();
        }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub

    }
    }

A: extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener
Then you need to register your activity.
mediaPlayer.setOnCompletionListener(this);
someView.setOnClickListener(this);
Where 'this' is the activity you just created

A: Stick this code right up at the start as part of the onCreate():
MediaPlayer mp = MediaPlayer.create(this, pathToTheFile, web, whereverTheSoundIs);
mp.setOnCompletionListener(this);
mp.start();

If that doesn't work, then you have a problem locating the sound file, or it is in the wrong format.
From experience, cut things down to simple parts and try and get each part working first before moving on.
Another thing I do is put comments after each } for example:  '} // End of Case'
Oh, almost forgot, in the onCompletion you might like to close off the media player with
mp.release();

Cheers

A: try this! it works to me, i hope it helps you:
main:
package com.hairdryer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

import com.hairdryer.ServiceReproductor;

public class Reproductor extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageButton btnInicio = (ImageButton) findViewById(R.id.on);
        ImageButton btnFin = (ImageButton) findViewById(R.id.off);
        btnInicio.setOnClickListener(this);
        btnFin.setOnClickListener(this);
    }

    public void onClick(View src) {
        ImageButton btnInicio = (ImageButton) findViewById(R.id.on);

        switch (src.getId()) {
        case R.id.on:
            btnInicio.setBackgroundResource(R.drawable.on2);
            startService(new Intent(this, ServiceReproductor.class));
            break;
        case R.id.off:
            stopService(new Intent(this, ServiceReproductor.class));
            btnInicio.setBackgroundResource(R.drawable.on);
            break;
        }
    }
}

ServiceReproductor.java:
package com.hairdryer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.widget.Toast;

public class ServiceReproductor extends Service implements OnCompletionListener{
    private MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        //Toast.makeText(this, "Servicio Creado", Toast.LENGTH_LONG).show();
        player = MediaPlayer.create(this, R.raw.inicio);
        player.setOnCompletionListener(this);

    }

    @Override
    public void onDestroy() {
        //Toast.makeText(this, "Servicio Detenido", Toast.LENGTH_LONG).show();
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        //Toast.makeText(this, "Servicio Iniciado", Toast.LENGTH_LONG).show();
        player.start();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        player = MediaPlayer.create(this, R.raw.secador);
        player.start();
        player.setLooping(true);
        // TODO Auto-generated method stub

    }

}

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/secador"
        />

    <ImageButton    android:id="@+id/off"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/off"

        />
    <ImageButton    android:id="@+id/on"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/off"
        android:layout_marginRight="10dp"
        android:background="@drawable/on"

        />

</RelativeLayout>


Q: py2app and python 2.7 OSX 10.6 Does py2app work with python 2.7 on Snow Leopard?
I can't even get a 'hello world' to compile properly.
Here's what I'm doing...
My script is
print "Hello World"

and then from a terminal:
cd myFolder
py2applet --make-setup helloWorld.py myIcon.icns
python setup.py py2app

The build hangs indefinitely at this point. If I add the -A switch it will build, but crashes with a Tick Count error.
If I edit the setup.py file and set argv_emulation to 'False' it'll build with the -A option and work (still hangs indefinitely without the -A).
So my real question is:
How can I get this to build without the -A option?

A: It seems as though py2app had some issues with the 32/64-bit install of python 2.7 I was using (the official one from python.org).
I downloaded a 32-bit only version of 2.7 and it works now.
On a related note, on another build I was using wxPython and to get it to work without the -A switch I had to import the package explicitly in my setup.py file.
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
           'packages' : ['wx', 'pubsub'],

          }

A: I've read that you need to leave the 'argv_emulation': True setting out of the options for a 64bit build.  Hope this helps.


Q: Reverse Regular Expression Matching in Javascript I have a file that contains basic examples of input and output:
[Database.txt]
Hello*==Hello. How are you?
How*are*you*==I am fine I guess.
Can you*die*==I can not die. I am software.

I will get an input string that does not have punctuation.
Example: "can you ever die in a million years"
I am trying to match the input with the first side of the database on the left of "==" and return the second side of the line the string matched the first side with.
So where input = "can you ever die in a million years", output = "I can not die. I am software."
I have to use native JavaScript. This is part of a personal project I have been working on and have not been able to get past in 4 months. It is part of an independent natural speech engine that could download the file, read it to a variable, and use it as a reference. I have tried combinations of looping through lines, splitting at "==", str.match(), and a lot of other stuff. I will manage case insensitivity. Any help would be greatly appreciated.

A: You can split it up into an array, and make each left side into a regexp.
then you can run a guantlet of tests to find the match.
the tricky part is that you need to make multiple tests, beyond just one super regexp. i used [].some() to terminate after the first match is found. you can change the some with filter and collect the output to get multiple matches.
var gaunlet=[],
 str="[Database.txt]\n\
Hello*==Hello. How are you?\n\
How*are*you*==I am fine I guess.\n\
Can you*die*==I can not die. I am software.";

str.split("\n").forEach(function(a,b){
    var r=a.split("==");
    gaunlet[b]=[RegExp(r[0].replace(/\*/g,"[\\w\\W]*?"), "i"), r[1]];
});

function lookup(inp){
  var out;
    gaunlet.some(function(a){
        if(a[0].test(inp)) return out=a[1];
    });
  return out;
}

alert(lookup("can you die in a million years?"));

fiddle: https://jsfiddle.net/joaze5u6/1/
i also wrote in a fix for the way js captures wildcards, the [\w\W]*? does what .*? should probably do but doesn't in js...


Q: Index was outside the bounds of the array This is my code where I am getting error "Index was outside the bounds of the array."
var objectData = new object[colRindas.Count, 4];
     int i = 0;
     foreach (DeArtIzm izm in colRindas)
     {
         objectData[i, 1] = izm.ArtCode;
         objectData[i, 2] = izm.ArtName;
         objectData[i, 3] = izm.Price;
         objectData[i, 4] = izm.RefPrice;
         i++;//Place where I get that error
     }

What seems to be the problem hare, cause I can't find the problem.

A: Arrays are 0-indexed instead of one.
foreach (DeArtIzm izm in colRindas)
     {
         objectData[i, 0] = izm.ArtCode;
         objectData[i, 1] = izm.ArtName;
         objectData[i, 2] = izm.Price;
         objectData[i, 3] = izm.RefPrice;
         i++;//Place where I get that error
     }

A: in C#, Arrays are Zero-based by default (i.e. The first element has the index 0).
So you need to start with objectData[i, 0], and end with objectData[i, 3].


Q: What document/artifact should alert me when an old requirement changes the scope of new one? I developed a software application a year ago, I delivered it with a simple documentation.
For example, it has an special and complicated login system as requirement.
Now the customer calls and ask me to change the application for support a new kind of users, then I review (quickly) the tables, views and code that I need to change to deliver the new requirement support a new kind of users and give an estimate time, but I forgot completely that I need to refactor the special and complicated login system.
This is a big mistake because the time that I will spend in the refactor of the special and complicated login system will not be paid.
What errors have I made? and how can I avoid it in the future?
A trace ability matrix gives me relations between test cases and requirements, but I need the track of old requirements in relation with new ones.

A: Contract matters

This is a big mistake because the time that I will spend [...] will not be paid

Actually, the big mistake is that your contract makes it possible that you spend your time working for free. It doesn't matter if you are solving a bug or learning a technology required for a new project: the customer has to pay for the time you spend.
You should not work for free. That's as simple as that. It makes you feel bad, and it encourages your customer to think about you as a guy who works for free anyway, and so who don't have to be particularly respected, or paid at all, after all. As soon as your customer knows that you spend one hour working for free, your relation is screwed.
This is also why it is essential to have a contract written by an actual lawyer specialized in software development contracts.
Technical estimates

What errors I did, and how can I avoid it in the future.

Technically speaking, you error was to give an estimate too quickly. You may have spent maybe a few more hours studying the impact, and probably find the relation between the data and the authentication.
But such mistakes happen anyway, so it's not a big fault from the technical point of view.
This is not very different from cases where you give an estimate of two weeks for a task, and a week after you started the task, you find that it requires much more work. Then, you simply send to the stakeholders (would it be your manager or your customer) the readjusted estimate which takes in account the things you have discovered meanwhile.
You may have made a mistake of giving a very precise estimate. If you tell that a change will take “eighty hours”, this is not the same thing as “ten days”, and not the same thing as “two weeks”. Moreover, estimates are often represented as a range or contain a hint about the precision:

The task will take from 4 to 9 days.

or:

The task will take 16 days ± 4 days.

This makes the progressive readjustment of the estimate more intuitive.
Another important aspect is that you should be able to say no. This applies specifically to those two types of questions:

“Do you know how long this task will take?”

If you don't know how long the task will take, don't tell “Three weeks” just to get rid of the person.

“Can you make an effort to deliver it faster?”

If you answer “Yes”, it means either that your last estimate was wrong (in which case, why would you make wrong estimates in the first place?), or that you know how to be more productive, but don't do it unless specifically asked, which doesn't sound very professional either.
It's all about leverage
But, again, the most important thing is how do you interact with your customer, which boils down to two things: what contract says and what is your leverage.
For instance, compare this message:

On February 7th, I sent you an estimate of 8 days ± 3 days for the task of migrating the bottom menu to the new data source. It appears that the task also requires to make changes in the top menu, since both partially rely on the same code. Given those new elements, the updated estimate is 11 days ± 2 days.

with this one:

On February 7th, I sent you an estimate of 8 days ± 3 days for the task of migrating the bottom menu to the new data source. It appears that the task is much more difficult than I thought, so I'm not sure I'll be able to release the changes on time. Can you, please, accord me three additional days for this task?

The second one sucks. It shows that the developer has no leverage whatsoever. It doesn't give any estimate, but barely begging for extra time. It feels like the developer screwed the original estimate, and feels bad about it. The first message is purely informal: here's an estimate, I don't care what you think about it and I don't need your approval, since our contract doesn't require your approval in this case. My early estimate was correct, and the later one just takes in account additional info. Nothing more.

A:
This is a big mistake because the time that I will spend in the refactor of the special and complicated login system will not be paid.

There is a big red flag showing you what has gone wrong.  The problem was embedded in this project before any changes were requested by the client, they were there before the code was even written...
Authentication and permissions are very well-known (and solved) problems even for exceptionally complex sets of requirements (2-factor authentication, time-locking, location restrictions for example).
The next step is to prevent recurrences...
You can reflect on the original development process and examine your design documents/process to understand the factors which led to those components being tightly-coupled and warning signs to look for.  Generally, when a common function is considered 'special' it's a good indication that the situation hasn't been fully understood for example.
Instead of taking this situation as a 'cost', take it as a wake-up call that you or whoever worked on the project might benefit from some professional development to better understand the development process - it's something good developers do all the time and using that knowledge to make sure that future projects are more amenable to extension and that code is easier to test/fix.  It has given you a chance to produce better code in the future.
As starting points the Single Responsibility Principle (SRP) and Separation of Concerns (SoC) should have kept unrelated code apart and mean that you shouldn't need complicated matrices of dependencies in the future.
Grab a couple of books on code quality and spend some time on them, it will not be wasted, and a few days of extra dev time is cheap compared to some projects that lose months due to issues that could have been avoided.


Q: Does including a random intercept in a pre-post design lead to inconsistency and bias? Background: modeling pre-post experimental data
Suppose you are running an experiment but have baseline measures of the outcome:

*

*You collect baseline data on $y_{it=0}$, the univariate outcome $y$ for subject $i$.

*All subjects then randomly receive a low or high dose of a treatment. Let $Z_i = 1$ if $i$ is assigned the high dose and $0$ if assigned the low dose.

*You collect post-treatment data from the same people for the same variable: $y_{it=1}$.

Without baseline data, we could regress the post-treatment outcome on an intercept and an indicator for treatment: $y_{it=1} \sim N(\alpha + \beta_1 Z_i, \sigma_y)$
Using the baseline data, we might arrange our data in a long structure so $y_{it}$ is a vector and fit the following varying intercept model:
$$y_{it} \sim N(\mu_{it}, \sigma_y)\\
\mu_{it} = \alpha + \alpha_i  + \beta_1post_{t[i]} + \beta_2 Z_{i} \times post_{t[i]}\\
\alpha_i \sim N(0,\sigma_a)\\
\sigma_a \sim N^{+}(0,3)$$
The motivation for the model is to assume a common baseline mean $\alpha$ that is independent of $Z$ (justified since no one was assigned to treatment yet) and allow post-treatment outcomes to vary by $Z$. This implies $\beta_1$ is the mean change in $y$ for the $Z=0$ group from time $t=0$ to $t=1$ while $\beta_2$ is the deviation of group $z=1$ from that change. Subject-specific intercepts are included to model the correlated errors across time.
Question
Does including the subject random intercepts $\alpha_i$ lead to inconsistent or biased $\beta$ estimates? My concern is that this is akin to including random intercepts in a lagged dependent variable model, which creates these problems.


Q: How to Create plus symbol with background-color in CSS? I want to create plus symbol using CSS.
this is the final output need to be shown.

But the challenge is, to create this icon using,

*

*only use one div tag

*use before/after pseudo-elements

*can't use keyboard '+' icon as a base.

A:

#plus {
  /* change this value to the desired width */
  --width: 40px;
  /* setting the background color */
  background-color: black;
  /* setting height and width with the value of css variable */
  width: var(--width);
  height: var(--width);
  /* perfect circle */
  border-radius: var(--width);
  /* centrering */
  display: grid;
  place-items: center;
  /* don't delete this, is important for the ::before and ::after pseudoelements */
  position: relative;
}

#plus::before,
#plus::after {
  content: "";
  /* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
  /* height and width relative to css variable, change to what you feel is good */
  height: calc(var(--width) / 1.5);
  width: calc(var(--width) / 5);
  /* coloring the pseudoelements */
  background-color: white;
  /* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
  transform: rotate(calc(var(--i) * 90deg));
  /* important don't delete */
  position: absolute;
}

#plus::before {
  --i: 1;
}

#plus::after {
  --i: 2;
}

this code is relative to the width of the element, so just change the width and all the elements inside will be changed automatically!
#plus {
  --width: 5rem; /* change this value if you need */
}

or here directly on your element (if you have multiple same buttons)

for this I am using CSS variables, make sure to see this before https://developer.mozilla.org/en-US/docs/Web/CSS/var

Example:

*

*smaller value

*higher value:

so now you can see, the div remain always the same as with big values

the code:

#plus {
  /* change this value to the desired width */
  --width: 5rem;
  /* setting the background color */
  background-color: black;
  /* setting height and width with the value of css variable */
  width: var(--width);
  height: var(--width);
  /* perfect circle */
  border-radius: var(--width);
  /* centrering */
  display: grid;
  place-items: center;
  /* don't delete this, is important for the ::before and ::after pseudoelements */
  position: relative;
}

#plus::before,
#plus::after {
  content: "";
  /* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
  /* height and width relative to css variable, change to what you feel is good */
  height: calc(var(--width) / 1.5);
  width: calc(var(--width) / 5);
  /* coloring the pseudoelements */
  background-color: white;
  /* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
  transform: rotate(calc(var(--i) * 90deg));
  /* important don't delete */
  position: absolute;
}

#plus::before {
  --i: 1;
}

#plus::after {
  --i: 2;
}


Q: How can I obfuscate only com.foo.* but excluding com.foo.bar.*? (Proguard) I tried:
-keep class !com.foo.** { *; }
-keep class com.foo.bar.** { *; }

but it obfuscates classes other than com.foo.* (which I don't want)
I also tried:
-keep class !com.foo.**, com.foo.bar.** { *; }

and it fails to parse.

A: From your description I understand that you want to keep everything in the com.foo.bar package (+ subpackages?). You can achieve this by the following rule:
-keep class com.foo.bar.** { *; }

The ** pattern will match also subpackages, if you only want to current package, use * instead.
If you use a rule like this:
-keep class !com.foo.** { *; }

you will actually keep everything but com.foo.**, so you should be careful with exclusion patterns. Always include at least one inclusion pattern afterwards. The exclusion pattern should be more specific as the inclusion pattern, see below.
This rule should parse correctly (just tested it), but will not work, as ProGuard will stop evaluating a rule once it finds a match:
-keep class !com.foo.**, com.foo.bar.** { *; }

The exclusion pattern !com.foo.** will match everything in com.foo and subpackages, thus it will also match com.foo.bar.


Q: Video trimming on Android using MediaCodec, Media Extractor and Media Muxer In my Android App I need a solution when the user can trim a video from internal storage. I am trying to achieve this without using any third-party library. I was referencing this Google's Gallery App source code  here. But I am getting the following error :
timestampUs 66733 < lastTimestampUs 133467 for Video track
There are few SO questions which talk about this timestamp issue, but I am really not being to figure out as I am new to using MediaCodecs, MediaMuxers etc. Would be great if any can hep
Here's my code :
 // Set up MediaExtractor to read from the source.
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(srcPath);
    int trackCount = extractor.getTrackCount();
    System.out.println("tracl" + trackCount);
    // Set up MediaMuxer for the destination.
    MediaMuxer muxer;
    muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

    // Set up the tracks and retrieve the max buffer size for selected
    // tracks.
    HashMap<Integer, Integer> indexMap = new HashMap<>(trackCount);
    int bufferSize = -1;
    for (int i = 0; i < trackCount; i++) {
        MediaFormat format = extractor.getTrackFormat(i);

        String mime = format.getString(MediaFormat.KEY_MIME);
        boolean selectCurrentTrack = false;
        if (mime.startsWith("audio/") && useAudio) {
            selectCurrentTrack = true;
        } else if (mime.startsWith("video/") && useVideo) {
            selectCurrentTrack = true;
        }
        if (selectCurrentTrack) {
            extractor.selectTrack(i);
            int dstIndex = muxer.addTrack(format);
            System.out.println(format);
            System.out.println("dstIndex" + dstIndex);

            indexMap.put(i, dstIndex);
            if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
                int newSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
                bufferSize = newSize > bufferSize ? newSize : bufferSize;
            }
        }
    }

    System.out.println(indexMap);

    if (bufferSize < 0) {
        bufferSize = DEFAULT_BUFFER_SIZE;
    }
    // Set up the orientation and starting time for extractor.
    MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
    retrieverSrc.setDataSource(srcPath);
    String degreesString = retrieverSrc.extractMetadata(
            MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
    if (degreesString != null) {
        int degrees = Integer.parseInt(degreesString);
        if (degrees >= 0) {
            muxer.setOrientationHint(degrees);
        }
    }
    if (startMs > 0) {
        extractor.seekTo(startMs * 1000, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
    }

  //  System.out.println(extractor.);
    // Copy the samples from MediaExtractor to MediaMuxer. We will loop
    // for copying each sample and stop when we get to the end of the source
    // file or exceed the end time of the trimming.
    int offset = 0;
    int trackIndex = -1;
    ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();

    try {
        muxer.start();
        while (true) {

            System.out.println("copying");
            bufferInfo.offset = offset;

            bufferInfo.size = extractor.readSampleData(dstBuf, offset);

            if (bufferInfo.size < 0 ) {
               // InstabugSDKLogger.d(TAG, "Saw input EOS.");
                System.out.println("Saw input EOS.");
                bufferInfo.size = 0;
                break;
            } else {

                /**
                 * The presentation timestamp in microseconds for the buffer.
                 * This is derived from the presentation timestamp passed in
                 * with the corresponding input buffer.  This should be ignored for
                 * a 0-sized buffer.
                 */

                /**
                 * Returns the current sample's presentation time in microseconds.
                 * or -1 if no more samples are available.
                 */
                bufferInfo.presentationTimeUs = extractor.getSampleTime();

                //1 sec = 1000000 micco sec

                if (endMs > 0 && bufferInfo.presentationTimeUs > (endMs * 1000)) {

                    break;
                } else {
                    bufferInfo.flags = extractor.getSampleFlags();
                    trackIndex = extractor.getSampleTrackIndex();

                    muxer.writeSampleData(indexMap.get(trackIndex), dstBuf, bufferInfo);

                    //System.out.println(muxer);
                    extractor.advance();
                }
            }
        }

        muxer.stop();

        File file = new File(srcPath);
        file.delete();
    } catch (IllegalStateException e) {

        System.out.println("The source video file is malformed");

    } finally {

        muxer.release();

    }


Q: Is there an ExecutorService implementation with queue limit and an option to replace old queue members with new ones? I need an ExecutorService implementation that can limit how many Runnables can be queued. I would also like to be able to control what happens when new runnables are submitted while the queue is already full. Ideally I'd like to be able to select a strategy but just removing the runnable at the front of the queue and placing the new one at the end of the queue would suffice. I'm sure there must be something like that already implemented and I looked around but couldn't find any.

A: Use DiscardOldestPolicy :

A handler for rejected tasks that discards the oldest unhandled
  request and then retries execute, unless the executor is shut down, in
  which case the task is discarded.

and BlockingQueue with fixed capacity:
int fixedThreadNumber = 10;
int idleSeconds = 10;

BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(10);

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        fixedThreadNumber,
        fixedThreadNumber,
        idleSeconds, TimeUnit.SECONDS,
        blockingQueue, new ThreadPoolExecutor.DiscardOldestPolicy());

ExecutorService executor = threadPoolExecutor;


Q: JPA/Hibernate using shared id and cascade=all tries to save child before parent, causing foreign key violation I am using JPA with hibernate. I have a 1-to-1 parent child relationship (the child is optional), with the id shared between the two and a foreign key relationship on the child table. My entities look like this:
parent:
public class LogItemEntity {
...

    @OneToOne(cascade={CascadeType.ALL}, mappedBy = "logItem", orphanRemoval=true, optional=true)
    @PrimaryKeyJoinColumn(referencedColumnName="ral_id")
    private LogAdditionalRequirement additionalRequirement;
...
}

child:
public class LogAdditionalRequirement {
...
    @Id
    @GeneratedValue(generator = "foreign")
    @GenericGenerator(name = "foreign", strategy = "foreign", parameters = { @Parameter(name = "property", value = "logItem") })
    @Column(name = "ral_id")
    private Long id;

    @OneToOne(optional=false)
    @PrimaryKeyJoinColumn(referencedColumnName="id")
    private LogItemEntity logItem;
...
}

When inserting a new object, the id for the parent is generated from a sequence and the cascade operation copies it onto the child. But the sql insert for the child is placed in the action queue of the session before the sql insert for the parent, and so it fails with a constraint violation on the foreign key:
ERROR o.h.util.JDBCExceptionReporter - ERROR: insert or update on table "rar_log_additional_requirement" violates foreign key constraint "fk_rar_ral_id"
Detail: Key (ral_id)=(70150) is not present in table "ral_log".

So how can I make the insert of the parent happen first?
This must be a pretty common usage, so I assume I'm doing something wrong, but I don't see what it is. I originally had the mappedBy attribute on the child side. I think that's wrong, but swapping it round made no difference.

A: One solution could be to remove the cascade "cascade={CascadeType.ALL}"
More on this subject here


Q: Braintree for flutter web I have a broader question. Is there any possibility to use a brain tree for the flutter web? I was searching for an API on pub.dev but there was only one for Android & Ios, but not for Web.
If there is one do you have a link to an example project, I just don't seem to find anything about the detailed integration

A: You can use Braintree using API calls with their GraphQL client. Read the whole guide on how to make API calls on their website.
Making API Calls


Q: How to make an image fill the entire div on hover? I want an image to show up on the div when I hover it. The code I am using makes the image larger than the div, how can I contain it to the fill the size of the div and not leak?
Here is the CSS code:
  img{
    display: none;
    max-height: 50vh;
  }
  .effect:hover .text{
    display: none;
  }
  .effect:hover img{
    display: block;
  }

Here is the HTML code:

Studio Griot

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Web Development

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Data Visualisation

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Incrediminds

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Thanks For The Help

A: EDIT with what OP actually wanted.
Here is the image that takes up the full width and height without stretching. You can use object-fit: cover
Information on object-fit: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

img {
  display: none;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.effect:hover .text {
  display: none;
}

.effect:hover img {
  display: block;
}

h1.text {
  font-size: 14px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

Studio Griot

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Web Development

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Data Visualisation

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Incrediminds

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Add width: 100% to the img. That will keep it 100% width of its parent. I changed your bootstrap markup to col-sm so you could see it when you run the snippet.
Added information for future visitors:
An img will always display as large as its own default/native size, unless you specify the width: 100% and make sure it is display: block, since img are inline by default.

img {
  display: none;
  width: 100%;
}

.effect:hover .text {
  display: none;
}

.effect:hover img {
  display: block;
}

h1.text {
  font-size: 14px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

Studio Griot

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Web Development

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Data Visualisation

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.

Incrediminds

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.


Q: Partial differential equation (multidimensional, Navier–Stokes) What is generic approach to solving this system?
$$
\rho\left({\partial v_i \over\partial t}+v_k{\partial v_i \over \partial x_k} \right) = - {\partial p \over\partial x_i} + {\partial \over\partial x_k}\left\{ \mu \left({\partial v_i \over\partial x_k}+{\partial v_k \over\partial x_i} - {2\over 3}\delta_{i,k}{\partial v_l \over\partial x_l}\right)  \right\}+{\partial  \over\partial x_k}\left( \zeta {\partial v_l \over\partial x_l}\delta_{i,k}\right)
$$
$$\vec{v}|_{\partial \Omega} = 0, \quad \vec{v}|_{t=0} = \vec{v}_{0}$$
I finished a course in differential math and PDE, but I can't even say what is the kind of the task.
The task is to be solved numerically.
PS: or can anybody say something about last two formulas? What is "\partial \Omega" ($\partial \Omega$) usually means?

A: This is the Navier–Stokes for compressible fluid exactly as was recorded here http://ru.wikipedia.org/wiki/%D0%A3%D1%80%D0%B0%D0%B2%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F_%D0%9D%D0%B0%D0%B2%D1%8C%D0%B5_%E2%80%94_%D0%A1%D1%82%D0%BE%D0%BA%D1%81%D0%B0
and the second formula seems to be "No Slip Condition", e.g. here http://scienceworld.wolfram.com/physics/NoSlipCondition.html for non-movable container. and the '\partial \omega' sounds as ... walls of the container. So, fluid at the points, just next to the walls is stopped and notmovable.


Q: Efficient way to store form data? I have a web app that has a big and complex form (fields, checks, etc).
I hade using standard OS form controls because they have visual (styling) limits.
I have been basically creating spans with IDs and attaching class or custom data attributes. I later need to send this to a PHP script for insertion into a database. This has worked well in the past, but I'm having to do a lot of manual processing of fields, which I don't think is efficient... Is there a better way?
I currently do,
IF ($('#foo').hasClass('on')){bar=1}

...
Then I manually compose a POST string via
foo=bar&bla=blabla ...

Then lots more on the PHP side to create an insert SQL statement.
Seems like its inefficient if you have dozens of fields... But I hate standard FORM elements...
Any suggestions? .... Loops? Arrays?

A: You should use a form. But how to make it pretty?
With JavaScript you can have a kind of front-end for the form. Hide the form elements and have some JS that changes the form field values on interaction.
Search for pretty forms jquery in Google.

A: From what I understand is that you don't want to manually get the value of each element that has the class 'on'. You could use jQuery's each function looping through all the elements you need. Something like:
var query = "";

$(".on").each(function(i){
    if(i === 0) {
      query+="?"+$(this).attr('id')+"="+$(this).text();
    } else {
        query+="&"+$(this).attr('id')+"="+$(this).text();
    }
});

(see: http://jsfiddle.net/MkbrV/)
Is this something you are looking for?

A: You could use jQuery's serialize() method:
$('form .on').serialize();

jsFiddle example


Q: Prefetch all relationship instances without call .all() I prefetch_related my objects with the following code:
    objs = wm.ModelA.objects.prefetch_related(
    'ModelB__ModelC')

and i want to iterate all ModelB from all objs and i do it with the following way
            for o in objs:
                for t in o.ModelB.all():

I noticed that in every iteration of e.ModelB.all() it calls the database. Is there a way to avoid this and bring all MobelB from the begining ?


Q: OPC Foundation Tree structure I've been searching the web, but I can't figure out how to get a tree view of the items on an OPC server. I used the following code:
 using Opc.Da;
 using Server=Opc.Da.Server;
 using Factory=OpcCom.Factory;

 string urlstring = string.Format("opcda://{0}/{1}/{{{2}}}", _hostName, _serverName, serverid);
 Server s = new Server(new Factory(), new URL(urlstring));
 ItemIdentifier itemId = null;
 BrowsePosition position;
 BrowseFilters filters = new BrowseFilters() {BrowseFilter = browseFilter.item};
 BrowseElement[] elements = s.Browse(itemId, filters, out position);

A: You do not state what precisely does not work. However, the main problems is probably in the fact that you are using BrowseFilter = browseFilter.item. The nodes in the tree are either leaves (sometimes called items), or branches. Your code only asks for the leafs, under the root of the tree. There may be no items under the root whatsoever, and you need to obtain the branches as well, and then dwelve deeper into the branches, recursively.
Start by changing your code to use BrowseFilter = browseFilter.all. This should give you all nodes under the root. Then, call the Browse recursively for the branches (just branches, not items) you receive, using the item ID of each branch as the starting point for the new browse.


Q: How to use ClamAV Antivirus in AWS EC2 for scanning S3 Bucket object when any file uploaded to s3 bucket? I need to run ClamAV antivirus in EC2 instance that can help me to scan a virus for s3 bucket object when any object being uploaded to s3. Is their any blog or way that i can use?

A: You can use S3 VirusScan, which is a third-party open source tool.
Some of its features are:

*

*Uses ClamAV to scan newly added files on S3 buckets

*Updates ClamAV database every 3 hours automatically

*Scales EC2 instance workers to distribute workload

*Publishes a message to SNS in case of a finding

*Can optionally delete compromised files automatically

*Logs to CloudWatch Logs

A: If you want to implement the solution by yourself, you can use: https://aws.amazon.com/blogs/developer/virus-scan-s3-buckets-with-a-serverless-clamav-based-cdk-construct/


Q: My draft in Outlook doesn't allow editing? I am trying to edit a draft, but this is the message I get:

Due to the size of this email, we've turned off Editor temporarily.

What do I need to do to enable editing??

A: As per my experience, this error is usually caused by large image presented in the signature. So if it happens that the problematic draft has a signature with image, try removing the image and see it helps.
Besides, considering that the error is often seen in OWA, so if you are referring to Outlook on the web by "Outlook", it's also suggested to open a private browser window and check the result.


Q: Working with jsoncpp to automate outputing json data
I am trying to automate the process of outputing the broad disciplines of UC Berkeley's majors. I have shortened the code and the JSON data to make the issue clearer. It is stored in JSON format and I am using the jsoncpp api to work with the data. The json data is the following:
{ "Berkeley": {
"1" :
{
"Broad Discipline": "Agriculture & Natural Resources",
"College/School**": "Letters & Science",
"Major": "ENVIRONMENTAL ECONOMICS & POLICY",
"Admit GPA Range": "3.63 - 3.94",
"Admit Rate": "0.342105263",
"Enroll GPA Range": "3.65 - 3.94",
"Yield Rate": "0.730769231",
"Admits": "26",
"Apps": "76",
"Enrolls": "19"
},
"2" :
{
"Broad Discipline": "Agriculture & Natural Resources",
"College/School**": "Natural Resources",
"Major": "CONSERVATION & RESOURCE STUDIES",
"Admit GPA Range": "3.32 - 3.88",
"Admit Rate": "0.333333333",
"Enroll GPA Range": "3.30 - 3.90",
"Yield Rate": "0.818181818",
"Admits": "22",
"Apps": "66",
"Enrolls": "18"
}
}}

Prior to this section of code, root is a json::Value and holds all the json data shown above.
// for loop through school's broad disciplines
for (int i = 0; i < 2; i++)
{
  string element = "\"" + to_string(i + 1) + "\"";
  string broadDiscipline = (root["Berkeley"][element]["Broad Discipline"]).asString();
  cout << "Broad Discipline: " << broadDiscipline << endl;
}

I would expect it to output:
Broad Discipline: "Agriculture & Natural Resources"
Broad Discipline: "Agriculture & Natural Resources"

The actual result is:
Broad Discipline:
Broad Discipline:

I do not know what I am doing wrong. Also I can not find the documentation in jsoncpp for whatever function is called in a command like: root["Berkeley"].


Q: Queue messages not being moved to the poison queue I have a job that imports files into a system. Everytime a file is imported, we create a blob in azure and we send a message with instructions to a queue so that the data is persisted in SQL accordingly. We do this using azure-webjobs and azure-webjobssdk.
We experienced an issue in which after the messages failed more than 7 times, they didn't move to the poision queue as expected. The code is the following:
Program.cs
public class Program
{
    static void Main()
    {
        //Set up DI
        var module = new CustomModule();
        var kernel = new StandardKernel(module);

        //Configure JobHost
        var storageConnectionString = AppSettingsHelper.Get("StorageConnectionString");
        var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel), NameResolver = new QueueNameResolver() };
        config.Queues.MaxDequeueCount = 7;
        config.UseTimers();

        //Pass configuration to JobJost
        var host = new JobHost(config);
        host.RunAndBlock();
    }
}

Functions.cs
public class Functions
{
    private readonly IMessageProcessor _fileImportQueueProcessor;

    public Functions(IMessageProcessor fileImportQueueProcessor)
    {
        _fileImportQueueProcessor = fileImportQueueProcessor;
    }

    public async void FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
    {
        await _fileImportQueueProcessor.ProcessAsync(item);
    }

}

_fileImportQueueProcessor.ProcessAsync(item) threw an exception and the message's dequeue count was properly increased and re-processed. However, it was never moved to the poison-queue. I attached a screenshot of the queues with the dequeue counts at over 50.
After multiple failures the webjob was stuck in a Pending Restart state and I was unable to either stop or start and I ended up deleting it completely. After running the webjob locally, I saw messages being processed (I assumed that the one with a dequeue count of over 7 should've been moved to the poison queue).
Any ideas on why this is happening and what can be done to have the desired behavior.
Thanks,
Update
Vivien's solution below worked.
Matthew has kind enough to do a PR that will address this. You can check out the PR here.

A: Fred,
The FileImportQueue method being an async void is the source of your problem.
Update it to return a Task:
public class Functions
{
    private readonly IMessageProcessor _fileImportQueueProcessor;

    public Functions(IMessageProcessor fileImportQueueProcessor)
    {
        _fileImportQueueProcessor = fileImportQueueProcessor;
    }

    public async Task FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
    {
        await _fileImportQueueProcessor.ProcessAsync(item);
    }
}

The reason for the dequeue count to be over 50 is because when _fileImportQueueProcessor.ProcessAsync(item) threw an exception it will crash the whole process. Meaning the WebJobs SDK can't execute the next task that will move the message to the poison queue.
When the message is available again in the queue the SDK will process it again and so on.


Q: How to read long lines from child pocress' stdout in an efficient way? Note: This question has changed significantly since the first version, so some comments or answers could seem weird. Please, check the edit history if something seems weird.
I am launching a child process from a C# class library.
I am using Process.BeginOutputReadLine() to read the output/error in an asynchronous way. I thought it didn't work with very long lines, but the problem seems to be that it's not scalable. In my computer, a 128 kb line is processed instantly, a 512 kb line seems to take around one minute, 1 mb seems to take several minutes, and I've been around two hours waiting for a 10 mb line to be processed, and it was still working when I cancelled it.
It seems easy to fix reading directly from the StandardOutput and StandardError streams, but the data from those streams seems to be buffered. If I get wnough data from stdout to fill the buffer, and then some more data from stderr, I can't find a way to check if there's data pending in one of them, and if I try to read from stderr, it will hang forever.
Why is this happening, what am I doing wrong, and what's the right way to do this?
Some code samples to illustrate what I'm trying to achieve.
Program1:

    // Writes a lot of data to stdout and stderr
    static void Main(string[] args)
    {
        int numChars = 512 * 1024;
        StringBuilder sb = new StringBuilder(numChars);

        String s = "1234567890";

        for (int i = 0; i < numChars; i++)
            sb.Append(s[i % 10]);

        int len = sb.Length;
        Console.WriteLine(sb.ToString());
        Console.Error.WriteLine(sb.ToString());
    }

Program2:

    // Calls Program1 and tries to read its output.
    static void Main(string[] args)
    {
       StringBuilder sb = new StringBuilder();
       StringBuilder sbErr = new StringBuilder();

       proc.StartInfo.CreateNoWindow = true;
       proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
       proc.StartInfo.UseShellExecute = false;

       proc.StartInfo.RedirectStandardError = true;
       proc.StartInfo.RedirectStandardOutput = true;
       proc.StartInfo.RedirectStandardInput = false;

       proc.StartInfo.Arguments = "";
       proc.StartInfo.FileName = "program1.exe";

       proc.ErrorDataReceived += (s, ee) => { if (ee.Data != null) sbErr.AppendLine(ee.Data); };
       proc.OutputDataReceived += (s, ee) => { if (ee.Data != null) sb.AppendLine(ee.Data); };

       proc.Start();
       proc.BeginOutputReadLine();
       proc.BeginErrorReadLine();
       proc.WaitForExit();
    }

Program1 has a constant that allows to set the size of data to generate, and Program2 launches Program1 and tries to read the data. I should expect the time to grow linearly with size, but it seems much worse than that.

A: I hope i understand your problem. the application hangs on Process.WaitForExit() because this is what Process.WaitForExit(): it waits for the process to exit.
you might want to call it in a new thread:
int your method that create the process:
    Thread trd = new Thread(new ParameterizedThreadStart(Start));
     trd.Start();

and add this method:
  private void Start(object o)
  {
     ((Process)o).WaitForExit();
     // your code after process ended
  }


Q: MySQL doesn't always use a key with the same query I've got a table:
CREATE TABLE `myTable` (
`a` DECIMAL(8,3) NULL DEFAULT NULL,
`b` INT(11) NULL DEFAULT NULL,
`name` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`id` INT(11) NOT NULL AUTO_INCREMENT,
`plus` VARCHAR(100) NOT NULL DEFAULT 't' COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
INDEX `myKey` (`a`, `b`, `name`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2416682;

I run a query:
SELECT * FROM myTable
order by a, b, name
limit 10000, 8 ;

It is very slow, takes about two seconds.
If I run an explain, it gives back this:
        'id' => 1,
        'select_type' => 'SIMPLE',
        'table' => 'myTable ',
        'partitions' => NULL,
        'type' => 'ALL',
        'possible_keys' => NULL,
        'key' => NULL,
        'key_len' => NULL,
        'ref' => NULL,
        'rows' => 1759263,
        'filtered' => 100.00,
        'Extra' => 'Using filesort',

Now if I set the limit to a lower value, it becomes very fast and explain says it uses myKey:
SELECT * FROM myTable
order by a, b, name
limit 1000, 8 ;

explain:
        'id' => 1,
        'select_type' => 'SIMPLE',
        'table' => 'myTable',
        'partitions' => NULL,
        'type' => 'index',
        'possible_keys' => NULL,
        'key' => 'myKey',
        'key_len' => '779',
        'ref' => NULL,
        'rows' => 1008,
        'filtered' => 100.00,
        'Extra' => NULL,

What can I do to make the select faster when the limit has high numbers?
I'm suprised the key is not used all the time, independent of the limit value. Is this normal?
MySQL version is 5.7.20-log.
Thanks

A: You can force the use of the index by doing the following:
FORCE INDEX (myKey)

FORCE INDEX mySQL ...where do I put it?


Q: C# model for nested properties I need to make API request to CloudFlare to purge cache of individual files.
Can someone please guide how to represent the below as C# model class.
files: [
        "http://www.example.com/css/styles.css",
        {
          "url": "http://www.example.com/cat_picture.jpg",
          "headers": {
            "Origin": "cloudflare.com",
            "CF-IPCountry": "US",
            "CF-Device-Type": "desktop"
          }
        }
      ]

A:     var obj = new
    {
        files = new object[]
        {
            "http://www.example.com/css/styles.css",
            new
            {
                url = "http://www.example.com/cat_picture.jpg",
                headers = new Dictionary<string,string>
                {
                    { "Origin", "cloudflare.com" },
                    { "CF-IPCountry","US" },
                    { "CF-Device-Type", "desktop"}
                }
            }
        }
    };

The dictionary is there because of the awkward property names like CF-IPCountry which make it not possible to use an anonymous type.
To show it working:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.Indented);

gives:
{
  "files": [
    "http://www.example.com/css/styles.css",
    {
      "url": "http://www.example.com/cat_picture.jpg",
      "headers": {
        "Origin": "cloudflare.com",
        "CF-IPCountry": "US",
        "CF-Device-Type": "desktop"
      }
    }
  ]
}

Edit; that's not quite right - the dictionary didn't work, but I don't have time to fix it.

A: Using classes (maybe you could use better class names then mine :) ):
class Root
{
    [JsonProperty(PropertyName = "files")]
    public List<object> Files { get; set; } = new List<object>();
}

class UrlContainer
{
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }

    [JsonProperty(PropertyName = "headers")]
    public Headers Headers { get; set; }
}

class Headers
{
    public string Origin { get; set; }

    [JsonProperty(PropertyName = "CF-IPCountry")]
    public string CfIpCountry { get; set; }

    [JsonProperty(PropertyName = "CF-Device-Type")]
    public string CfDeviceType { get; set; }
}

Usage
var root = new Root();

// Add a simple url string
root.Files.Add("http://www.example.com/css/styles.css");

var urlContainer = new UrlContainer() {
    Url = "http://www.example.com/cat_picture.jpg",
    Headers = new Headers()
    {
        Origin = "cloudflare.com",
        CfIpCountry = "US",
        CfDeviceType = "desktop"
    }
};

// Adding url with headers
root.Files.Add(urlContainer);

string json = JsonConvert.SerializeObject(root);

Note: I'm using Newtonsoft.Json