permutation of a subset from a set with multiple repetitions

Question: Suppose I have an urn with 20 tokens which has 10 different colors and each color appears exactly twice. These token are are non distinct except their color. The question is in how many different arrangements of 10 can be made from these above mentioned 20 tokens?
How would be solve the generalized version of this problem: An urn contains $\sum_{i=1}^{n}a_{i}$ tokens in all, of which $a_1$ of them are of the first color, $a_2$ of them are of the second color and  $a_n$ of them are of the $n^{th}$ color, then in how many ways can we arrange $m$ token chosen from this urn?
Comment: There is no "formula" for this, but there are ways to compute it. See https://math.stackexchange.com/questions/3090295/drawing-balls-of-different-colors-from-an-urn, and also the list of linked questions.
Comment: In particular, I illustrated the exponential generating function method [in this anwer](https://math.stackexchange.com/questions/3325683/how-to-calculate-the-number-of-distinct-subsets-of-a-set-that-has-repeated-eleme).
Comment: what have you tried ? have you ever heard permutation with repetition ?
Comment: I know how to solve the combination version of this problem, but the permutation version becomes difficult because you need to consider all possible different choices and consider each of them separately... unless I am overthinking
Comment: If this problem were assigned to me, I'd break it into consideration of cases.  First case is there are no repeated colors in the arrangement of ten tokens.  Second case is one repeated color in those arrangements.  So on, up to final case where the ten tokens are representative of just five colors.  Your generalized problem is typically a lot more difficult because the number of possible repetitions of a color can be more than two and indeed varies with the color.
Comment: Isn't there a more elegant way to do it than the case by case handling?
Answer: There is no formula, but there is a method to compute the number of ways using a recursive procedure and a computer. As I mentioned in the comments, this question has been asked many times before on this site, but I have never taken the time to write out this simple method.
For each $k\in \{1,2,\dots,n\}$, and each $j\in \{0,1,\dots,m\}$, let
$$
A(k,j)=
\begin{matrix}
\text{number of arrangements of $j$ items from an urn with $k$ colors of tokens,}\\\text{with $a_1$ tokens of the first color, $a_2$ of the second color, ... , $a_k$ of the $k^{th}$ color}
\end{matrix}
$$
The answer to your problem is $A(n,m)$, while $A(k,j)$ is a simpler problem for $k<n$ and $j<m$. These subproblems satisfy the following recursive equation:
$$
A(k,j) = \sum_{i=0}^{\min(j,a_k)} \binom{j}{i}A(k-1,j-i)\\
A(1,j)=\begin{cases}1 & 0\le j\le a_1 \\ 0 & a_i< j\end{cases}
$$
The idea is that in order to count the number of arrangements of $j$ items using the first $k$ colors, you consider all the possibilities for the number of times color $k$ is chosen. If color $k$ appears $i$ times, then you can place those $i$ tokens in the sample in $\binom ji$ ways, and then fill in the remaining $j-i$ spots with the first $k-1$ colors in $A(k-1,j-1)$ ways.
This recursive equation lets you compute $A(n,m)$ by filling out a $(n+1)\times m$ dynamic programming table, whose entry in the $k^{th}$ row and $j^{th}$ column is $A(k,j)$. Since there are $O(mn)$ entries, and each entry is a summation of $O(m)$ terms, the time this takes is $O(m^2n)$. The time this takes gets unwieldly pretty quickly. For a faster method, you would instead have to use exponential generating functions, using FFT multiplication to multiply the polynomials. For more details, see my other answer here.
Answer: You have N objects, some are identical. Label them (1,1) through (N,m) where the first component is just the kth object and the second component is the jth class. |j| = size of the jth class.
There are clearly N! ways to order these N objects. The problem is that some the same so some of these orderings will be identical and so we have to remove them.
Say you have Red_(1,1) Blue_(2,2) Green_(3,3) Red_(4,1)
This arrangement is the same as Red_(4,1) Blue_(2,2) Green_(3,3) Red_(1,1)
If we ignore the class info then we have Red_1 Blue_2 Green_3 Red_4 and Red_4 Blue_2 Green_3 Red_1 and these are different than the fully distinguishable case. Hence we "double counted".
If we ignore the distinguishing indexing then we Red_1 Blue_2 Green_3 Red_1 or just Red Blue Green Red.
Now if we index them we actually have $N = \sum a_i$ total distinguishable objects and so N! possible combinations. But now we have to remove "extras" due to collapsing to classes. In the above example, Red_(1,1) and Red_(4,1) are different and but they are also the same. How are they the same? We can swap them. There are 2! ways to swap. So we must remove 2!. If we had 3 reds(a_1 = 3) then we could form 3! different distinct strings or remove 3! to collapse them.
The way I think about this removable is that we collapse down all the same class objects to one object but that object exists in "multiple places" due to the original arrangement order. E.g., what I showed above. E.g., say we have RBGRRGRBBRRG but we also have RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, RBGRRGRBBRRG, etc. Yes, these are all the same! NO THEY ARE NOT ALL THE SAME! YES THEY ARE! If you just think of "how many ways can I fill the R's with my a_R marbles, well, there are a_R! ways. Same goes for each of the other colors. But when we combine them we have to multiply to get all the possible combinations. If you are just dealing with R's then you can ignore the B and G's for now so that RBGRRGRBBRRG -> RRRRRR. So we have 6 R's that we can fill in with our 6 red marbles. If we ordered our marbles then that would be 6! ways to arrange them. RBGRRGRBBRRG -> BBB and so we can arrange our 3 blue marbles 3! ways and RBGRRGRBBRRG -> GGG also has 3!. Combined though this means we have 6!*3!*3! distinguishing combinations(and to go the opposite way we have to remove these).
This is an easier problem than if we are given, say, a pattern like RGRRGB and have 10 reds, 34 greens, and 8 blue marbles and asked how many distinguished combinations can we form. Well, only slightly more difficult. We have 3 spots for our red marbles and have 10 so we have 10C3, then 24C2 and 8C1. Then multiply together to get all combinations. But that was just for RGRRGB, we then might have RRGGBR and all other arrangements for those sequences(which is a sort of separate problem).
So you end up with $$\frac{(\sum a_i)!}{\prod a_i!}$$
Note that if they are all distinguishable then you just have $N!$. Imagine you have 2 classes of x and y elements. This means you have a total of $(x+y)!$ ways to order them if you treat the elements as distinct. Once you have those combinations you have over counted by x! and y! ways(for a total of x!*y!).
Comment: This only deals with the case $m=\sum_{i=1}^n a_i$, but OP also cares about when $m<\sum_{i=1}^n a_i$, as their first example illustrates.


Force FFmpeg output only TCP as RTSP proxy

Question: There are lot of topics around about RTSP and FFmpeg, but in none of them I have found how to force FFmpeg outputing a TCP RTSP instead of default UDP.
I know how to force the input to TCP, with -rtsp_transport tcp option, but I cannot find how to force the output.
Someone solved suggesting to use avformat_write_header(ofmt_ctx, &options); but did not say nothing mode about that, and this is too generic info.
Thanks a lot for help!
I am using this string, it connect to first source by TCP, but FFmpeg is not opening a TCP listenng port. It does open 4 UDP ports with different values (far from what I have specified for tcp), anyway I have tried to connect to them too with VLC, but no one works.
ffmpeg -re -i rtsp://email@example.com:554/live.sdp -rtsp_transport tcp -f rtsp -rtsp_transport tcp rtsp:/192.168.0.100:50041/

Answer: I've solved it using https://github.com/aler9/rtsp-simple-server
in the end you may get a TCP stream from the rtsp://serverIP:port/proxied
it seems there are no ways to tell ffmpeg to stream on TCP only


Download Views CSV automatically Daily

Question: I have a bunch of views/reports built for my client. The reviewers then click download csv for the excel file. They asked if the views could download themselves daily to a folder.
Is that possible? And could you share links or knowledge how to handle this. I have been trying to figure it out.
Note: Right now the user is downloading CSV's from Drupal 7, an install of Moodle 1.9 in a Drupal 6 Shell and Survey Monkey. After they download and combine using Excel, the user creates reports that way for the users we have come to our events. Being a Front-end developer, coding is not my strength.
Answer: Maybe you want to consider the Forena module (disclosure: I'm a co-maintainer of it) ... Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

My answer to "How to retrieve data directly from a Drupal database" contains like a 1 minute summary to explain the typical (about 3) steps for creating:

a connection to an external database (typically by an admin).
a custom SQL query (typically by an admin).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).

These steps (without any PHP coding involved ...) are like the equivalent to writing the PHP coding as included in the question there.
For an online demo (prior to installing/testing Forena), refer to these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.

Forena Documentation, which you also get in your own site after installing the module). It contains topics such as (incomplete list):

Module installation and administration, a kind of getting started guide.
WYSIWYG Report Writing, using a report editor to facilitate the creation of reports.
Site Building, topics about integrations of Forena with other Drupal modules.
Forena hooks, to use it in other (custom) modules.
Comment: Wow, Thank you for the answer. Right now the user is downloading csv's from Drupal 7, an install of Moodle 1.9 in a Drupal 6 Shell and Survey Monkey. After they download and combine using Excel, she creates reports that way for the users we have come to our events.

Being a Front-end developer, coding is not my strength. I will be spending some time today to read through this module.   If you have more to share based on that please share away! I still have a lot to learn. Thanks!
Answer: You might want to take a look at Views Rules. It's just for Drupal 7, but it should allow you to integrate your view with rules.
Views Bulk Operations might be another option, it can also work with rules, but might be have a bit of a learning curve to get it set up.

Download Views CSV automatically Daily


Asp.Net load data by button click

Question: I have a simple list view where I'm loading my data.
Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Your application description page.";
        IList<Product> products;

        using (ISession session = NHibernateSession.OpenSession())  // Open a session to conect to the database
        {
            products = session.Query<Product>().ToList(); //  Querying to get all the books
        }

        return View(products);
    }
}

View is a simple list view from template.
Now, I need to load data to list view just after button click.
So as I understand I need to render partial view.
I've add this to view:
<button id="Load">Load data</button>

And add controller action:
public ActionResult LoadData()
{
    // here will be model creation and passing view
    return PartialView();
}

But controller action doesn't get called.
What should I do?
Comment: Then its not being loaded correctly or in the wrong order, and your script should be immediately before the closing `` tag, or wrapped in `$(document).ready()`
Comment: also, button by default type is "submit" for ajax please specify button type "button" (in case page is being submitted).
Comment: What errors do you get in the browser console?
Comment: @StephenMuecke Now I that I have "$ is not defined", but I'v include JQuery script in layout.cshtml
Comment: @StephenMuecke thanks, that's it.
Answer: This is now I would do it.
We create an action method which return JSON on http gets
public class SomeController : Controller

    [HttpGet]
    public ActionResult LoadData()
    {
        using (ISession session = NHibernateSession.OpenSession())  // Open a session to conect to the database
        {
            products = session.Query<Product>().ToList(); //  Querying to get all the books
        }

        return Json(new {data=product},
                    JsonRequestBehavior.AllowGet);
    }

Inside your view we do a ajax request to get the data by calling LoadData
$.ajax({
  type: 'get',
  dataType: 'json',
  url: 'SomeController/LoadData',
  success: function (data) {
    //Render data to view maybe using jquery etc
  },
  error: function(data) {
    //Notify user of error
  }
});

Hope this helps man

Asp.Net load data by button click


Converter CSV para xlsx, em vba

Question: Estou a utilizar este código para converter de CSV para XLSX. Mas está ignorando o OtherChar:=";" e separando as colunas na vírgula.

Dim xlApp As Object 'Excel.Application
 Dim xlBook As Object 'Excel.Workbook
 Dim xlSht As Object 'Excel.Worksheet

 Set xlApp = CreateObject("Excel.Application")

 '################### teste de conversão de tipo de ficheiro cvs to xlsx

 Set objExcel = CreateObject("Excel.Application")
  objExcel.Visible = False
  objExcel.DisplayAlerts = False

Set objWorkbook = objExcel.Workbooks.Open(TextBox1.text)
Set objWorksheet1 = objWorkbook.Worksheets("E60POR03")
objWorksheet1.Columns("$A:$A").TextToColumns destination:=objWorksheet1.Range("A1"), dataType:=1, _
        TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=True, OtherChar:=";", _
        FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), _
            Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1) _
            , Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array( _
            19, 1), Array(20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1)), _
            TrailingMinusNumbers:=True

        'FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), Array(27, 1), Array(28, 1), Array(29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array(33, 1), Array(34, 1), Array(35, 1), Array(36, 1)), _

'Save Spreadsheet, 51 = Excel 2007-2010
 objExcel.ActiveWorkbook.SaveAs FileName:=Left(TextBox1.text, InStrRev(TextBox1.text, ".") - 1), FileFormat:=51

' objExcel.Workbooks.Close
 objExcel.Quit

 Set objExcel = Nothing
 Set objWorkbook = Nothing
 Set objWorksheet1 = Nothing

Answer: A resposta está no seu próprio código. Repare na seguinte linha onde você instrui o que o Excel tem que considerar e desconsiderar:
TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=True, OtherChar:=";",

Você está dizendo para ele ignorar o ponto e vírgula no atributo Semicolon com o False e dizendo para ele usar a vírgula no atributo Comma setado em True. Basta alterar isto e remover os campos Other e OtherChar.
Fica assim:
Dim xlApp As Object 'Excel.Application
Dim xlBook As Object 'Excel.Workbook
Dim xlSht As Object 'Excel.Worksheet

Set xlApp = CreateObject("Excel.Application")

'################### teste de conversão de tipo de ficheiro cvs to xlsx

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False

Set objWorkbook = objExcel.Workbooks.Open(TextBox1.text)
Set objWorksheet1 = objWorkbook.Worksheets("E60POR03")
objWorksheet1.Columns("$A:$A").TextToColumns destination:=objWorksheet1.Range("A1"), dataType:=1, _
TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), _
Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1) _
, Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array( _
19, 1), Array(20, 1), Array(21, 1), Array(22, 1), Array(23, 1), Array(24, 1)), _
TrailingMinusNumbers:=True

'Save Spreadsheet, 51 = Excel 2007-2010
objExcel.ActiveWorkbook.SaveAs FileName:=Left(TextBox1.text, InStrRev(TextBox1.text, ".") - 1), FileFormat:=51

' objExcel.Workbooks.Close
objExcel.Quit

Set objExcel = Nothing
Set objWorkbook = Nothing
Set objWorksheet1 = Nothing

Converter CSV para xlsx, em vba


AutoSuggest in Android from jsonencoded array of php

Question: I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
 try {
        String temp=sName.replace(" ", "%20");
        URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
        URLConnection jc = js.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
        String line = reader.readLine();
        JSONObject jsonResponse = new JSONObject(line);
        JSONArray jsonArray = jsonResponse.getJSONArray("results");
        for(int i = 0; i < jsonResponse.length(); i++){
            JSONObject r = jsonArray.getJSONObject(i);
            ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
        }
}

Answer: As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);

Try changing that to:
JSONArray jsonResponse = new JSONArray(line);

Answer: You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);


Java source code dependency graph

Question: Well, first of all, this could potentially be stupid and crazy.
I am trying to build (or use, if there already exists one) a framework, which takes in a number of Java source files and outputs the way these files interact; for example, file1.java could import file2.java; file2.java could call a static method from file3.java. It would ideally be great, if this could be done without compiling or running the set of files. I am aware of the Reflection API that allows me to explore the parts of a class, but is that what I am looking for?
Also, how hard is this to extend to other languages, for example, Python, or Lisp (add any other language here)?
I was not really sure how to construct the question title, so if something like this has been asked before, I'd be glad if you could link me to that question.
Comment: Technically, you don't import files - the import is simply used by the compiler to resolve fully qualified class names when non-fully qualified class names are used.
Comment: Via reflection, you can look at the fields in a class, the arguments and return types of the methods -- but reflection won't tell you anything about classes that are used *within* a method.
Comment: Check out the source of OpenJDK? I think you are doing something that the compiler is doing already.
Comment: There should be a variety of UML tools which can do close to this.  They would show which Objects are related, not files, but Java has a pretty close coupling between the two so the UML dependency chart will get you close.
Comment: @GregKopff Yes, I had the same limitation of reflection in mind.
Comment: @nhahtdh sure, that's pretty valid, but how feasible?
Comment: @Thomas Right, I'll have a look at those. But for other languages?
Answer: i am currently working on a project , the main function is very similar to what you mentioned , and i use the javaparser : http://code.google.com/p/javaparser/
javaparser is very powerful , it can help us a lot in source code analysis , but it is very hard to get the full dependencies and classes interactions even if i use javaparser.
For example:
if you want to get all the dependencies of a class , the most directly approach is to get the "import" area of the source code - this is very easy by using javaparser.
But only the "import" is not enough , if the class - ClassA - you are currently analyzing called a class - ClassB - which is in the same package with ClassA , then ClassB will not appears in the import area .
So in this situation , we can not get the ClassB dependency.
And for the interactive of classes , if you can not 100% get the right dependencies of a class , then you can not 100% know the right interactive between classes.
But anyway , up to now, the javaparser is the most powerful and useful java source code analyze tool i can find .
Comment: OK, i would suggest to use : ANTLR (http://www.antlr.org/) this time. ANTLR is the best solution for programming language parse and process.
Answer: You have asked two questions and I will try to address the first one. I believe you are doing some kind of source analysis of java files to see how they could interact with each other (at least that's what I understood) So basically to do this you have to act a bit like the Eclipse IDE. Scanning the source code in each .java file and constructing data structures of java reserved words and constructs. Once each .java file has been analyzed you can then proceed to discover the links between them.
ex.

Store the package name of the class and its name and its scope
Store a HashMap of all declared variables, their values and their scope
Discover the methods in the source file and store their names, in + out parameters and scope

You can do a lot more too and to detect these constructs you'd have to write your own (or find something on the net) parser and use regular expressions to detect these. You store them in your program and then once all source files are analyzed, you can begin to see the interactions.
ex.
Source file 1 is in package x.y and has 3 public methods and 2 package scope methods.
Source file 2 is in package z and has 1 public method and 3 private methods.
So you can conclude that file 1 can interact with file 2 by invoking that 1 public method. And you can do the same analysis for all the files.
Comment: This sounds interesting, but I'm not sure how feasible it is. I'll probably wait for more answers.
Comment: It is 100% feasible, we learn this stuff in university. Usually course goes by the name of "compiler construction." You're basically looking at coding a parser and analyzing the source code and mapping every single portion of it. Then you just find the connection between the mappings based on rules. and those rules are defined in the JVM specs.
Comment: If there is time I could write you a sample program that does what I mentioned. Like something really basic as a proof of concept if you doubt the feasibility of what I am suggesting.
Answer: I know you said you'd rather not do the compile, but it would be far easier to look through the class files. Between the bytecode and the constants pool you can get everything you need without resorting to essentially rewriting javac. Use Apache BCEL and you're mostly there. Obviously no tool will be able to find dependencies accessed through reflection; for that you'd need to do runtime analysis with a custom classloader or something.
https://en.wikipedia.org/wiki/Java_class_file
http://commons.apache.org/proper/commons-bcel/
Comment: It might be easier, but it would also be wrong. javac inlines constants across source files, meaning that you can have A.java depending on B.java, but A.class with no references to B.class.
Answer: For someone coming across this question in 2023 or later, seems like this work was done by Patrick Beuks and Darius Sas as their Bachelor thesis , and the code open sourced. While it is usually preferable to have standalone answers in Stackoverflow, there's no way to do that here without copy-pasting the thesis or the code, which makes no sense and would be unethical.
Edit:
I attempted to use the software, but it requires building from source, and makes childish assumptions that fail the build. Thus, like many academic projects, this one too fails to work without a lot of time and effort invested by the user.
You wanted to scan source code, but there's a popular open source software that can scan class files.
https://github.com/classgraph/classgraph

Java source code dependency graph


How to catch exception on RollBack

Question: What is the best way to implement error handling for a SqlTransaction RollBack that already exists within a catch clause? My code is roughly like this:
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {
  objSqlConn.Open();

  using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {
    try {
      // code
      // more code
      // and more code
    }
    catch (Exception ex) {
      // What happens if RollBack() has an exception?
      objSqlTrans.Rollback();
      throw ex;
    }
  }
}

I believe that my application had an exception in the try block, which in turn was caught in the catch block and then the RollBack was attempted. However, the error that I'm seeing says something about a SqlTransaction.ZombieCheck(), which is making me wonder if the RollBack() itself threw an exception as well. So, do I need to implement some type of error handling at the RollBack()? How do I do that and manage to hold on to the exception that put the execution into the catch block in the first place?
EDIT - All of my code:
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {

    objSqlConn.Open();

    // Begin Transaction
    using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {

        try {
            // Create file in db (which in turn creates it on disk according to where the
            // ...FileStream points)
            SqlCommand objSqlCmd = new SqlCommand("usp_FileAdd", objSqlConn, objSqlTrans);
            objSqlCmd.CommandType = CommandType.StoredProcedure;

            // Sql parameter - report name
            SqlParameter objSqlParam1 = new SqlParameter("@ObjectID", SqlDbType.Int);
            objSqlParam1.Value = objID;

            // Sql out parameter - returns the file path
            SqlParameter objSqlParamOutput = new SqlParameter("@filepath", SqlDbType.VarChar, -1);
            objSqlParamOutput.Direction = ParameterDirection.Output;

            // Add Sql parameters to command obj
            objSqlCmd.Parameters.Add(objSqlParam1);
            objSqlCmd.Parameters.Add(objSqlParamOutput);

            // Execute command object
            objSqlCmd.ExecuteNonQuery();

            // Path to the FileStream
            string path = objSqlCmd.Parameters["@filepath"].Value.ToString();

            // Reset command object to get FileStream
            objSqlCmd = new SqlCommand(
                "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()",
                objSqlConn,
                objSqlTrans);

            // Execute command object
            Object obj = objSqlCmd.ExecuteScalar();

            if (obj != DBNull.Value) {
                // Byte array representing the FileStream
                byte[] fsBytes = (byte[])obj;

                SqlFileStream sqlFS = new SqlFileStream(path, fsBytes, FileAccess.Write);

                using (FileStream fs = fi.OpenRead()) {
                    //byte[] b = new byte[1024];
                    byte[] b = new byte[4096];
                    int read;

                    fs.Seek(0, SeekOrigin.Begin);

                    while ((read = fs.Read(b, 0, b.Length)) > 0) {
                        sqlFS.Write(b, 0, read);
                    }
                }

                sqlFS.Close();
            }

            // Commit the transaction
            objSqlTrans.Commit();
        }
        catch (Exception ex) {
            objSqlTrans.Rollback();
            throw ex;
        }
    }
}

Answer: This fragment should read like so:
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {
 objSqlConn.Open();

 using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {
   try {
     // code
     // more code
     // and more code
   }
   catch (Exception ex) {
     // What happens if RollBack() has an exception?
     try {
        objSqlTrans.Rollback();
     } catch (Exception ex2) {
        /* can't roll back -- db gone? db will do it for us since we didn't commit. */
     }
     throw;
   }
 }
}

EDIT: Come to think of it there's no need for the whole try/catch at all in this particular case as closing a connection with an uncommitted transaction rolls back the transaction, so the block can look like this:
using (SqlConnection objSqlConn = new SqlConnection(connStr)) {
 objSqlConn.Open();

 using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction()) {
  // code
  // more code
  // and more code
 }
}

Comment: I think you missed the catch keyword in that 2nd try block. One thing that I'm confused about - if Rollback() works just fine and doesn't have an error, then I'll never actually get to see the original exception since the throw only exists in the 2nd catch block, right?
Comment: Fixed newlines to make it obvious the throw is at the end of the first catch block.
Answer: You've already got
using (SqlTransaction objSqlTrans = objSqlConn.BeginTransaction())

This will cause the Transaction to be rolled back when it the using block ends if it hasn't been commited.
So I would remove the catch block entirely.
As for what happens when the rollback fails I would start by recognizing this as a very bad situation to be in and follow Eric Lippert's advice on a similar problem. here
Comment: I think you may have nailed it. I found another question on SO that dealt with using blocks for SqlTransaction, and I noticed that within their example they don't use the Rollback either. I don't think my question is a duplicate of that one though. http://stackoverflow.com/questions/1127830/why-use-a-using-statement-with-a-sqltransaction
Comment: ok the rollback will attempt without the explicit, but will it preserve the inner exception instead of throwing an exception that doesn't have the more likely cause?
Comment: @Maslow what's in the exception won't be affected by the using statement. So if there's an inner exception provided by the SqlCommand.ExecuteScalar it will be preserved.

How to catch exception on RollBack


Track user-id in button click - google analytics

Question: I would like to track a button click event on my wordpress site. But i want the info in such a way that how many clicks were made by a particular user. Can i pass user-id from my website and get the number of clicks for the user-ids?
Comment: Where are you getting the user-id from? Do you require your users to be logged in on your wordpress site?
Comment: yes the users will be logged in.
Answer: I'd split this out into two areas: (1) tracking the button click, and (2) collecting data by user. For tracking the button click, I would recommend Event Tracking. For collecting data by user, I would recommend passing in a non personally identifiable user ID as a user-scoped custom dimension. Then, you'll be able to create a flat table custom report with your custom dimension and event category as dimensions, and total events as a metric. Then you can see events per user.
One additional note here, you might want to explore using the User ID feature, which allows you to measure logged in users across browsers and devices. But even if you use the User ID feature, you'll still need to use custom dimensions to see data by User ID.
Comment: Hi is there any example coding implementation for this?
Comment: Do i need universal analytics to implement custom dimensions and metric?
Comment: You will need Universal Analytics (UA) for custom dimensions and metrics, but if you are not using UA you can use a custom variable instead. [example code for custom variables](https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables) and [custom dimensions](https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets)
Comment: Thank you. But i  have used event tracking code to achieve the result. I have answered above.
Answer: I have find a solution for this. I have used event tracking to achieve this. I have used the following function in the click event of the button.
_gaq.push(['_trackEvent','button-category','Click','Clicked by the user:User id from my site']);
In the label field i pass the user id from my site. Now, i can see the clicks of a particular user using his id under Behavior->Events->Pages->Your Page->Event Category->Event Action->Event Label. As username is personally identifiable info according to google, i didn't use username.
Comment: You are just passing this value as label. Is there any other way if we didn't pass this value in label but initialised the google analytics object with userid


Solving $\cos(x)\cos(2x) = \cos(3x)$

Question: Are there specific trigonometric identities that I can use to solve the following problem:
\begin{align*}
\cos(x)\cos(2x) = \cos(3x)
\end{align*}
Answer: HINT
\begin{align*}
\cos(3x) = \cos(x + 2x) = \cos(x)\cos(2x) - \sin(x)\sin(2x)
\end{align*}
Comment: Thanks. Then, I just get -sin(_x_) sin(_2x_) = 0. Can you help me solve the problem from there?
Comment: Sure. Just remember that
\begin{align*}
\sin(\alpha) = 0 \Longleftrightarrow \alpha = k\pi
\end{align*}
where $k\in\textbf{Z}$, then solve for $x$ and $2x$.
Comment: If you think I deserve it, give me an upvote.
Answer: Hint:
$$\cos(\alpha)\cos(\beta)=\frac{1}{2}[\cos(\alpha+\beta)+\cos(\alpha-\beta)]$$
Apply that result to the LHS, as well as rewrite $\cos(3x)$ as $\cos(2x+x)$ and apply the above result.

Solving $\cos(x)\cos(2x) = \cos(3x)$


Drupal 7 drill down menu with Checkboxes - Similar to Amazons left menu

Question: I'm new to drupal, so I'm looking for any suggestions as I am learning here.
I'm working on a site where I have a taxonomy setup like so:
Top Vocabulary:
Events
Sub Vocab that would have check boxes:
[] New Events
[] Past Events
Category of Events
[] Webinars
[] Conferences
[] Workshops
Topics of Events ()
[] Topic 1
[] Topic 2
[] Topic 3
When you check one of the checkboxes it just narrows down what shows in the content area.
Similar to Amazon's menu here:

After I setup the taxonomy, how do I create a menu like this?
Answer: I have found the term I am looking for here... it's called Faceted Search. There is a module for Drupal 7 here: http://drupal.org/project/facetapi
There is also a good writeup on best practices here: http://www.uxmatters.com/mt/archives/2009/09/best-practices-for-designing-faceted-search-filters.php
There is also another post here on StackOverflow: Does anyone know of a faceted search solution for Drupal 7?
A couple good resources I have found for Drupal 7 Faceted Search:

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/
http://php.dzone.com/videos/video-walkthrough-faceted
http://drupal.org/project/search_api/
http://www.webbydude.com/posts/10-drupal-faceted-search-tutorial
http://nickveenhof.be/blog/screencast-2-creating-facets-apache-solr-drupal-7

I hope this helps someone looking for such a thing as Faceted Search.


What are the values of x?

Question: I want to know what values of x are so that $(-2)^x = 4$
If this equation is true, why $\log_{-2}{4}$ is undefined in $\mathbb{R}$?
Comment: Check this out:http://math.stackexchange.com/questions/690024/why-must-the-base-of-a-logarithm-be-a-positive-real-number-not-equal-to-1
Answer: Multiply by $-1$ the left term and take logarithms:
$\log_{2}(2^x) = \log_{2}(4) \Rightarrow x\log_{2}(2) = 2$
$x = 2$
Answer: $\log_{-2}4=\frac{\ln4}{\ln(-2)}$, which leaves you with $\ln(-2)$, which is undefined in the real numbers.
Comment: but if we use the definition that $(-2)^x=4$, I think that x would be 2. In that case, it's defined.
Answer: Consider the following:
Let $x=log_{-3}(27)$. Then, by definition $(-3)^x = 27$. This, however would lead to a contradiction, since $(-3)^3 = -27$. In that case, our function would not have a solution, which means it is not defined for the basis $-3$. Just because it works out for some special cases does not make it well defined.

What are the values of x?


nhibernate mapping does not save/insert keys of inserted subclasses

Question: After having changed around my mappings a bit (
see my other question about cascade-delete for reasons) , i tried inserting a completely new object and all its subclasses.
After this another problem emerged, an issue with the insertion of the keys into the database. Situation is as follows:
I have an object with 2 tiers of subclasses, both a collection.
lets call the object Parent, this one has a collection of childs, and every enitity in this collection has its own collection of enitities. Which are mapped as follows.
Parent's mapping of its <set>

<set name="Collection"
     table="Table"
     cascade="all-delete-orphan"
     batch-size="15"
     inverse="true">
  <key column="ParentID"/>
  <one-to-many class="CollectionObject,CollectionObject-ns"/>
</set

CollectionObject's Mapping
<id name="ID" column="ID">
  <generator class="native"/>
</id>

<property name="ParentID" column="ParentID" not-null="true"/>

<set name="Collection"
     table="Table"
     cascade="all-delete-orphan"
     inverse="true"
     batch-size="15">
  <key column="ChildID"/>
  <one-to-many class="CollectionObject,CollectionObject-ns"/>
</set>

The mapping mapping of the object in the 2nd collection is similar tot he above.
The envisioned scenario would be, I save Parent, this would trigger the save of subclasses/collections.
e.g. I have Parent with ID = 1, Parent is filled with 1 collection, and this collection has 1 collection of its own.
So I save Parent, parent gets an ID from database (native sql identity). Now the first collection should get its ParentID property filled with the ID the Parent just got from the database. And the collection of the collection should get its ChildID filled with the ID the Child got from the database in the same way as Parent got his ID.
What happens now is (I checked created SQL in NHProf) Everything gets inserted, with its own ID, But the collections do not get their keycolumn filled with the ID of their parentclass. (instead it just gets 0 inserted)
So my question boils down to, what did i forget to add to my mapping which causes the to happen? Does the key column not do what i think it should do?
If i forget to add anything here, please say so. I will gladly give additional information.
update
I think the problem might have to do with the childs not having a <many-to-one> tag. So i tried to add one of those to the first child mapping. I came up with this
   <many-to-one name="ParentID"
             class="Parent,Parent-ns"
             column="ParentID"
             not-null="true"/>

However, this setup gives me the following error.
Exception occurred getter of Parent.ParentID
with InnerException
{"Object does not match target type."}
Sadly, This error does not give me any ideas of where to continue.
Answer: I think it would be helpful if you could show us your classes as well.  Have you checked that your Parent class really has a ParentID property of the type Parent, also I assume you have now removed the
<property name="ParentID" column="ParentID" not-null="true"/>

from your mapping and replaced it with the many-to-one?  Finally if you want your child objects to have collections of child objects then the child object will also need a many-to-one
<many-to-one name="CollectionObjectParent"
             class="CollectionObject,CollectionObject-ns"
             column="ChildID"
             not-null="true"/>

Comment: Hey Gareth,

Im not sure if I understand you completely. Parent should have a property named ParentID of its own type?

like Parent ParentID {get; set;}

At the moment ParentID is just an integer, im confused now :)
Comment: Rather than adding a reference to the DocumentID you need to reference the actual parent object Document.  See the link for info on how to handle parent child situations - hope it helps http://www.nhforge.org/doc/nh/en/index.html#example-parentchild
Comment: I've read trough the documentation close to 20x but I'm still missing something im affraid. I posted a workaround below, and it has to do for the moment, but still open for suggestions. Currently i'm watching the http://www.summerofnhibernate.com/ sessions. in the hope it get a little bit more clear for me.
Answer: Sadly, after playing around with mappings and reading trough half the internet, I have not been able to solve this.
The problem lies in the fact that i cant get to the scenario that <Document> gets his key from the database <generator class="native"/> and after this Inserts this key into the foreignkey properties of its underlying classes, inside just one session.Save() call.
e.g. for scenario i'd like session.Save(document)
-- * new document detected
-- * get new identity
-- * document has subclass with a foreignkey to it!
-- * insert idenity into the specified foreignkey properties (guess here lies the problem)
and repeat this with all underlying classes.
I did however come up with a workaround (most ugly code ever, but it gets the job done) Im not really into sharing code this crappy, but it just might help people reading here.
I have not yet given up on solving this the right way, but for the moment this has to do. Stil open for a nudge in the better direction.
incoming crap code!
    public void InsertDocument(Document document)
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                 try
                 {
                    IDocument document2 = new Document();
                    document2.Bodyregels = document.Bodyregels;
                    //for making the query a little neater
                    document.Bodyregels = null;

                    //lets get the elusive identity
                    session.Save(document);
                    session.Flush();

                    //reattach subclass and enter the id explicitly
                    document.Bodyregels = document2.Bodyregels;
                    foreach (DocumentBodyregel dbr in document.Bodyregels)
                    {
                        dbr.DocumentID = document.DocumentID;
                    }

                    //save it again, now with filled FK
                    session.Save(document);
                    session.Flush();

                    //now save the final subclass with FK's
                    foreach (DocumentBodyregel dbr in document.Bodyregels)
                    {
                        foreach (DocumentBodyregelWaarde dbrw in dbr.Waardes)
                        {
                            dbrw.RegelID = dbr.ID;
                            dbrw.DocumentID = document.DocumentID;
                        }
                    }

                    //and save the entire thing again (now with FK's)
                    session.Save(document);
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }
            }
        }
    }


Yamaha Bass keys accompaniment in Ableton live

Question: My piano teacher was telling me that when he turns on the accompaniment and when you are playing chords, when you hold the previous black key you get the minor chord for that. Example if i wanted to play the Eminor i hold E and d# to get the chord. How can i set it up in ableton live. I know it should be one of the midi effects, but i do not know which one. This happens in yamaha keyboards.
Thanks
Answer: The Yamaha 'ABC' method is proprietary [& iirc patented] system, so you won't find exactly the same algorithms used in other devices or software.
The method you are referring to is the 'easy-play' version of ABC. It uses a different, much simpler but less musically-accurate shorthand to play a much smaller selection of chord types [only major/mnior, 7th, iirc]. It really isn't a system you ought to use to learn how to play, it's more for 'fun.
The 'full' version of ABC requires you to state the chord you wish quite clearly; giving the system a root, 3rd, 5th + any flavour notes, before it will follow you accurately.
For instance,
if you press just C it will play Unison... nothing but C's
if you add an E above it will play C Major
adding an A above, it would assume A minor, even though C is the lowest note
so to get C6 you would need to add G as well.
Source: I used to actually program those built-in styles for a living, long time ago ;)
Comment: Could you elaborate on your third para..? Are you also telling that there is nothing like that in ableton and i have to make a device using max for live or something.?
Comment: I've added an example to the answer, & yes, afaik, you'd need to make something yourself to do that type of input. It might have a version of the 'full' ABC built-in, but less likely the simplified one.


transfer to live agent

Question: I'm working on chatbot development in C# on MS Bot framework.
I need to connect to Live agent when intent is none for particular conversation.
Please let me know the steps to connect to Live agent when bot unable to answer.
Answer: Here you can find sample code on how to potentially accomplish this: https://github.com/microsoft/BotBuilder-Samples/tree/master/experimental/handoff-library/csharp_dotnetcore/samples.
If you want out of the box functionality and want to stick with Microsoft technology I suggest you take a look at Power Virtual Agents which has handover available.
PVA can make use of Bot Framework Skills.

transfer to live agent


profile.d script permission denied

Question: I'm trying to disable ACPI wake on usb in Ubuntu 20.04
So I created a script in /etc/profile.d
-rwxr-xr-x   1 root root   110 May 18 00:23 disable-usb-wake.sh
#!/bin/sh -e
if cat /proc/acpi/wakeup | egrep 'XHC.*enabled'; then
    echo "XHC" > /proc/acpi/wakeup
fi

When I start my machine it says permission denied. Why?
Comment: IIRC `/etc/profile.d` scripts are run when a user logs in (more specifically, when a login shell is started), as the user. Has your user permissions to write into `/proc/acpi/wakeup`?
Comment: I could not post here without making an attempt. i'm looking for guidance on how to achieve a simple end, in a paradigmatic way. What are other people doing to stop USB from waking their machines? I've tried setting this in rc.local. I didn't get an error, although neither was the value set. At least by the time I got to it. People accuse systemd of over-reaching. I don't mind, as long as users aren't expected to figure it all out though deductive inquiry.
Answer: As mentioned in the comments, /etc/profile.d is being run as the user logging in, so will not have sufficient permissions to modify system configuration. You could add a sudo command there, but that would just mean you'll need to type your password again when you log in - this would be annoying and will also not work if the logging in user is not a system admin. Also, it will not do its job if no one is logging in after boot.
There are a few options, including adding /etc/rc.local as you mentioned, which was one of the common ways to do this kind of custom "on-boot" jobs before SystemD made the whole /etc/rc* thing irrelevant.
But - if you already have /etc/rc.local set up with your script, you can just enable it in SystemD by:

Make sure /etc/rc.local is executable. For example by running chmod a+x /etc/rc.local. The SystemD compatibility mode will not work otherwise.
Allow the SystemD compatibility mode to be enabled by creating the file /etc/systemd/system/rc-local.service.d/enable.conf with the contents below.
Enable the SystemD compatibility by running sudo systemctl enable rc-local

/etc/systemd/system/rc-local.service.d/enable.conf :
[Install]
WantedBy=multi-user.target

Next time your system boot, SystemD will run your custom /etc/rc.local.
SystemD Alternatives

Make use of SystemD tmpfiles management system to have it write what you need during boot. This is my recommended solution.
See this AskUbuntu question for some people making SystemD services to do the same thing.
I believe you can write a udev rule that disables "power/wakeup" when it sees whatever the XHC is (I think its the onboard XHCI USB hub?), as documented here: https://www.kernel.org/doc/html/v4.13/driver-api/usb/power-management.html

profile.d script permission denied


FreeIPA (LDAP): Refuse auth for users with expired password

Question: I have a FreeIPA used mostly for LDAP-based authentication in many local web services. Unfortunately, LDAP authorizes users to login to 3-rd party applications even when user's password is expired (including first random password, that is already expired and was not yet changed).
Is there a way to configure a "policy" to refuse users with expired login everywhere but FreeIPA web interface, letting users only to change their expired password?
Regards,
Comment: FreeIPA uses the 389 Directory Server for LDAP implementation, which doesn't seem to have a password policy manager. Probably, not what you want, but if you know when the password expires, you can nullify the userpassword attribute (which I guess what 389 is using for authenticated binds) of the user's entry. After that, 389 will most likely return LDAP RC 48 to the application which was doing the authenticated bind on behalf of the user, preventing access to whatever the resource the user was trying to get to.
Answer: No, not at the moment. Please see related upstream ticket.
What you could do, when applicable, is to authenticate users via Kerberos which does not log in users when expired. More information about the FreeIPA and available Web Application modules are on the FreeIPA.org page Web App Authentication.


DrawableBottom Error in Android Sdk 17

Question: I have a Button in my activity's layout like this:
<Button
        android:id="@+id/button_before"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_gravity="center_vertical|start"
        android:background="@color/transparent"
        android:drawableBottom="@drawable/ic_navigate_before"
        android:textColor="@color/gray_2" />

It is ok when I run my app to a device with Android SDK >19 but when I run my app to a device with Android SDK <19 like 17, my activity unfortunately stopped and this error occurs:
11-16 08:57:41.042 3549-3549/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.app.SearchActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_navigate_before.xml from drawable resource ID #0x7f02007d
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1958)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
                                                 at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881)
                                                 at android.graphics.drawable.Drawable.createFromXml(Drawable.java:822)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1955)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)

When I remove this line from my layout XML activity runs ok in every device:

android:drawableBottom="@drawable/ic_navigate_before"

And ic_navigate_before is an XML file:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="@color/gray_2"
    android:pathData="M15.41,7.41L14,6l-6,6 6,6 1.41,-1.41L10.83,12z"/>
</vector>

Also, my app min SDK is 16.
What can I do to resolve this problem?
Answer: Hi refer this document for why the crash was occuring.
As it stated that 'You'll find directly referencing vector drawables outside of app:srcCompat will fail prior to Lollipop.'
As I Know,
We cant directly set vector drawable.
From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource()
Try below solution,
create new file drawable_navigate_before.xml file write down below code.
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/ic_navigate_before"/>
 </layer-list>

and now set this file as drawable in you layout file.
     android:drawableBottom="@drawable/drawable_navigate_before"

Comment: What is your answer exactly do?
Comment: this will fix your crash
Comment: It solved my problem, but I want to know why this crash occurred?
Comment: wait i am updating my answer with reason.
Answer: From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource(). see here.
you can get VectorDrawable to work as drawableLeft (etc.) but it depends on the Support Library version and it comes with a price.the best way to take this issue i found is, remove drawable bottom from xml and add drawable bottom programmatically.
navigateBefore.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, R.drawable. ic_navigate_before);

Comment: How can I verify my drawables resolution?
Comment: @behrooz.fard is ic_navigate_before drawable defined by a XML file as state drawable, shape drawable or png, jpg?
Comment: It is an XML file. I put it to my question now.
Comment: It is in question.
Comment: ```android:fillColor="@color/gray_2"``` change to android:fillColor="#929292". change to hexcode color. and let me know its working
Comment: if its not working.remove drawable bottom from xml and add drawable bottom programmatically

```navigateBefore.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, R.drawable. ic_navigate_before);```
Comment: Your first answer is not worked, but when I add drawable programmatically it is ok.

DrawableBottom Error in Android Sdk 17


Forge Viewer - How to access (or get render/fragment proxy of) cloned Meshes in scene?

Question: I have a problem with Forge Viewer when i add a cloned object to scene i can see it, but not select it or make any changes to it.
I have this pseudo-code.
// get first selected Mesh
let selected = Object.values(viewer.impl.selectionMeshes)[0];

// clone it
let clone = selected.clone();

// add it to scene
viewer.impl.scene.add(clone);

// update scene
viewer.impl.sceneUpdated(true);

Did i miss something? Or do i need to make cloned object a part of the model?
Answer: You can add custom meshes to Forge Viewer in various ways, for example:

as you did, by inserting three.js meshes into viewer.impl.scene or viewer.impl.sceneAfter
using the overlay manager
using the new scene builder extension

Note that the first two approaches are typically only used for "overlays", meaning that the meshes don't behave (interact with the viewer) in the same way as the actual loaded model. With the scene builder however the custom meshes can be hovered, selected, etc.
Comment: My bad. I was using old version of Forge Viewer. Now it works :-)
Comment: Yep, you'll need a newer version of the viewer :) Btw. we've got a blog post talking about the scene builder in more detail as well: https://forge.autodesk.com/blog/custom-models-forge-viewer.
Comment: Is Scene Builder extension downloadable somewhere?
My Forge Viewer is throwing an unregistered extension error.


How can I put image file on the left side and texts on the right side

Question: I want to be able to put an image on the left side and texts on the right side.
How can I do this? Also if the image is too big, how can I resize it?

.container {
  background: #34618c;
  border-radius: 25px;
}
h1 {
  font-family: consolas;
  border: 2px solid #73AD21;
  border-radius: 25px;
}
p {
  font-family: Consolas;
  border: 2px solid #73AD21;
  border-radius: 25px;
}

Hello

World

I get an image on the left side but I only want the border around the text not around the image as well.
Answer: There are many, many ways  you can achieve this. Too many to list all of them. I do however suggest using a framework like Bootstrap since this will help you in getting good and consistent results across your pages.
One of Bootstraps' many features is the Grid System, which aids in laying out your design.

Grid systems are used for creating page layouts through a series of rows and columns that house your content.

Basically, Bootstrap provides certain classes which lets you define "rows" and "columns" to your layout. Each row, should have a total column width equal to 12. This means that you can have only one column with a column-width of 12; 2 columns each with a column width of 6; 3 columns with 4 width and so on.
For your particular case, it looks like you want 2 columns for your row. One to put your image in and one for your container. Here's that layout:

  <-- column with "6" width
      //image goes here

  <-- column with "6" width
      //container goes here

What each
 does here is quite obvious from the class-names they have. Each col-md-6 is one of our 2 columns. The 6 means that it has 6/12 width (half the width). The md is a breakpoint for medium devices. Basically, if the device you're viewing this page on is classed as "medium sized" or larger, it will have 6 column-width - otherwise 12. You can see what this actually means by shrinking the window of your browser (demo). If you want the content to break sooner, replace md with lg (large); if you want the break to happen at even smaller devices use sm (small) or xs (extra-small).
The full code for your app can be found on this fiddle or in the demo below:

.my_container {
  position: relative;
  height: 200px;
}
.my_container div {
  background: #34618c;
  border-radius: 25px;
  top: 50%;
  position: absolute;
  transform: translateY(-50%);
  width: 100%;
  border: 2px solid #73AD21;
  border-radius: 25px;
  padding: 10px;
}
.my_container h1,
.my_container p {
  margin: 0;
  font-family: consolas;
}
.my_image {
  width: 100%;
  height: 200px;
  background-size: cover;
  background-position: 50%, 50%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

Hello

World

Again, do check the Bootstrap documentation and don't forget to include the library to your project. Good luck!
Comment: Thank you Chris,  how can I use my image from local here?   doesn't seem to work.
Comment: you just replace the url. Change from `` to ``
Comment: what did you put as the url?
Comment: c:\users\name\desktop\name.img
Comment: and where do you store your project/html files?
Comment: @Ninja, did you find a solution?
Comment: Hi, yes I did.  Used table for the image.  Thanks for your help Chris!
Answer:

img {
  width : 20%;
}

.container{
background: #34618c;
border-radius: 25px;
width : 80%;
float : right;
}
h1{
 font-family: consolas;
border: 2px solid #73AD21;
border-radius: 25px;

}
p{
font-family: Consolas;
border: 2px solid #73AD21;
border-radius: 25px;

}

Hello

World

Like this?
Comment: hi Earl, yes kind of but the border is around the image and the texts.  How can I just have the border around texts?
Comment: Or you can try to use position absolute. http://www.w3schools.com/cssref/pr_class_position.asp


Diferença entre os tipos de controle de acesso ACL e RBAC?

Question: Gostaria de saber a diferença entre esses dois tipos de controle de acesso ACL e RBAC.
Venho dando uma lida a respeito deles, e ando meio confuso para entendê-los.
As seguintes dúvidas sobre eles são:
1- Diferença (uma explicação direta por favor).
2- Qual utilizar?
3- Vantagens entre ambos.
Comment: Sua dúvida é normal e a resposta é simples. Procure a diferença de autorização e autenticação :)
Answer: Primeiro: pesquisei para dar uma resposta mais fundamentada e concluí que algumas pessoas discordam pelo menos dos detalhes do que é cada coisa, não é fácil achar uma definição formal, e isto é menos desejável, desde que o que use resolva bem o problema. Vou colocar minhas conclusões.
O Access Control List costuma ser um termo usado genericamente sem indicar a implementação disto. Mas algumas pessoas o confundem com o DAC (Discretionary Access Control) e acho que é isto que está perguntando. Vou responder a diferença entre o DAC (que chamou de ACL) e o RBAC (Role-Based Access Control).
Quem manda
Pra mim a principal diferença se dá em que tipo de recurso está se dando privilégio. O DAC costuma fazer isso objeto por objeto. Pode ser um arquivo, uma mensagem, uma entrada em um banco de dados genérico ou especializado, qualquer coisa individual. O RBAC costuma dar acesso a recursos mais gerais, a entidades genéricas que possuem vários objetos. Pode ser acessar páginas de documentos (mas não a página individual), clientes cadastrados, dispositivo, etc.
Em geral pode ter alguma granularidade do que pode fazer ali como criar, editar, apagar, ver, baixar, aprovar, etc. Alguns privilégios gerais só fazem sentido em um deles. Por exemplo se pode dar propriedade para alguém isso costuma ser interessante no DAC, mas não necessariamente no RBAC.
Onde está definido
Outro ponto importante é que o RBAC costuma ser definido em código ou se tiver alguma flexibilidade pode ser controlado por um administrador do sistema de forma geral. O DAC costuma ser controlado pelos donos dos objetos.
Em um sistema operacional costumamos ver um DAC e como o usuário daquela máquina costuma ser o administrador as duas se confundem. E de fato em alguns casos algumas implementações costumam ser híbridas, ou pelo menos emprestam características.
Quando o RBAC começa ficar mais dinâmico e menos codificado, quando vai podendo dar privilégio condicionalmente até mesmo por fórmulas complexas ele começa se transformar em Attribute-Based Access Control (ABAC).
Papel
O Role Based Access Control costuma ter 3 entidades:

Papel (role) - que indica uma função que pode ser exercida no sistema
Usuário - que está associado à uma pessoa que usa o sistema
Privilégio - que indica algo que pode ser feito no sistema (em geral existe uma associação com um recurso porque senão é só chamado de permissão), até porque a permissão é dada sempre para um recurso, então poder alterar um cliente é diferente de poder alterar um produto. Alterar é um privilégio genérico, e cliente e produto são recursos, então o privilégio não é único, existem dois, um para cada recurso. Alguns chamam de ação.

O papel é o foco desta modalidade.
No RBAC um novo privilégio é dado para o papel e todos os usuários que estão associados àquele papel ganham o privilégio. Assim como se adicionar um usuário você o associa à papéis e ele ganha os privilégios destes. E quando cria um novo papel diz quais privilégios ele terá e quem são os usuários que estão associados.
Fica bem mais fácil gerenciar desta forma. Mas nem tudo são flores porque tem casos que um usuário deve ter um privilégio específico que as pessoas de um papel não devem ter. A solução em um RBAC puro é criar um papel só para isso.
Em última análise você poderia ter tantos papéis quantos forem a combinação de privilégios possíveis, ou seja, poderia ter zilhões de papéis com alguns poucos privilégios existentes. Claro que isso seria em caso exagerado mas dá uma ideia que pode complicar.
Para fins de entendimento e comparação com o DAC pode-se considerar que o dono do recurso nesses casos é o administrador do sistema ou o desenvolvedor.
Feito corretamente é mais escalável.
Ele pode criar um paradoxo. Um papel pode ser restrito a uma ação, outro papel a uma outra. E ainda, uma pessoa tem o papel de atender o cliente, se ela que é a menos especializada e talvez menos confiável (muitas vezes até terceirizada) não deve ter o privilégio dos dois papéis anteriores para resolver tudo o cliente o precisa. Se não tiver esses privilégios o cliente precisa falar com várias pessoas para resolver seus problemas e vai xingar sua empresa, e se tiver, a restrição não faz sentido. Mas claro que isso é uma questão de organização.
ABAC
Algumas pessoas dizem que se tiver papéis não é ABAC, mas não sei, talvez só mude o nome porque usuário ou grupo podem ser considerados a mesma coisa. Tem tanta informação dissonante que fica complicado dar uma informação canônica. E não sei se é importante, importa é saber que existem vários mecanismos que podem ser usados e atender suas necessidades. Acho que alguém cria uma definição e depois outros começam usar algo parecido usando o mesmo termo, sabe Bombril ou Gilette? Então estritamente ABAC pode ter uma definição clara, mas as pessoas usam o termo para coisas parecidas.
O ABAC costuma considerar contextos. Então pode até um privilégio ser dado dependendo de onde a pessoa está acessando, o momento, se já aconteceu algo antes, ou qualquer parâmetro definido.
Alguns consideram o ABAC um framework (não necessariamente um software framework).
Dono
No DAC tem um dono específico do recurso individual que é quem pode dar o privilégio. O privilégio também pode ser mais granular.
Este não costuma ter o papel, então os privilégios são dados diretamente para os usuários. Mas alguns consideram um sistema híbrido que permite ter papéis (grosso modo, grupos, ainda que seja um conceito um pouco diferente) como se fossem usuários uma forma de DAC, desde que mantenha a característica de propriedade do recurso.
Aqui o foco é o recurso.
Híbrido
Justamente por isso é comum adotar um sistema híbrido onde adota-se o RBAC sempre e o DAC quando é muito necessário (infelizmente isso não é tão bem usado assim e começa virar bagunça). Inclusive a permissão de usar o DAC pode ser dada de acordo com o RBAC, o que diminui a possibilidade falhas na organização.
Algumas pessoas dizem que o ABAC é justamente uma forma híbrida. Alguns colocam outras características e tenta padronizar uma forma de fazer todo processo dando a chance de cada um ter suas necessidades próprias atendidas.
Outros pontos
Não é um requerimento claro, mas o RBAC costuma ter mais granularidade nos privilégios. O DAC costuma ter o direito de acesso e eventualmente escrever ou algo geral a mais. O RBAC costuma ter privilégios que só fazem sentido para um tipo de recurso, por exemplo pode dar desconto em um título a receber. Mas não vejo porque o DAC não possa ter isso, exceto pelo fato de ter granularidade dos dois lados criar um fardo bem grande para administrar. Alguns dirão que começa ser um ABAC.
Papéis costumam ter hierarquias, se é que podemos usar este nome. Então se um papel derivado ganha um privilégio o papel base dele ganha automaticamente, que é o inverso da hierarquia.
Vantagens de cada
Em geral o RBAC é melhor onde potencialmente tem muitos usuários, ou tem muita volatilidade de usuários, o que é a grande maioria dos casos, e o DAC adotado como medida de flexibilização. Usar somente o DAC costuma acontecer quando se sabe que terá bem poucos usuários em qualquer caso.
O RBAC obviamente é um pouco mais difícil de entender e operar para pequenos volumes. O conceito de usuário e privilégio é intuitivo por todos, o conceito de papel não é. E em muitos casos é um passo a mais a se fazer (é uma indireção na aplicação), traz vantagens, mas impõe um custo. Mas ter alguns papéis facilita o gerenciamento dando estabilidade e visão de quem pode o quê.
O DAC permite melhor controle de privacidade e pode não ser tão difícil de administrar se existirem papéis como complemento para o sistema de usuário e puder agrupar os recursos (alguns dirão que são só grupos e não papeis).
O melhor costuma ser o hibrido, mas em alguns casos para simplificar pode ter só o RBAC, desde que não precise de grande flexibilidade e os recursos sejam mais gerais e não objetos específicos, embora isso funcione também). O DAC costuma ser melhor em ambiente colaborativo com muitos recursos não estruturados (arquivos, fichas, mensagens, objetos específicos), mas ainda o RBAC em casos assim pode ser útil.
Você encontrará mais o RBAC ou ABAC em um ERP ou algo do gênero, e mais o DAC em um sistema operacional ou plataforma (uma rede social por exemplo).
Se você é um usuário ativo do SO faça um exercício: aqui usa um RBAC, um DAC ou um ABAC? Como é o Windows? Dica: não é tão simples.
Como o DAC costuma dar mais trabalho é comum as pessoas acabarem usando ele como um A/RBAC ou afrouxando o controle. Leve isso em consideração.
Parece que o RBAC é a solução para um ERP, mas pense em casos que uma divisão empresarial compete com outra ou tenha uma legislação que não deixa os dados de um produto específico serem acessados indevidamente porque tem acesso aos produtos como um todo. Ou um vendedor que não pode ver dados de clientes que não são dele. Ou ainda um funcionário ver o salário de outras pessoas que não são suas subordinadas. Não é tão simples identificar o que é melhor. Mas o híbrido costuma ser mais poderoso quando precisa.
Vi algumas pessoas falando que o R/ABAC funciona melhor com APIs, mas não vejo sequer a ligação. Pra mim API não é recurso, o que está atrás dela é que é, API é o meio de acesso mas não o acesso em si.
As formas específicas de implementar cada um é bem vasta, dá para usar bastante criatividade.
Conclusão
Como eu sempre digo, a necessidade concreta é que define qual usar. Entendendo os conceitos corretamente e sabendo analisar e definir bem o problema que tem pela sua frente é que permite escolher qual é o melhor. Dá para citar exemplos como o fiz acima para indicar um caminho, mas corre-se o risco de decidir de forma simplista e tentar encaixar seu caso como se fosse um desses exemplos e fazer igual.
Algo complexo não pode ser entendido como se fosse uma receita de bolo. Infelizmente as pessoas acreditam que isso é possível, por isso tem cada vez mais coisa ruim sendo desenvolvida.
Sempre é o comprometimento de quem usa que fará o controle ter sucesso. Ambos são difíceis de manter coerente ao longo do tempo.
Eu discordo de algumas conclusões que achei por aí, talvez por experiência diferente ou porque algumas delas foram tomadas no passado quando não se sabia lidar com certas situações, inclusive misturando auditoria com controle de acesso que são conceitos muito diferentes, ligados, mas independentes.
Coloquei no GitHub para referência futura.


Quando uma classe utilitária deve tornar-se uma dependência injetável?

Question: Muitas vezes, eu escrevo pequenas classes utilitárias para resolver algum problema menor no meu código. Por exemplo (vou utilizar Spring para DI):
@Service
class PessoaService {

    public PessoaResponse converter(Pessoa pessoa, Long valor1, Long valor2) {
        PessoaResponse pessoaResponse = new PessoaMapperUtil(pessoa).toResponse();
        Long resultado = valor1 + valor2;
        pessoaResponse.setResultado(resultado);
        return pessoaResponse;
    }

}

Meu PessoaMapperUtil é bem simples, ele apenas converte os dados da Pessoa para uma nova classe PessoaResponse, usando um mapper interno.
Contudo, digamos que o PessoaMapperUtil comece a ficar mais complexo porque o Pessoa começa a ficar maior, atrapalhando meus testes unitários do método converter, pois cada vez mais preciso incluir mais campos no Pessoa para que o PessoaMapperUtil funcione.
Ficando mais complexo, precisarei identificar o momento no qual vai valer a pena fazer o PessoaMapperUtil virar uma dependência e ser "mockável", ficando mais ou menos assim:
@Service
class PessoaService {

    private final PessoaMapperUtil mapper;

    @AutoWired
    PessoaService(PessoaMapperUtil mapper) { this.mapper = mapper; }

    public PessoaResponse converter(Pessoa pessoa, Long valor1, Long valor2) {
        PessoaResponse pessoaResponse = mapper.toResponse(pessoa);
        Long resultado = valor1 + valor2;
        pessoaResponse.setResultado(resultado);
        return pessoaResponse;
    }
}

Fazendo com que PessoaMapperUtil vire um componente (@Component), fica mais simples mocká-lo e a partir disto eu me preocuparia apenas com o restante do código.
Enfim, qual seria o sintoma no código no qual um utilitário deve virar uma dependência? Atualmente eu faço isto quando ele começa a atrapalhar os testes... É isto mesmo?
Comment: É difícil responder isso sem saber ao certo o que há dentro de `PessoaResponse` e `PessoaMapperUtil`. No link do meu comentário anterior, eu falo um pouco sobre modelo anêmico, e acho que é o seu caso aqui.
Comment: Eu votei positivo. Receber downvotes aleatórios sem justificativa é sempre muito chato, mas infelizmente não há o que fazer quando isso acontece.
Comment: [Pergunta relacionada](https://pt.stackoverflow.com/q/252765/132) (não é duplicata).
Comment: [Outra pergunta relacionada](https://pt.stackoverflow.com/q/276787/132) (também não é duplicata).
Comment: Qual o motivo do downvote?
Comment: @VictorStafusa, obrigado! Costumo fazer o mesmo, rs
Answer: A classe PessoaMapperUtil não representa um conceito de programação orientada a objetos!
Partindo de um modelo MVC, a classe Pessoa é a sua classe responsável por modelar as regras de negócio. Ou seja, está na camada Modelo.
A classe PessoaResponse seria algo que transporta dados do modelo para fora, em direção a camada de visão, e portanto é algo que está na camada do Controlador, juntamente com o PessoaService.
A classe PessoaMapperUtil tem como finalidade pegar algo da camada de modelo (Pessoa) e fabricar um objeto da camada controladora (PessoaResponse).
Como o modelo não deve conhecer o controlador (apenas o contrário é que vale), então a classe Pessoa não deve referenciar PessoaResponse ou PessoaMapperUtil. Até aqui tudo bem.
Entretanto, uma vez que PessoaResponsse e PessoaMapperUtil estão na mesma camada e no mesmo módulo/JAR/pacote/qualquer-coisa, então começamos a questionar se de fato deveriam ser separados.
Em geral, classes que tenham nomes terminando em Manager, Util, Handler, Helper não representam conceitos reais de programação orientada a objetos, sendo frequentemente:

Uma cassetada de métodos estáticos amontoados (não parece ser o seu caso).
Um objeto que tem vida curta e que é construído apenas para que um método seja chamado, separando alguma tarefa em duas etapas (a construção e a invocação do método em si) sem muitas razões para tal.
Alguma outra coisa com sérios problemas de coesão.

A sua classe PessoaMapperUtil parece ser o segundo caso. Você até instancia isso, mas é só para chamar o método toResponse() logo em seguida. Nesse caso, o melhor sseria dar um passo atrás e colocar um método estático:
public static PessoaResponse criar(Pessoa p) {
    // ...
}

Qual é o melhor lugar para se colocar esse método? Bem, ele é algo que está na camada do controlador e produz uma instância de PessoaResponse que já está nessa camada, logo isso deveria ser um método estático (ou um construtor) de PessoaResponse, e não uma classe a parte.
Voltando a classe PessoaService, vejamos o que ela faz:
public PessoaResponse converter(Pessoa pessoa, Long valor1, Long valor2) {
    // 1. Cria um objeto PessoaResponse.
    PessoaResponse pessoaResponse = new PessoaMapperUtil(pessoa).toResponse();
    Long resultado = valor1 + valor2;

    // 2. O objeto PessoaResponse foi criado incompleto!
    // Portanto, conserta ele chamando setters!
    pessoaResponse.setResultado(resultado);

    // 3. Agora sim, o PessoaResponse está completo e pode ser retornado.
    return pessoaResponse;
}

Ou seja, o PessoaMapperUtil(pessoa).toResponse() não cria o PessoaResponse pronto e esse tem que ser finalizado por fora. Ora, a responsabilidade de criar o PessoaResponse corretametente e completamente deveria estar na classe PessoaResponse (ou mesmo que fosse no PessoaMapperUtil), e portanto não deveria ser responsabilidade de PessoaService terminar esse serviço inacabado (veja mais sobre isso nessa outra resposta). A responsabilidade de PessoaService deveria ser apenas a de expor funcionalidades da aplicação ao Spring e nada mais que isso.
Ou seja, o ideal seria você ter isso na classe PessoaResponse:
public static PessoaResponse criar(Pessoa p, Long valor1, Long valor2) {
    Long resultado = valor1 + valor2;
    // ...
}

Com isso sua classe PessoaService fica assim:
@Service
class PessoaService {
    public PessoaResponse converter(Pessoa pessoa, Long valor1, Long valor2) {
        return PessoaResponse.criar(pessoa, valor1, valor2);
    }
}

Ok, mas e aí, como mockamos isso? Nesse caso caímos no que explanei nessa resposta aqui, não deveria fazer sentido mockar método estático. Nesse caso, se quisessemos mockar ele, a própria classe PessoaService testada não faria nenhum sentido. Ela não seria nada mais do que algo que retornaria de forma burra e cega, qualquer tranqueira que o mock lhe devolvesse sem olhar nada mais e nem fazer qualquer crítica ou verificação. Ou seja, ao mockar o método que ela chama, produziríamos um teste inócuo. O motivo é que o que tem que ser testado aqui é o método PessoaResponse.criar(Pessoa, Long, Long), para certificar-se que o PessoaResponse produzido está correto. A classe PessoaService se reduz a apenas uma forma muito verbosa de dizer ao Spring que o método criar(Pessoa, Long, Long) da classe PessoaResponse é uma funcionalidade exposta como serviço.
E para testar o método criar(Pessoa, Long, Long) da classe PessoaResponse? Simples, crie um objeto Pessoa (aqui pode ser um mock sem problemas), passe-o para esse método e faça um monte de assertXXXs no objeto retornado. Note que testar se o PessoaResponse retornado está certo, é muito mais fácil se ele for uma classe imutável - sem setters, com todos os campos final e sem quaisquer outras coisas que possam modificar uma instância após o construtor terminar de executar, ainda mais considerando que a finalidade para a qual a classe PessoaResponse existe é para transportar dados para outras partes da aplicação que devem estar desacopladas da origem dos mesmos. Adotar-se essa prática faz com que o problema de criar objetos incompletos seja sanado e impede que ele seja reintroduzido por descuido.
Assim sendo, para testar o método converter(Pessoa, Long, Long) da classe PessoaService é só fazer os mesmos testes que foram realizados com criar(Pessoa, Long, Long) da classe PessoaResponse, afinal de contas os dois devem ter exatamente o mesmo comportamento sem tirar e nem pôr nada.
Melhor ainda seria você conseguir convencer o Spring a usar o método criar(Pessoa, Long, Long) da classe PessoaResponse como serviço por meio de alguma anotação sem precisar da classe PessoaService, mas acho que isso daí já é algo que não dá para convencer o Spring a engolir (ao menos não facilmente). Com outros frameworks, pode ser que você consiga ou não.
Sei que isso pouco diz sobre o que acontece quando a complexidade da classe Pessoa começar a ficar grande demais, mas isso seria algo que ficaria na responsabilidade de PessoaResponse mapear. Entretanto, nesse caso, você teria que fornecer mais dados sobre a sua aplicação.
Bem, ainda há o caso de você realmente não querer de forma alguma colocar o método criar(Pessoa, Long, Long) na classe PessoaResponse (talvez porque as duas não devam se conhecer de forma nenhuma). Aí sim, nesse caso, você teria que colocar esse método numa classe a parte, mas isso tende a prejudicar a coesão e o encapsulamento de PessoaResponse.


Plumber R post on server dosen't work

Question: I'm building an Shiny-App with different API connections. It's all running on a server (CentOS Redhat).
I've got a problem with my API. If I'm running this on my terminal (Mac), everything works.
curl --data "InvestAmountInWei=2000000000000000000&Address=Test" "http://s*******aw.ch:8002/invest"

Same with the Postman-App. I can do a post there and all will be done perfectly. The post request should transfer the ammount and the adress (like an id) to my r-script which is running via plumber.
As sad, if I do this command through terminal or Postman it works. But I need to do this command with the webbrowser.
I used this link to test it:
http://s*********aw.ch:8002/invest?InvestAmountInWei=1000000000000000000&Address=Jennifer

and now I only get this error in my web browser: {"error":["404 - Resource Not Found"]}
If checkt the iptables as well and it should be fine.
# netstat -ntpl | grep 8002
tcp        0      0 16*.**.**.*6:8002           0.0.0.0:*                   LISTEN      28563/R

any ideas how I can solve this problem?
Answer: When you make a request to a URL in your browser, that's a GET request. If you setup your endpoint to support GET and POST requests at the same location, your browser and Postman requests should both work just fine.
If you want your browser to send a POST request, you'll either need to submit a form to it or use JavaScript.

Plumber R post on server dosen't work


How do you use the same glyph for multiple characters?

Question: I'm trying to create a tool font that will display latin letters and numbers but all other unicode code points will display an error character instead.
I can't leave the characters blank as for my use case this will result in the program falling back to a font that does have that character.
How do you use the same glyph for multiple characters?
Answer: Right click on the glyph > copy reference > paste into the new character
Now they are both linked and when you change the original it will change all the references.