How much overtension can I put on a guitar string before it snaps?

Question: In relation to this question
Which strings do I need to play these notes?
I have calculated that I will have to take the highest string upto 150% of the maximum stated Newtons (I have tried calculating D-addario pl007 to pl0095, they all need 150% overtension), and the next string needs 135% overtension.
(All the other strings are around 100% of maximum tension.)
Will this automatically break the strings, or can I buy the strings and see what happens?
Is there an alternative type of string that might handle higher Newtons per linear-mass?
Thank you.
Clarification: it isn't a guitar.  It looks ugly but it works.
Comment: Just asking to break not only strings but the instrument as well!  Why not search out the equivalent of a "soprano guitar" designed to produce the frequency range of interest?
Comment: @CarlWitthoft: You mean, a Ukulele?
Comment: @David  ;-)  Tiny Tim returns!
Comment: Hmmmm - with your picture edited in, I guess this is a home made instrument? If so, you'll probably be the one to decide whether it can cope with the tension!
Comment: It's quite strong enough, I just don't want to waste money on strings when I should redesign the sides instead.  I will recalculate string tensions to see what the new measurements will be.
Comment: Wow! That top beam where the machine heads are looks really thin, and is at right angles to the string tension. I'd be quite worried about that snapping. Also, the more flexible the frame, the more it will dissipate the energy of the strings and damp them. Good luck with your project! PS I would probably call that a harp. Have you ever seen a zither? it's another way to go with this.
Answer: As Carl said, you may need to rethink your plan. The strings may cope with that much overtension.
The neck of the guitar is quite likely to be catastrophically damaged! Bent, or possibly snapped.
Just use an instrument designed for the higher range, or possibly play much higher up the neck - this may sound sarcastic, but people do make 36 fret guitars, such as the R36 Turbulence from Gary Kramer guitars:
Comment: Not sure how well this translates to an electric guitar, but that far up the fingerboard (and past it) on an acoustic cello, I can get the notes to sound just by touching the string (as you'd normally do to get the harmonic).
Comment: Yep - natural harmonics work the same with guitar. And they can give a lovely tonal chime.
Comment: I think I will recalculate and see if I can make the strings shorter.
Comment: @DrMayhem a guitar neck is much strong than many realise, see  my answer here for a basic calculation showing a neck is over 18 times stronger than required:  http://physics.stackexchange.com/questions/94222/if-a-material-is-built-to-handle-tension-would-removing-the-tension-damage-it/94276#94276
Comment: @Fergus also, it's possible to get well over a semitone of pitch bend on a guitar without a tremolo by pushing or pulling on the neck. I saw Adam Bomb doing this in a small venue near where I live. I spoke to him about it and he said it doesn't harm the guitar. I had a little go on mine and it works, but I really don't want to make a habit of it on my precious instrument.
Comment: Fergus - maybe you'll trust that. I've seen both ends: I have dropped a guitar down a flight of stairs, landing on the headstock and had no damage or loss of tuning, and I have seen a catastrophically broken neck from one set of very heavy strings overtightened. I wouldn't trust that 18x to be consistent across instruments.
Comment: @DrMayhem Of course it is not consistent across instruments as not all instruments dimensions, materials and tensions etc are equal. eg if you double the tension the safety factor becomes 9, still large by any standard, the safety factor for aircraft can be less than 2...We do however, all 'trust that' methodology every day. It is the same method used to build the buildings you enter, the bridges you cross and the cars you drive. It's validity is long past being debatable. Your sample of one in a population of millions means nothing, there is a multitude of other reasons that the guitar broke.


Application Loader - Create new Package from File (different languages)

Question: Application loader supports the creation of inApp-Purchase items via an import template. I'd like to create a bunch of products with localized display name/description. The "Using Application Loader" doc says

Displayed Name @@language@@
  A user-visible display name (from 2 to 75 characters) where @@language@@ is a supported localized language. You can add a new column for each localized language display name.

I tried to use fr, de, zh-Hans for language adding additional columns but Application loader always displays the display name as for english. Has anyone got it working?
Answer: Use Simply the full Language without @@ or () i.e "Display Name Language"
e.g "Display Name French" And "Description French"
Comment: Not so easy... but how do I differentiate stuff like Portuguese Brazil and Portuguese Portugal or French France, French Canada, etc? Just putting French France or Portuguese Brazil is not working... Some times I think Apple hate developers. :(
Answer: The language which you add using the following methods can be visible to the user according to the iPad language set using this. You cannot edit the .itmsp without using Application Loader. Refer this
Comment: The question was how to use "New from file". If you have tenth of products to create it would drive you crazy if you had to add them as you showed.


hook_menu question

Question: What is "access content" used as access argument in the following code? I don't see it in Drupal permissions.
function hook_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

Answer: That permission comes from the node module (node_permission()). Definition is:
'access content' => array(
  'title' => t('View published content'),
),

So in the permissions UI you'll be looking for "View published content".

hook_menu question


Turn a data frame into a ts in R

Question: I want to turn a list data structure into a double data structure:
Starting list data from my CSV.
> my_data = read.csv("time series test.csv", header = TRUE)
> my_data
        Date    Value
1   1/1/2014 123.0000
2   1/2/2014 128.5693
3   1/3/2014 129.1474
4   1/4/2014 130.1361
5   1/5/2014 137.9758
6   1/6/2014 141.0548
7   1/7/2014 141.3517
8   1/8/2014 142.1449
9   1/9/2014 142.1479
10 1/10/2014 149.8912

Example double:
> nottem
      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
1920 40.6 40.8 44.4 46.7 54.1 58.5 57.7 56.4 54.3 50.5 42.9 39.8
1921 44.2 39.8 45.1 47.0 54.1 58.7 66.3 59.9 57.0 54.2 39.7 42.8
1922 37.5 38.7 39.5 42.1 55.7 57.8 56.8 54.3 54.3 47.1 41.8 41.7
1923 41.8 40.1 42.9 45.8 49.2 52.7 64.2 59.6 54.4 49.2 36.3 37.6
1924 39.3 37.5 38.3 45.5 53.2 57.7 60.8 58.2 56.4 49.8 44.4 43.6
1925 40.0 40.5 40.8 45.1 53.8 59.4 63.5 61.0 53.0 50.0 38.1 36.3
1926 39.2 43.4 43.4 48.9 50.6 56.8 62.5 62.0 57.5 46.7 41.6 39.8
1927 39.4 38.5 45.3 47.1 51.7 55.0 60.4 60.5 54.7 50.3 42.3 35.2
1928 40.8 41.1 42.8 47.3 50.9 56.4 62.2 60.5 55.4 50.2 43.0 37.3
1929 34.8 31.3 41.0 43.9 53.1 56.9 62.5 60.3 59.8 49.2 42.9 41.9
1930 41.6 37.1 41.2 46.9 51.2 60.4 60.1 61.6 57.0 50.9 43.0 38.8
1931 37.1 38.4 38.4 46.5 53.5 58.4 60.6 58.2 53.8 46.6 45.5 40.6
1932 42.4 38.4 40.3 44.6 50.9 57.0 62.1 63.5 56.3 47.3 43.6 41.8
1933 36.2 39.3 44.5 48.7 54.2 60.8 65.5 64.9 60.1 50.2 42.1 35.8
1934 39.4 38.2 40.4 46.9 53.4 59.6 66.5 60.4 59.2 51.2 42.8 45.8
1935 40.0 42.6 43.5 47.1 50.0 60.5 64.6 64.0 56.8 48.6 44.2 36.4
1936 37.3 35.0 44.0 43.9 52.7 58.6 60.0 61.1 58.1 49.6 41.6 41.3
1937 40.8 41.0 38.4 47.4 54.1 58.6 61.4 61.8 56.3 50.9 41.4 37.1
1938 42.1 41.2 47.3 46.6 52.4 59.0 59.6 60.4 57.0 50.7 47.8 39.2
1939 39.4 40.9 42.4 47.8 52.4 58.0 60.7 61.8 58.2 46.7 46.6 37.8

So how do I turn my_data into the same structure as nottem, so I can use it with STL()? plot(stl(nottem, "per"))
Comment: What is `class(nottem)`? It looks like it's a `ts` object. -- Ah, I see it's a build in dataset. and it is a `ts` object. Try using the `ts()` function to convert your data.frame to a time series object.
Comment: I tried coercion

`as.double(dat)
Error: (list) object cannot be coerced to type 'double'`
Comment: Thanks MrFlick, ts() works great :)
Answer: You can use the ts function. c(2014,1) is January 2014.
 myts <- ts(my_data[,2], start = c(2014,1), frequency = 12)

Comment: Thanks germcd, do you have a method that does not requiring hardcoding in dates? This should take arbitrary date data.
Comment: Sorry i read the dates as d/m/y. Try to aggregate the data by month
Comment: as.numeric and strftime could be used to get the year and month from the date

Turn a data frame into a ts in R


Retornar campo diferente do inserido na clausula GROUP BY

Question: Eu tenho a seguinte tabela:
| id | payment_id | user_id | device |
 ------------------------------------
  1  |     2     |     1   | active |
 ------------------------------------
  2  |     4     |     5   | not_active
 ------------------------------------
  3  |     8     |     1   | not_active
------------------------------------
  4  |    10     |     5   | active |
 ------------------------------------
  5  |    12     |     1   | active
 ------------------------------------
  6  |    14     |     1   | active
------------------------------------
  7  |    16     |     3   | active |
 ------------------------------------
  8  |    18     |     7   | active
 ------------------------------------
  9  |    20     |     7   | active
 ------------------------------------

Eu gostaria de fazer um query que retorna o payment_id apenas dos usuários que tem mais do que 2 device igual a active.
Pensei nisso:
SELECT payment_id
FROM table
GROUP BY user_id
HAVING count(device) > 2

Nesse caso eu retornaria os payment_ids 2, 12 e 14 o user_id igual a 1.
Alguém sabe como fazer isso ?
Answer: A query estava "quase pronta", faltou usar o WHERE para retornar apenas os registros com device='active'  e no HAVING contar mais de 2 ocorrências, mas isso não ia retornar o 2, 12 e 14, ia retornar também o 8.
Primeiro, é preciso fazer um query que retorne "todos os user_id, que tenham mais de dois device='active'", que seria algo assim:
 select user_id
   from teste
  where device='active'
  group by user_id
 having count(user_id) > 2;

Isso iria retornar o user_id=1. Mas nem todos os registros com o user_id=1 são active, para isso, vamos fazer uma outra query, que use essa anterior por base, e filtro somente device='active':
 select payment_id
   from teste
  where device='active'
    and user_id in (
     select user_id
       from teste
      where device='active'
      group by user_id
     having count(user_id) > 2)
  and device='active';

Pode ver funcinando aqui: http://sqlfiddle.com/#!9/58a17e/6
Comment: Muito obrigado pela sua ajuda Ricardo


running nginx as a reverse proxy with apache

Question: Q1) Do I need mod_deflate running on apache? does it help in performance in anyway?
Q2) Do I need mod_cache running on apache if nginx is serving a static caching proxy?
<code><IfModule mod_cache.c>
CacheEnable disk http://website.com/
CacheIgnoreNoLastMod On
CacheMaxExpire 86400
CacheLastModifiedFactor 0.1
CacheStoreNoStore Off
CacheStorePrivate On
<IfModule mod_disk_cache.c>
CacheDefaultExpire 3600
CacheDirLength 3
CacheDirLevels 2
CacheMaxFileSize 640000
CacheMinFileSize 1
CacheRoot /opt/apicache
</IfModule>
</IfModule>
</code>
Answer: You don't need to run mod_deflate on apache, use compression of nginx instead. Secondly you can use caching of nginx instead of mod_cache on apache.
You can read up using the link below to get a better idea of nginx caching.
How to set up Nginx as a caching reverse proxy?
Comment: but an off question... wouldn't mod_deflate/cache running increase the performance of content passed to nginx?
Answer: If Nginx was doing gzip compression on the client's incoming connection, I would guess that the overhead of compression in Apache just to get the response back to Nginx would outweigh, or at least cancel out any gain.


Corejava to print unique elements from two arryas

Question: I want  a core java program to find unique elements between two arrays.
Example:
Array1 - 9, 5,3,23,2,5
Array2 - 19, 5,3,23,24,53
output of unique elements from both of the array's should print as: 9, 2, 19, 24, 53
pls help me to write the program with accurate loops.
NOTE: Dont want to handle the same program using any of the collections and want to be done using only loops. Thanks
Comment: Are your numbers limited to be within a certain range? (i.e. 1-25)
Comment: tried with rotating from first array for every element from first array, checked with each element with second array elements. But I want the reverse also (like printing from second array as well)
Comment: yes durron, it is fixed but need to use minimal loops. thanks
Comment: Whats wrong with using collections for this, anyway?  You just use a Map to track the items and their count, and then spit out the keys with a matching value of 1.  Although there's probably a better collection than that, even...
Answer: You have to use at least 2 loops.
public void uniqueM(int arrayA[], int arrayB[]){
    boolean uniqueA = true, uniqueB = true;
    int high_size = arrayA.length, low_size = arrayB.length;

   if(arrayA.length < arrayB.length){
     low_size = arrayA.length;
     high_size = arrayB.length;
    }

    for(int i = 0; i < high_size; i++){
      for(int j = 0; j < low_size;j++)
      {
         if(i < arrayA.length && arrayA[i] == arrayB[j]) uniqueA = false;
         if(i < arrayB.length && arrayB[i] == arrayA[j]) uniqueB = false;
      }
       if(uniqueA && i < arrayA.length) System.out.println(arrayA[i]);
       if(uniqueB && i < arrayB.length) System.out.println(arrayB[i]);

       uniqueA = true;
       uniqueB = true;
    }
}

Answer: You need to tweak the size of the counter array and the offset variable based on what range your legal integers can fall in. But this doesn't use anything in the java.util API, only loops.
public static int[] uniques(int[] array1, int[] array2) {
    // assuming your integers are 0-53, you'd have to modify this if it's different
    int[] counter = new int[54];

    // offset needs to be changed based on if negative numbers are allowed
    int offset = 0;

    for(int i = 0; i < array1.length; i++) {
        counter[array1[i] + offset]++;
    }
    for(int i = 0; i < array2.length; i++) {
        counter[array2[i] + offset]++;
    }

    int numUniques = 0;
    for(int i = 0; i < counter.length; i++) {
        if(counter[i] == 1) numUniques++;
    }

    int[] uniqueArray = new int[numUniques];
    int index = 0;
    for(int i = 0; i < counter.length; i++) {
        if(counter[i] == 1) uniqueArray[index++] = i;
    }

    return uniqueArray;
}

Comment: Can you please explain me whats happening here? for(int i = 0; i < array1.length; i++) {
        counter[array1[i] + offset]++;
    }
    for(int i = 0; i < array2.length; i++) {
        counter[array2[i] + offset]++;
    }
Comment: I think I understand, for every element index it maintains counter. Thanks, this is a nice program
Comment: Yes, exactly, glad I could help


Java Case Insensitive Method Breakdown and Explanation

Question: public class StringMatchesCaseInsensitive
{
   public static void main(String[] args)
   {
      String stringToSearch = "Four score and seven years ago our fathers ...";

      // this won't work because the pattern is in upper-case
      System.out.println("Try 1: " + stringToSearch.matches(".*SEVEN.*"));

      // the magic (?i:X) syntax makes this search case-insensitive, so it returns true
      System.out.println("Try 2: " + stringToSearch.matches("(?i:.*SEVEN.*)"));
   }
}

The code block above is what it is; an example of a case-insensitive search. But what I'm most interested in is this : "?i:.*SEVEN.*";.
I know that ?:. is the case-insensitive syntax. But what about the .* that encapsulates SEVEN? What does it do?
Where can I read more about the ., *, and .* regex modifiers?
Thanks in advance
Answer: Following is what those symbols stand for.

. stands for any character except the newline. If used with s flag then it matches newline too.
* is quantifier which says zero or many.
.* will say zero or many characters.

You can read more about them on

Regular-Expressions.info
Tutorials Point


yum list installed including version of all installed packages CentOS 5.4

Question: I have a list of packages installed with yum on CentOS 5.4
[root@server ~]# yum list installed
...
Installed Packages
GConf2.x86_64             2.14.0-9.el5           installed
ImageMagick.x86_64        184.108.40.206-4.el5_1.1      installed
MAKEDEV.x86_64            3.23-1.2               installed
MySQL-python.x86_64       1.2.1-1                installed

I would like to download these rpms locally using
yumdownloader --resolve MySQL-python-1.2.1-1.x86_64 etc.
However the package formatting is different (MySQL-python.x86_64       1.2.1-1 vs MySQL-python-1.2.1-1.x86_64) so I am unable to download them using the above command.
I don't want to have to parse the output of yum list installed, and I also don't want to use the contents of /var/log/yum.log* as I'll have to account for erased packages and version discrepancies. However /var/log/yum.log* does have the formatting I require...
May 25 14:58:15 Installed: groff-184.108.40.206-11.1.x86_64
May 25 14:58:15 Installed: bzip2-1.0.3-4.el5_2.x86_64

Any suggestions?
Answer: You can use rpm to list the installed rpms and format the output:
rpm -qa --qf "%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n"


remove SQL duplicate values, distinct not working

Question: SELECT BM.PUser,
   BM.Desc, BM.Price,
   BM.Info,
   CAST (CASE
      WHEN BI.Closed = 'E' then BQ.Qty-BQ.Consign-(SUM(BD.QtySold))
      ELSE BQ.Qty-BQ.Consign
   END as int) as Stock
FROM BINVOICE BI
 , BDETAIL BD
 , BQTY BQ
 , BMASTER BM
WHERE (BD.User = BI.User)
   AND
  (BQ.PartNo = BD.PartNo)
   AND
  (BQ.PartNo = BM.PartNo)
   AND
  (BM.Price > 0.01)
   AND
  (BM.Active = 'Y')
GROUP BY BM.PUser, BM.Price,
     BM.Desc, BM.Info,
     BQ.Consign, BQ.Qty,
     BI.Closed

My issue is that I want only one of each PUser to display, but some of them appear multiple times.  I believe the CASE I have made is where they are coming from.  I am not quite sure how to get around this.  Using SELECT DISTINCT did not work for me.  Any guidance would be greatly appreciated.  It is used on NexusDB.
Comment: Show code with "distinct" select that you have tried
Comment: I it's only PUser you want "distinct", then that's the only column you should specify in the GROUP BY! (All other columns in the select list should be arguments to aggregate functions.)
Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**more than 20 years** ago) and its use is discouraged
Comment: i am using an old version of reportbuilder because that is what i have been supplied with.  it is basically requiring me to have everything in the group by and will not work if i take any of them out.  same thing goes for the way i have comma separated my tables.
Answer: Use Distinct
SELECT DISTINCT column_name,column_name
FROM table_name;
SELECT Distinct  BM.PUser,
   BM.Desc, BM.Price,
   BM.Info,
   CAST (CASE
      WHEN BI.Closed = 'E' then BQ.Qty-BQ.Consign-(SUM(BD.QtySold))
      ELSE BQ.Qty-BQ.Consign
   END as int) as Stock
FROM BINVOICE BI
 , BDETAIL BD
 , BQTY BQ
 , BMASTER BM
WHERE (BD.User = BI.User)
   AND
  (BQ.PartNo = BD.PartNo)
   AND
  (BQ.PartNo = BM.PartNo)
   AND
  (BM.Price > 0.01)
   AND
  (BM.Active = 'Y')
GROUP BY BM.PUser, BM.Price,
     BM.Desc, BM.Info,
     BQ.Consign, BQ.Qty,
     BI.Closed

Comment: @utility might have not been used properly


Why is $\mathbb{Z}/p^{m-n}\mathbb{Z} ≅ p^n\mathbb{Z}/p^m\mathbb{Z}$?

Question: Where $m \geq n$?
It's intuitive but I have no reason to justify the interchange.
Answer: If $d\mid n$ then the composition $\Bbb Z\xrightarrow{\times d} d\Bbb Z\to d\Bbb Z/n\Bbb Z$ has kernel $\frac{n}{d}\Bbb Z$ and is onto.
Answer: As a variation of Wacka's answer, consider the homomorphism \begin{align}\phi : p^n\Bbb Z &\to \Bbb Z/ p^{m-n}\Bbb Z
\\ p^nk &\longmapsto \overline k  \end{align}
It is surjective, and it has kernel $$\ker\phi=\{p^nk \mid k \equiv 0 \pmod{p^{m-n}}\},$$ but then $k \in \ker\phi \implies k=p^{m-n}j$ for some $j \in \Bbb Z$, so $p^nk=p^n(p^{m-n}j)=p^mj,$ meaning $\ker\phi \subseteq p^m\Bbb Z$.
Then $p^m\Bbb Z \subseteq \ker\phi$ because $p^mh=p^{m-n}(p^nh) \equiv 0 \pmod{p^{m-n}}$
(Then use the first isomorphism theorem.)


what does "out of range" mean?

Question: I have checked these statements with mysql  and no error will happen and also the out put will be 0 rows BUT my friend checked it and he found an error for SELECT becaouse it is out of range !! IS he correct? thanks
<code>CREATE TABLE T1(A INTEGER NULL);
SELECT * FROM T1;
</code>
Comment: Perhaps you should ask your friend to explain.
Answer: There is nothing wrong with those two lines.
"Out of range" normally means that some value is outside the expected range of valid values. For example if you have an array of length 2, trying to access position number 10 in that array could lead to an "array index out of range" error (depending on your programming language).
Answer: I don't immediately see anything wrong with it - but I haven't got an install of mysql handy at the moment to test with.

what does "out of range" mean?


Swift - tableView not reloading after adding to array

Question: I am having an issue updating my UITableView. I have an app that has a basic UIViewController with a with a navigationItem to "Add New" items to the UITableViewContioller. I can add the string and then dump the array to see if it has been added. The dump function shows the added item in the array but the UITableView does not, even after calling reloadData. Here is my code.

Here is the console dump after hitting save.

So you can see something is there after I save but nothing shows up on the UITableview.
From the UIViewController class I have a UIAlertAction to accept text and a save button.
      let table = TableViewController()

        let saveAction = UIAlertAction(title: "Save", style:UIAlertActionStyle.Default, handler: {
        alert -> Void in

        let firstTextField = alertController.textFields![0] as UITextField
        self.table.cityArry.addObject(firstTextField.text!)
        self.table.refresh()
    })

And from UITableViewController class
 class TableViewController: UITableViewController {

var cityArry:NSMutableArray = ["Local"]

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self

}

func refresh(){
    dump(cityArry)
    tableView.reloadData()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cityArry.count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->   UITableViewCell {
    let item = cityArry[indexPath.row]
    let cell = UITableViewCell()
    let label = UILabel(frame: CGRect(x:20, y:0, width:200, height:50))
    label.text = item as? String
    cell.addSubview(label)

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    // Nothing here yet

}
}

Comment: You sure the `table` displaying on your screen is the one you call `refresh` on?
Answer: I don't think that you should have two separate view controllers for the screen you're showing. Simplification may end up, as @J.Wang alludes to, solve your problem of calling methods on different objects. Your screen should be well handled with a TableViewController embedded in a Navigation Controller that has a button added to it.
Answer: Try changing this:
func refresh(){
    dump(cityArry)
    tableView.reloadData()
}

to this:
func refresh(){
    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        dump(cityArry)
        self.tableView.reloadData()
    }
}

If it happens that refresh() is getting called on anything other than the main thread the table view will likely not update properly. Might not be the issue but its a good first step.
Answer: you need to reload data  in main thread in refresh function.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})


How to combine multiple indices?

Question: I'm trying to combine various risk indices e.g. flooding, fire, burglary and structural damage. These values are scored from 1-3. For instance, I could have  measures for two different areas as follows:
<code>    flooding | fire | burglary | structural |
            1|     2|         3|           1|
            2|     1|         1|           3|
</code>
My issue is that these values sum to the same score (7) despite the differences in the individual indices (flooding gets a 1 on the first row but a 2 on the second).
My end goal is to plot these values on a map. Thus, I would like a way to identify the unique combinations of each of these 4 scores. In this case I have 81 possible combinations ($3^4$).
I appreciate this is a little off topic, but I thought someone here could help.
Comment: There are different ways of doing this. You could have a weighting system. The weighting function would take each of the 81 possible results and map them to a single number. You could keep it as separate variables and map it in four dimensions (this would be far less visual, obviously). It depends a great deal on what you hope to accomplish to determine the best way to plot these values.
Comment: Well this would be a 4-D map so ... we have to think harder about what you actually want to do.  If you just want to distinguish them then just map them to the numbers $0$ to $80$.  (Map $(a,b,c,d) \to 27(a-1) + 9(b-1) + 3(c-1) + (d-1)$
Answer:
I would like a way to identify the unique combinations of each of these 4 scores

Then map them to a four digit base 3 number.
$(a,b,c,d) \to (a-1)*3^3 + (b-1)*3^2 + (c-1)*3 + (d-1)$.
Each value gets mapped to a distinct number between $0$ and $80$.
Comment: Great, that works. The next step is to visually identify changes in these values so that it's clear when index A is increasing or index B etc.. Would it make sense to multiply each value by a colour measure?

How to combine multiple indices?


Accuracy of SVM prediction

Question: I'm trying to build a text classification model with SVM. The training data set consists of 100 string records with a one-to-one mapped response variable which is also a string. I can't split the data into training and test sets because there are 100 different classes in the response variable.
When I try to predict a new input, the model returns a response, but my question is is there any way to quantify this? Why I want to do this is if the model sees a totally new input, then based on some threshold on this metric, I can write some code to give feedback like "Can't predict as it is not trained before."
Comment: Welcome to Cross Validated! So each outcome category is observed exactly once?
Answer: Since SVM returns an essentially unbounded distance value it can be hard to quantify that in easy terms like one can with probability. Ideally if you could do some cross validation you could look at the average max distance value returned across the different hold out sets and use that as your boundary for saying you're unable to predict. If you can't do any hold out sets you could a similar thing with your training set but set the threshold based on some mis-classification rate. I would however be concerned with over-fitting if you went that route.

Accuracy of SVM prediction


PEP234 iter,unexpected screen output

Question: My code
import sys

f=open('iter.txt')
for chunk in iter(lambda: f.read(20), ''):
   n = sys.stdout.write(chunk)
   print(n)

Screen
Iteration is one of 20
Python's strongest f20
eatures. At a high l20
evel, you might simp20
ly view
iteration as20
 a way to process it20
ems in a sequence. H20
owever, there is so 20
much more that
is po20
ssible, such as crea20
ting your own iterat20
or objects,
12

I expected chunk to be printed without this numerical value.How it comes that it appears?
I found this
iter(callable, sentinel)
This form creates an iterator out of any callable, and will stop when an exception is raised or the sentinel value is returned by the callable.

What is sentinel value?
Comment: Explicitly does `print(n)` - Wonders why it gets done.
Comment: I am using Python3.
Answer: sys.stdout.write does the same as print except it does not add newline at the end. So if you want to remove numerical value remove print(n).

PEP234 iter,unexpected screen output


What the max disc label when recording CDs/DVDs?

Question: When doing backups, I get confused about the max character size of the disk label when recording CDs/DVDs. It's fixed size or follow some standard?
Answer: The max character size does follow a standard.  This webpage gives a good summary about the differences in the formats:
http://msdn.microsoft.com/en-us/library/aa364836(VS.85,loband).aspx


Problem w/ Migrate Source CSV importing Body content w/ HTML

Question: I am using migrate_source_csv to import node body fields. The header for my CSV file is: "nid, title, body". The body fields contain HTML. My problem is that, on import, the HTML is being encoded into literals. See the screen grab below. Here is my migration YML file:

id: news_article_nodes
label: News article data we want.
migration_group: gdg_group
source:
  plugin: csv
  path: 'modules/custom/gdg_migration/import/news_article/news_articles.csv'
  ids: [nid]
  header_row_count: 1
process:
  nid: nid
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: full_html
destination:
   plugin: entity:node
   overwrite_properties:
     - body
   default_bundle: news_article

I must be missing something. Is there a plugin that imports the data as plain text?

Answer: You could try to use PHP's html_entity_decode() on the source field:
process:
  nid: nid
  title: title
  body/value:
    plugin: callback
    callable: html_entity_decode
    source: body
  body/format:
    plugin: default_value
    default_value: full_html

PS: You've written that your source CSV doesn't contain encoded entities... have you checked the display settings for your field? (Manage > Structure > Content types > NODE_TYPE > Manage display). It could be that the import is correct, but the render settings are incorrectly set to something like plain text or a |raw filter in a Twig template file.
Comment: Thanks.  I tried that but same result.   Interestingly, I am having this problem on Windows.  I tried the same development environment on a Mac and it displays the HTML correctly.  I am still  trying to debug on Windows.
Answer: you have just to remove de /0/ from body field
 body/value: body
 body/format:
  plugin: default_value
  default_value: full_html

Comment: When I view source I can see that < is replaced with <, > w/ >, etc.  This is not in the CSV file.  Some thing is filtering the HTML on import.
Comment: Thanks for the suggestion.  Unfortunately, I am getting the same result.


Pegar string entre barras de uma variável PHP

Question: Como pegar a string que esta dentro das duas primeiras barras (naacoclqtsafkbsk) com PHP?
recebo a url pelo GET
$url = $_GET['url']
// https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4

Comment: ela sempre vai ser a quarta?
Comment: Talvez pode mudar por causa de diferentes nomes de arquivos... o tamanho pode afetar eu acho
Answer: O valor que você deseja é o que chamamos de segmento de caminho da URL (do inglês, segment path). Para isso, o ideal é tratar a URL como uma URL através da função parse_url:
$url = parse_url('https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4');

Assim, pegamos apenas a parte do path da URL:
$path = trim($url['path'] ?? '/', '/');

Com o operador ?? garantimos que se a URL não possuir um path seja considerado a string "/", tal como recomenda a RFC. Com a função trim removemos qualquer barra do início ou fim do path, pois para nós, neste ponto, não serão úteis.
Para a string dada na questão, o valor de $path será:
embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4

Assim, dividimos a string nas barras, gerando um array com todos os segmentos de caminho da URL:
$segments = explode('/', $path);

Que será o array:
Array
(
    [0] => embed
    [1] => naacoclqtsafkbsk
    [2] => L3j3md0fD3N4g4P34rIz_Legendado_mp4
)

Com isso, basta você definir qual posição do array lhe é interessante, visto que pelo comentário isso não parece estar muito definido ainda.
Answer: Dê uma olhada na função  parse_url() - Interpreta uma URL e retorna os seus componentes.
A parte em que você está interessado é o caminho, então você pode passar o PHP_URL_PATH como o segundo argumento.
$url = "https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4";

//var_dump(parse_url($url, PHP_URL_PATH));
//string(58) "/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4"

$uriSegmentos = explode("/", parse_url($url, PHP_URL_PATH));

echo $uriSegmentos[2];

ideone


zingchart scale-y-n zoomtovalue

Question: It is possible to use the zoomtovalues in scale-y-2 ?
I have several series in multiple y-axis and I would like to zomm each scale-y-n to specific values, but I do not know how...
Thanks and regards,
Comment: Hi Bill, I'm on the ZingChart team. I don't see a way to do this in our source, although I may be able to implement this into our code by adding an additional option to the zoomtovalues method to allow for zooming on specific scales. Stay tuned!
Comment: Thank yhou Stalfos, I will be watching for the new updates :)
Answer: We've added the ability to do this in one of our recent updates. To zoom in on a different scale, append the scale number onto the option in the zoomtovalues method call. E.G.:
<code>zingchart.exec('myChart','zoomtovalues',{
  'ymin-2':0,
  'ymax-2':500000
});
</code>
This will zoom to 0, 500000 on scale-y-2 and can be seen in action here.
Sorry for the late answer... make sure to let me know if you have any other, newer questions!
Comment: Good to hear that, I will try the new method call :), Thanks Stalfos

zingchart scale-y-n zoomtovalue


android ViewModelFactory with hilt

Question: I am first trying android ViewModel and Hilt DI
As i understand from below link, to initialize ViewModel with a value on run-time i should use ViewModelFactory
Use a ViewModelFactory
//ViewModel
class ScoreViewModel(finalScore: Int) : ViewModel() {
   // The final score
   var score = finalScore
   init {
       Log.i("ScoreViewModel", "Final score is $finalScore")
   }
}

//ViewModelFactory
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
   if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {
       return ScoreViewModel(finalScore) as T
   }
   throw IllegalArgumentException("Unknown ViewModel class")
}

//Fragment
viewModelFactory = ScoreViewModelFactory(ScoreFragmentArgs.fromBundle(arguments!!).score)

And to use ViewModel with hilt i should use @ViewModelInject as explained in below link
Hilt and Jetpack integrations
//ViewModel
class ExampleViewModel @ViewModelInject constructor(
  private val repository: ExampleRepository,
  @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
  ...
}

//Activity / Fragment
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
  private val exampleViewModel: ExampleViewModel by viewModels()
  ...
}

But how to use Hilt with ViewModelFactory?
It seems the answer is in the @Assisted but i can't figure out how
How to tell hilt i like it to inject repository interfaces to ViewModel while still allowing ViewModelFactory to initialize the ViewModel with parameters on run-time?
Comment: This article might provide a clear sharing of how to work with this issue https://medium.com/mobile-app-development-publication/passing-intent-data-to-viewmodel-711d72db20ad
Answer: courtesy of @Elye, next articles helped a lot. I recommend a read.
Passing Activity Intent Data to ViewModel through Injection
Injecting ViewModel with Dagger Hilt
It seems that mostly Factory is not needed since mostly viewmodel initial parameters are taken from previous fragment and can be accessed via SavedStateHandle which is automatically injected if marked as @Assisted
To set-up hilt i used the following code-labs tutorial
Using Hilt in your Android app
Then, viewModel injection is done automatically using only the next code
Note that as noted by fabioCollini here, it seems savedStateHandle can also get values from safe args by simply placing argument name as the key. In fact, that is what i did in the following example. ps: In an attempt to make the safe args be more "safe", i did try to replace the SavedStateHandle with ItemsFragmentArgs hoping it will work but the app did not compile. I do hope it will be implemented in the future (and if already, please let me know)
//ItemFragment file
@AndroidEntryPoint
class ItemsFragment : Fragment() {

    private val viewModel: ItemsViewModel by viewModels()

    //use viewModel as you would. No need to initialize.
}

//Module file - if you have any repository, remember to bind it
//or provide the exact implementation as noted in code-labs
@InstallIn(ApplicationComponent::class)
@Module
abstract class DatabaseModuleBinder {

    @Binds
    abstract fun bindGlistRepository(impl: FirestoreGlistRepository): GlistRepository

}

//ItemsViewModel file - lastly, anotate as follows and take your arguments
//from savedStateHandle (for safe args, use variable name as key)
class ItemsViewModel @ViewModelInject constructor(private val glistRepo: GlistRepository,
                     @Assisted private val savedStateHandle: SavedStateHandle) : ViewModel() {

    private val glistLiveDate = glistRepo.getGlistLiveData(
        savedStateHandle.get<String>("listId")!!
    )

..
}

Hope it helps anyone and if any mistake, please let me know
Comment: `@ViewModelInject` and `@Assisted` are deprecated now.
Comment: To use safe-args in the view model you can implement something like I've shown here: https://stackoverflow.com/a/64814055/1842900
Comment: My Problem was, I was using viewmodel in Fragment and on Fragment i didn't mention @AndroidEntryPoint. I mentioned that on Activity but not on Fragment.
Answer: Pass your ScoreViewModelFactory into built in ktx-extension of viewModel. Also you can consume Activity/Fragment arguments by using SavedStateHandle itself with defaultViewModelProviderFactory.
/*
Gradle Dependencies
def lifecycle_version = "2.2.0"
def hiltLifeVersion = "1.0.0-alpha01"
def hiltVersion = "2.28.1-alpha"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "com.google.dagger:hilt-android:$hiltVersion"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01"
implementation "androidx.hilt:hilt-work:$hiltLifeVersion"
implementation "androidx.hilt:hilt-common:1.0.0-alpha01"
kapt "com.google.dagger:hilt-android-compiler:$hiltVersion"
kapt "androidx.hilt:hilt-compiler:$hiltLifeVersion"
*/

import androidx.fragment.app.viewModels

@AndroidEntryPoint
class ExampleFragment : Fragment(R.layout.example_fragment) {

    //internally using defaultViewModelProviderFactory
    private val viewModel : ExampleViewModel by viewModels()

    //or you own viewmodal factory instance --> scoreViewModelFactory
    private val viewModel : ExampleViewModel by viewModels { scoreViewModelFactory }

}

class ExampleViewModel @ViewModelInject constructor(
    private val repository: ExampleRepository,
    @Assisted override val savedStateHandle: SavedStateHandle
) : ViewModel() {

    //bundle args -> String, Int, Parcelable etc..
    private val arg1LiveData: MutableLiveData<String> =
                         savedStateHandle.getLiveData("arg1", "")

}

In built ktx-extension of Fragment viewmodel
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
    noinline ownerProducer: () -> ViewModelStoreOwner = { this },
    noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)

Comment: scoreViewModelFactory from where?
Answer: In Jilt 2.44, at least, there is no @ViewModelInject. To inject into the constructor of a ViewModel the ViewMolde needs to be annotated with @HiltViewModel and for the constructor you can just use @Inject.
@HiltViewModel
class MyViewModel @Inject constructor(
    private val navigationHelper: NavHelper
) : ViewModel()

android ViewModelFactory with hilt


String append in linux shell script

Question: I writing Linux shell script to test upload file .
before we upload file into storage system i need to get the storage url using rest full service , getting url is successful .in storage url i want to append one string .
Url=$(grep "X-Storage-Url" swiftAuth.txt)  //read url value from file
storageFileUrl=${storageUrl#*:}  //remove extra string before :
echo $storageFileUrl"/111"

url is like https://cloudstorage.com/auth/1.0
so when i trying to append string in run time it gives me wrong value
result is :
/111s://cloudstorage.com/auth/1.0

above result is wrong i want result
https://cloudstorage.com/auth/1.0/111

Please help me
Thanks.
Comment: @BasileStarynkevitch It's the same old problem.  The file from which the value is being read has `CR+LF` line endings.
Comment: Try: storageFileUrl=${storageUrl#*:}/111 ?
Comment: If this is a bash script, put `#!/bin/bash -vx` on its first line (for debugging purposes) and run it again. You'll get a trace of what the shell is doing.
Comment: Also, consider using `awk` in your case. It would make the shell script shorter.  Or even make it an `awk` script
Answer: No, you are not getting /111s://cloudstorage.com/auth/1.0. You are getting https://cloudstorage.com/auth/1.0␍/111.
The ␍ is carriage return, also known as Ctrl-M or ^M.
Bash considers that a regular character. You should be able to strip it by simply ${storageFileUrl%␍}. You can type ␍ on command-line, in vim or in emacs using combination Ctrl-VCtrl-M.
Or you can use recode or dos2unix or similar tool to get rid of the ␍s in input to the initial grep.
Or you can use sed to combine the grep and stripping into one step and that can handle the ␍ for you as well (using the fact that URL can't contain whitespace):
storageFileUrl=$(sed -n 's/X-Storage-Url:[ \t]*\([^ \t\r]*\).*/\1/p')

Note: MIME specifies ␍␊ line endings for the header and Unix only uses ␊, so it's kind of expected to see the ␍s there.

String append in linux shell script


Using supervisor to run a flask app

Question: I am deploying my Flask application on WebFaction. I am using flask-socketio which has lead me to deploying it with a Custom Websocket App (listening on port). Flask-socketio's instructs me to deploy my app by starting the serving with the call socketio.run(app, port= < port_listening_on >) in my main python script. I have installed eventlet on the server so socketio.run should run the app on the eventlet web server.
I can call python < app >.py and all works great – server runs, can view it at the domain, sockets working, etc. My problems start when I attempt to turn this into a long running process. I've been advised to use supervisor which I have installed and configured on my webapp following these instructions: https://community.webfaction.com/questions/18483/how-do-i-install-and-use-supervisord-to-control-long-running-processes
The problem is once I actually add the command for supervisor to run my app it errors with:
<code>Exited too quickly
</code>
My log states the above error as well as:
<code>(exit status 1; not expected)
</code>
In my supervisor config file I currently have the following program config:
<code>[program:<prog_name>]
command=/usr/bin/python2.7 /home/<user>/webapps/<app_name>/<app>.py
autostart=true
autorestart=true
</code>
I have tried a removing and adding settings but it all leads to the same FATAL error.
Comment: Add options to send the `stdout` and `stderr` output to files, so that you can see what's going on when supervisor runs the app. It could be that it runs under a different user (you didn't specify a user to run under).
Comment: Did you find a solution? I am having same the issue here...
Answer: So this is what part of my supervisor config looks like, I'm using gunicorn to run my flask app.
Also, I'm logging errors to a file from the supervisor config, so if you do that, it might help you see why it's not starting correctly.
<code>[program:gunicorn]
command=/juzten/venv/bin/gunicorn run:app --preload -p rocket.pid -b 0.0.0.0:5000 --access-logfile "-"
directory=/juzten/app-folder-name
user=juzten
autostart=true
autorestart=unexpected
stdout_logfile=/juzten/gunicorn.log
stderr_logfile=/juzten/gunicorn.log
</code>

Using supervisor to run a flask app


C++ Debian SDL segmentation fault

Question: I am using SDL to create a quiz game program. The code compiles fine, but when I run the output executable, I get a segmentation fault. I am trying to blit a button onto the screen. Here is my code:
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>
#undef main

void ablit(SDL_Surface* source, SDL_Surface* destination, int x, int y){
        SDL_Rect offset;
        offset.x = x;
        offset.y = y;
        SDL_BlitSurface(source, NULL, destination, &offset);
}

void acreatebutton(int x, int y, int w, int h, SDL_Color fill, SDL_Surface*
screenSurface, const char* buttontext, int fontsize, SDL_Color textfill){
        SDL_Rect* buttonrect;
        buttonrect->x = x;
        buttonrect->y = y;
        buttonrect->w = w;
        buttonrect->h = h;
        int fillint = SDL_MapRGB(screenSurface -> format, fill.r, fill.g,
fill.b);
    SDL_FillRect(screenSurface, buttonrect, fillint);
    TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/droid/DroidSansMono.ttf", fontsize);
    SDL_Surface* buttontextsurface = TTF_RenderText_Solid(font, buttontext, textfill);
    ablit(buttontextsurface, screenSurface, 300, 300);
    TTF_CloseFont(font);
}

int main(int argc, char** argv){
        SDL_Init(SDL_INIT_EVERYTHING);
        TTF_Init();
        SDL_Window* screen = SDL_CreateWindow("Quiz Game",   SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 500, 400,SDL_WINDOW_RESIZABLE);
    SDL_Surface* screenSurface = SDL_GetWindowSurface( screen );
    SDL_FillRect (screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0, 0, 255 ) );
    SDL_Color black = {0, 0, 0};
    TTF_Font* afont = TTF_OpenFont("/usr/share/fonts/truetype/droid/DroidSansMono.ttf", 35);
    SDL_Surface* aQuiz_Game = TTF_RenderText_Solid(afont, "Quiz Game", black);
    ablit(aQuiz_Game, screenSurface, 150, 50);
    acreatebutton(175, 350, 200, 50, black, screenSurface, "Take Quiz", 35, black);
    SDL_UpdateWindowSurface( screen );
    SDL_Event windowEvent;
    while (true){
        if (SDL_PollEvent(&windowEvent))
        {
            if (windowEvent.type == SDL_KEYUP &&
            windowEvent.key.keysym.sym == SDLK_ESCAPE) break;
        }
        SDL_GL_SwapWindow(screen);
    }
    TTF_CloseFont(afont);
    SDL_Quit();
    TTF_Quit();
    return 0;
}

Th ablit function is for blitting, and the abutton function is for creating button images.
Comment: Try to use a debugger to know when the SegFault happens, and if you still can't resolve your problem post your debugger's output here. Another thing is that your never check the return value of the functions, so if some surface or font is null, you can't be warned.
Answer: You should show, where does you code gets to the segfault, otherwise it's difficult to guess.
First culprit could be the line:
TTF_Font* afont = TTF_OpenFont("/usr/share/fonts/truetype/droid/DroidSansMono.ttf", 35);

You create the font, but doesn't check if it succeeded. If the font file doesn't exist on you computer, you will probably get a segmentation fault.
Second problem is in the function acreatebutton. You declare buttonrect as a pointer, but never initialize it! It's an UB and may do anything, e.g. crashing your program.
In this case you probably don't need it to be a pointer at all, so changing it to a simple variable on the stack should work:
SDL_Rect buttonrect;
buttonrect.x = x;
/* more code ... */
SDL_FillRect(screenSurface, &buttonrect, fillint);

You can find both these problems very easily.

Enable all warnings. GCC will tell you about uninitialized pointer when compiling (I recommend adding -Wall -Wextra -pedantic  to you g++ flags).
Learn to use a debugger (GDB is an excelent one). The would tell you everything.
Try a memory sanitizer (compile with -fsanitize=address -g). It will very nicely show you, what went wrong.

C++ Debian SDL segmentation fault


Prove the convergence of $b_n=\log(\frac n{n+1})$

Question: Let $b_n=\log\left(\dfrac n{n+1}\right)$
How can I prove that: $$\lim_{n \rightarrow \infty}b_n=0$$
using an $\epsilon$-$N$ argument.
Answer: Hint: Given $\epsilon > 0$, choose a positive integer $N > \frac{1}{\exp(\epsilon)-1}$. Note $|b_n| = \log(1 + \frac{1}{n})$.
Answer: This depends on whether you have the continuity of the logarithm function available to cite.
Let $\varepsilon>0$ be given.  By continuity of $x\to\log x$ at $x=1$, there exists $\delta>0$ such that whenever $|x-1|<\delta$ then $|(\log x)-(\log 1)|<\varepsilon$.  So the problem then is to that there is an integer $N$ so large that whenever $n\ge N$ then $\left|\dfrac n {n+1} - 1\right|<\delta$.
So
$$
\left| \frac n {n+1} - 1 \right| = \frac 1 {n+1} < \delta \text{ if } n +1 > \frac 1 \delta.
$$
Answer: Hint: $\log(\frac{n}{n+1})=\log n-\log(n+1)=\int_n^{n+1}\frac1x\,\mathrm dx$.


How do I update a subversion server from 1.5 to 1.6 on windows server 2003?

Question: I need to update subversion to make it behave better with branching. how do I go about updateing it?
Answer: If you are running VisualSVN Server on Windows 2003 (as I am), all you have to do is run the new setup file.
Comment: VisualSVN is a nice clean easy solution for Windows server.


Have JUnit fail tests that don't actually run an assertion

Question: My team is working on educating some of our developers about testing. They understand why to write tests and are on board that they should write tests, but are falling a little short on writing good tests.
I just saw a commit like this
public void SomeTest{

@Test
public void testSomething{
 System.out.println(new mySomething.getData());
}

So they were at least making sure their code gave them the expected output by looking.
It will be a bit before we can really sell the idea of code reviews. In the mean time I was considering having JUnit fail any tests that do not have actual assertXXX or fail statements in them. I would then like to have that failure message say something like "Your tests should use assertions and actually examine the output!".
I fully expect this to lead to calls like assertTrue(1 == 1);. We're working on the team buy in for proper testing and code reviews, are there any technical mechanisms we can use to make life easier for the developers that already get it?? What about technical mechanisms to help the new guys understand?
Answer: I think you should consider organizational changes: mentoring, training, code reviews.
The tools can only help you if you're using them in good faith with a base understanding of the goals. If one of these is missing they won't help you.
Humans are just to intelligent to do dump things or work around metrics. I think your assessment is not correct that "they" are on board if they can't write a single useful test. Automatic tools are simply not the correct tools at this stage. You can't learn by being told by a program what to do next.
Comment: I'm with you on getting people to buy in and get educated. I'm looking more for tools to help another developer and I monitor the the code so that when we spot a bad test we can flag it and go talk to the guys that are still learning.
Answer: You can use some static code analyzer.
I use PMD which includes a JUnit rule set. There are a lot of IDE plugins which will mark rule violations in the IDE. You can configure the rule sets to your needs.
You will also profit from the other rule sets - which will warn you on code style / best practice violations (although you have to decide sometimes if the tool or you are the fool :-)).
Answer: to answer the stated question for future viewers.
JUnit uses reflection to run tested function if any Exception, Error throws -> test fails, otherwise succeed. Assert class is just a utils class.


SizeLimitExceededException in LDAP request returning large number of objects

Question: I need to update a large number of objects in LDAP. When I try to fetch them, I catch org.springframework.ldap.SizeLimitExceededException. How can I avoid this exception?
I tried to look for a paging solution, unfortunately the only one I found on the web is deprecated.
Answer: When an LDAP client issues a search request and the number of entries that match the filter exceeds either the client-requested size limit or the size limit imposed on a client's authorization state, or the server has imposed some other limit on the number of entries that match the filter, the server must set the result code in the response to "size limit exceeded". Perhaps the Spring framework has bubbled the response code upwards.
Simple Paged Results are available when supported by the server, as well as Virtual List View.
For more information, see "LDAP: Using ldapsearch", "LDAP: Mastering search filters", and "LDAP: Programming Practices". Also, I have shared some technical LDAP notes related to resource limits being exceeded at my website.


orientation of symplectic manifold and lagrangian submanifolds

Question: A statement: The self-intersection index of lagrangian submanifold $M \subset X$ is equal to Euler characteristic $\chi(M)$. How I should oriented $X$?
Let's consider some example. The null-section $M^2$ of cotangent bundle $T^{*}\!M^2$ is lagrangian submanifold of $T^{*}\!M$. Let $(q_1,q_2)$ be local coordinate on $M$ and $(p_1,p_2)$ is natural coordnate on $T^{*}\!M$. The local forms $\text{d}\,q_1 \wedge \text{d}\,q_2 \wedge \text{d}\,p_1 \wedge \text{d}\,p_2$ define the natural orientation of
$T^{*}\!M$. As I think, for this orientation the self-intersection index $M$ in $T^{*}\!M$ is equal to $\chi(M)$.
The natural symplectic structure on $T^{*}\!M$ is $\omega^2 = \text{d}\,p_1 \wedge \text{d}\,q_1 + \text{d}\,p_2 \wedge \text{d}\,q_2$.
The symplectic form also define orientation
$$
\omega^2 \wedge \omega^2 = 2\,\text{d}\,p_1 \wedge \text{d}\,q_1 \wedge \text{d}\,p_2 \wedge \text{d}\,q_2
$$
So, the orientation induced by symplectic strucuture is not natural. And I should oriented $X$ by $(-1)\omega^2 \wedge \omega^2$.
Answer: If you are dealing with lagrangians inside $X$, then it is clear that you are assuming the existence of a symplectic form, let us say $\omega\in\Omega^2(X)$.
Assume that the dimension of $X$ is the even number $2n$. If $f$ is a smooth function on $X$ such that $f(p)>0$ for every $p\in X$, and $\mathrm{Vol}(X)\in\Omega^{2n}(X)$ is any volume form, then $f\cdot \mathrm{Vol}(X)$ is also a volume form: there is no uniqueness or "natural" choice.
The most famous choices for volume forms for $X$ are $\omega\wedge\cdots\wedge\omega$ and $\frac{1}{n!}\omega\wedge\cdots\wedge\omega$, where the latter is more commonly called the Liouville volume (not always, though).


Types of regression that might work on small samples

Question: I know that this kind of discussion might be both a silly...very silly and a hot issue simultaneously...but I thought it would be nice to raise it : Which types of linear AND non-linear regression could be recommended when you have a small sample size (e.g. 50-70 records) and you want to predict a continuous outcome from 5-7 predictors (both categorical and continuous). Can k-fold cross-validated stepwise linear regression OR Partial Least Regression be a remedy to this problem? Are boosted trees OR Neural networks just insane even to think about them? Your responses are GREATLY WELCOMED and VERY MUCH APPRECIATED.
THANK YOU!
Comment: You don't select the regression method based on the sample size, you select the regression method based on the dependent variable and your research questions.
Comment: This doesn't really deserve to be an answer but part of it is gonna be: what is (in) your data? Because best case a regular OLS will do. Worst case nothing will do. It really will entail a throughout investigation though, as the asymptotic shortcuts cannot be made. So I guess a start would be to check ye olde OLS assumptions first. I think you can guess whre this is going.
Comment: So...Indeed my question was silly. I can admit knowing that it would not make it any better :) With respect to the research question: Testing the predicting ability of these 5 independent variables with reference to the continuous outcome/variable (e.g. attitude)...but I still think...that (sample) size always matter unfortunately...as far as "IMA" kind response...yes now I have a better idea where this is going...THANK YOU! P.S. of course any other additional ideas/views from other members are always welcomed!
Answer: For a simple linear regression model with 1 covariate, I've heard the rule of thumb being no less than 30 observations. However, this can be flexible depending on how well the data fits compared to a $N(\mu, \sigma^2)$ distribution. But for discussion purposes, I recommend the following paper:
http://sites.stat.psu.edu/~ajw13/stat501/SpecialTopics/SampleSizes_MLR.pdf
Please refer to tables 1 and 2 in the paper.


Ridge Regression and The Lasso

Question: I'm trying to compare the penalties of ridge regression and the Lasso. I know the difference between the two methods and that ridge regression shrinks the regression coefficients towards zero while the Lasso sets some of them to be zero and that's why it's in a way a subset selection procedure. My question is that what should I compare in the penalties and is it a mathematical comparison?
My second question is: I obtained the form of the ridge regression estimates when the regressors are orthogonal. How should I obtain that of the Lasso when the regressors are orthogonal? Because there's no close form for the Lasso estimates.
Answer: Ridge regression uses a quadratic penalty, and this is very small for small coefficients, giving almost no regularisation benefit from further reduction, which is why it typically fails to force any of them fully to zero
LASSO uses an absolute value penalty, so reducing a small coefficient to zero can  give the same regularisation benefit as reducing a large coefficient by a small amount, making the approach frequently reduce the number of variables actively used in the final model
For your second question, it might be better to demonstrate LASSO with actual data
Answer: Regarding the second question - this is one of the two (three?) cases when LASSO do have a closed form. Take $ X $ an $n \times p$ matrix, hence you target function is
$$
S(\beta) = || Y - X \beta ||_2 ^ 2 + \lambda || \beta ||_1,
$$
hence the gradient is
$$
\nabla S = 2 X ' ( Y - X \hat{\beta}) + \lambda \text{sign} (\hat{\beta}) = 0
$$
where $\text{sign}(\hat{\beta})$ is an abuse of notation for vector of $\beta$'s OLS signs. So, as $x_i ^ Tx_j = 0$ and $x_i ^ T x_i = 1$, you have
$$
\hat{\beta}(\lambda) = X'Y+ \lambda/2 \text{sign}(\hat{\beta}) = \hat{\beta}^{OLS}+\lambda/2 \text{sign}(\hat{\beta}^{OLS}),
$$
thus the LASSO estimator for any $\beta_j$ can be written as
$$
\hat{\beta}_j(\lambda) = \text{sign}(\hat{\beta}^{OLS})\max\{\hat{\beta}_j^{OLS}+\lambda/2 \text{sign}(\hat{\beta}_j^{OLS}), 0\}.
$$
This is a special case as for orthogonal design each estimator does not depends on the other variables/coefficients.

Ridge Regression and The Lasso


Cannot unpack a zip object multiple times

Question: Why is this not working?:
t = zip([3],[4],[3])
print("1:",*t)
print("2:",*t)

We cannot unpack a second time in Python, why is that?
Comment: How is it not working? What happens when you try it?
Comment: If you dont know why its not obvious
Comment: What is missing is a decent problem description. *This is not working* doesn't tell us anything about what you were expecting and what happened instead. Sure, the experts can take a good guess, but that's not helpful for other future visitors with the same issue, they won't find this question.
Comment: @TimCastelijns: I realised, and edited the comment already. :-)
Answer: zip returns an iterator in Python 3.x instead of a list like it did in Python 2.x.  This means that, after you unpack it once, it will become exhausted and no longer usable:
>>> t = zip([3],[4],[3])
>>> print("1:",*t)
1: (3, 4, 3)
>>> list(t) # t is now empty
[]
>>>

You need to explicitly convert the iterator into a sequence (a list, tuple, etc). if you want to unpack it multiple times:
>>> t = tuple(zip([3],[4],[3]))
>>> print("1:",*t)
1: (3, 4, 3)
>>> print("2:",*t)
2: (3, 4, 3)
>>>


change color of listview in android by custom adapter

Question: Below is my mainactivity java code I have a json file which returns the following values.
[
 {
  "COMPONENT": "xxxx",
  "FLAG": "T",
  "SAMPLINGPOINT": "dddd"
 },
 {
  "COMPONENT": "yyyyy",
  "FLAG": "F",
  "SAMPLINGPOINT": "ggggg"
 },
 {
  "COMPONENT": "xxxx",
  "FLAG": "F",
  "SAMPLINGPOINT": "dddd"
 },
 {
  "COMPONENT": "xxxx",
  "FLAG": "T",
  "SAMPLINGPOINT": "dddd"
 }

]

On display if the json value FLAG:T then the ListView color should be red else if FLAG:F then green. Where do I put the custom adapter and how?? any help??
public class MainActivity extends Activity {

    String TAG = "Response";
    TextView responseText;
    Button bt;
    EditText celcius;
    String getCel;
    SoapPrimitive resultString;
    String color, item;
    String str = "%s";
   //private static final String name = "ID_NUMERIC";
   // private static final String test = "TEST";
    private static final String component = "COMPONENT";
   // private static final String units = "UNITS";
    private static final String value = "VALUE";
    private static final String flag = "FLAG";
    //private static final String color = "color";
    //private static final String samplingpoint = "SAMPLINGPOINT";
    JSONArray Response = null;
    String jsonObject_string ;
    String jArray;
    ListView list;
    TextView vers;
    TextView name;
    TextView flg;
    TextView api;
    ListAdapter adapter;
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

    public void calculate() {
        String SOAP_ACTION = "";
        String METHOD_NAME = "";
        String NAMESPACE = "";
        String URL = "";

        try {
            SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
            Request.addProperty("SmapleID", getCel);

            SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            soapEnvelope.dotNet = true;
            soapEnvelope.setOutputSoapObject(Request);

            HttpTransportSE transport = new HttpTransportSE(URL);

            transport.call(SOAP_ACTION, soapEnvelope);
            resultString = (SoapPrimitive) soapEnvelope.getResponse();

            //Log.i(TAG, "Result SmapleID: " + resultString);
        } catch (Exception ex) {
            Log.e(TAG, "Error: " + ex.getMessage());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       // ListView list = (ListView) findViewById(R.id.list);
        responseText = (TextView) findViewById(R.id.responseText);
        bt = (Button) findViewById(R.id.bt);
        celcius = (EditText) findViewById(R.id.cel);
        list = (ListView) findViewById(R.id.list);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                getCel = celcius.getText().toString();
                AsyncCallWS task = new AsyncCallWS();
                task.execute();

            }
        });

    }

    private class AsyncCallWS extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected String doInBackground(String... params) {
            Log.i(TAG, "doInBackground");
            calculate();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            //calculate();

            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_child,new String[] {component, value, flag, color }, new int[] {R.id.name, R.id.vers, R.id.flg});
            list.setAdapter(adapter);

             oslist.clear();

            // Making a request to url and getting response
            String data = "";
            String data1 = "";
            String data2 = "";
            String data3 = "";
            String data4 = "";
            String data5 = "";
            String jsonStr = resultString.toString();

            //Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {

              try

            {

              JSONArray jArray = new JSONArray(jsonStr);

            for(int i=0;i<jArray.length();i++){
                JSONObject json_obj = jArray.getJSONObject(i);

               // String name = json_obj.getString("ID_NUMERIC");
               // String test = json_obj.getString("    TEST");
                String component = json_obj.getString("COMPONENT");
                //String units = json_obj.getString("UNITS");
                String value = json_obj.getString("VALUE");
                String flag = json_obj.getString("FLAG");
               if ("F".equalsIgnoreCase(flag));{
                   color = "red";
               }
                //data = name;
               // data1 = test + ", ";
                data2 = component;
               // data3 = units;
                data4 =  value;
                data =  flag;

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("COMPONENT", data2);
                map.put("VALUE", data4);
                map.put("FLAG", data);

                oslist.add(map);

        }
            }catch (JSONException e) {
                // handle exception
            }

        }
          // return null;
        }

    }}
}

From the comment
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, oslist, R.layout.list_child,
            new String[]{component, value, flag}, new int[]{R.id.name, R.id.vers, R.id.flg});
    list.setAdapter(adapter);

Comment: Please share custom Adapter code also
Comment: well..thts what i want..the code and where and how to put it i basically need to change the color of my listview based in the json value using custom adapter
Comment: But you have already `SimpleAdapter` class which is Adapter for ListView. please share `SimpleAdapter` class code
Comment: you can use BaseAdapter for that you can check this answer for BaseAdapter and in base adapter getView method you can change view http://stackoverflow.com/a/28104066/1140237
Comment: okay...so then how do i filter out the json value from the file above using this adapter..
Comment: @ThunderGoli: dude, share `SimpleAdapter` class code then we will tell you
Comment: ok  ρяσѕρєя..here is the SimpleAdapter class code
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_child,new String[] {component, value, flag}, new int[] {R.id.name, R.id.vers, R.id.flg});
list.setAdapter(adapter);
Comment: waitin fr yr answer  ρяσѕρєя plzz
Comment: @ρяσѕρєяK `SimpleAdapter` is android class not custom class by  @thunder Goli
Answer: Use below adapter for reference.I have changed colors for every alternate row. Change it by putting condition as appropriate.
Make sure to create osList before setting adapter on the list & replace stockCursor with osList.
private class StockAdapter extends BaseAdapter
{
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return stockCursor.getCount();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View v = convertView;
        ViewHolder viewHolder = null;
        if(convertView == null)
        {
            v = LayoutInflater.from(StockDetailsActivity.this).inflate(R.layout.stock_details_list_item, null);

            viewHolder = new ViewHolder();
            viewHolder.model_name_tv = (TextView) v.findViewById(R.id.model_name);
            viewHolder.model_type_iv = (ImageView) v.findViewById(R.id.model_type_icon);
            viewHolder.model_type_tv = (TextView) v.findViewById(R.id.model_type_desc);
            viewHolder.model_stock_tv = (TextView) v.findViewById(R.id.model_stock_value);
            v.setTag(viewHolder);
        }
        else
            viewHolder = (ViewHolder) v.getTag();

        stockCursor.moveToPosition(position);

        if(position % 2 == 1)
            v.setBackgroundColor(getResources().getColor(R.color.john_deere_green40));
        else
            v.setBackgroundColor(getResources().getColor(R.color.john_deere_green60));

        return v;
    }

    public class ViewHolder
    {
        public TextView model_name_tv;
        public ImageView model_type_iv;
        public TextView model_type_tv;
        public TextView model_stock_tv;
    }
}

Comment: i am sorry..i am not able to understand as to how to use this reference in my code...
Answer: You can use setViewBinder method for customization list
you can edit your code in onPostExecute
 SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_child,new String[] {component, value, flag, color }, new int[] {R.id.name, R.id.vers, R.id.flg});
 adapter.setViewBinder(new ViewBinder() {

        @Override
        public boolean setViewValue(View view, Object data,
                String textRepresentation) {

        switch (key) {
           case R.id.name:
             //example
             TextView tvName = (TextView) view;
                // hear you can customize your textview as per your req.
             tvName.setText(Html.fromHtml(""
                        + /*get you value from JSON*/  + " "));
             return true;
            case R.id.vers:
             return true;
            case R.id.flg:
             return true;

        default:
            break;
        }
      return false;

    });
}
list.setAdapter(adapter);

Comment: so for changing the color of the json value flg what code do i write milapTank
Comment: @ThunderGoli see my update `tvName.setText(Html.fromHtml(""
                        + //get you value from JSON  + " "));`
Comment: thnx milap but there is a syntax error showing at the end of your code before the line

list.setAdapter(adapter);
Comment: You can get hint from this code may be there is my mistake in typo but you can solve syntax error  BTW can you tell me more about that ?
Comment: it says Syntax error, insert "}" to complete ClassBody
Comment: there is switch case problem are  you able to solve this ?
Comment: first of all dont copy my code use editor hint and write code from my code DONT COPY please
Comment: @ThunderGoli  i have update my question you can get it
Comment: i can give you technical solution but syntax error you have solve buddy  this is basic :)
Comment: maan still gettin syntax error
Syntax error on token(s), misplaced construct(s)
newas u hlpd yr best milapTank. ..thnx buddy
Answer: Please check below posted code for custom listadapter & i have mentioned things in comment inside code block.
private class ListViewCustomAdapter extends BaseAdapter {
        Context context;
        int totalDisplayDatasize = 0;
        ArrayList<HashMap<String, String>> codeLeanChapterList;

        public ListViewCustomAdapter(Context context,
                                     ArrayList<HashMap<String, String>> codeLeanChapterList) {
            this.context = context;
            this.codeLeanChapterList = codeLeanChapterList;
            if (this.codeLeanChapterList != null)
                totalDisplayDatasize = this.codeLeanChapterList.size();
        }

        @Override
        public int getCount() {
            // this could be one of the reason for not showing listview.set
            // total data length for count
            return totalDisplayDatasize;
        }

        @Override
        public HashMap<String, String> getItem(int i) {
            return this.codeLeanChapterList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        private class Holder {
            TextView textView1, textView2;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            View view = convertView;
                /*
                 * First time for row if view is not created than inflate the view
                 * and create instance of the row view Cast the control by using
                 * findview by id and store it in view tag using holder class
                 */
            if (view == null) {
                holder = new Holder();
                // / No need to create LayoutInflater instance in
                // constructor

                convertView = LayoutInflater.from(this.context).inflate(
                        R.layout.listitem, parent,false);

                holder.textView1 = (TextView) convertView
                        .findViewById(R.id.textView1);
                holder.textView2 = (TextView) convertView
                        .findViewById(R.id.textView2);

                convertView.setTag(holder);
            } else {
                    /*
                     * Here view next time it wont b null as its created and
                     * inflated once and in above if statement its created. And
                     * stored it in view tag. Get the holder class from view tag
                     */
                holder = (Holder) convertView.getTag();

            }
            holder.textView1.setText("COMPONENT: "
                    + codeLeanChapterList.get(position).get("COMPONENT"));

            holder.textView2.setText("VALUE: "
                    + codeLeanChapterList.get(position).get("VALUE"));
            String flagChar = codeLeanChapterList.get(position).get("FLAG");
            if ("T".equalsIgnoreCase(flagChar)) {
                holder.textView1.setBackgroundColor(Color.RED);
                /// in this i have given background color to textview
                //you can change it to listitem layout or whatever object you want
            } else if ("F".equalsIgnoreCase(flagChar)) {
                holder.textView1.setBackgroundColor(Color.GREEN);
                /// in this i have given background color to textview
                //you can change it to listitem layout or whatever object you want
            } else {
                // keep this case if its required
            }
            return convertView;
        }
    }

listitem is listitem layout which has 3 textview in your case it will be your listview layout and based on that you need to change getView method and holder class too. if you are new with this things thn please check http://developer.android.com/reference/android/widget/BaseAdapter.html
http://ocddevelopers.com/2014/extend-baseadapter-instead-of-arrayadapter-for-custom-list-items/
Answer: public class CustomList extends BaseAdapter{
ArrayList<HashMap<String, String>> data

public CustomList(Activity context, ArrayList<HashMap<String, String>> arr) {
    this.ctx = context;
    this.data = arr;

}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return data.size();
}
@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    try {
        return data.get(position);
    } catch (Exception e) {
        return 0;
    }
}
@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    try {
        return position;
    } catch (Exception e) {
        // TODO: handle exception
        return data.size();
    }
}
@SuppressLint("NewApi")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    try {
        // TODO Auto-generated method stub
        LayoutInflater inflat = ctx.getLayoutInflater();
        final Holder holder;
        if (convertView == null) {
            convertView = inflat.inflate(R.layout.listview_desc_discover, null, false);
            holder = new Holder();

            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }

        if (data.get(position).get("FLAG").equals("F")) {
            // set green color to  convertView
        } else if(data.get(position).get("FLAG").equals("T")){
           // set green red to  convertView
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return convertView;

}


View content inside linux virtual machine without root password

Question: I have a virtual machine, which run opensuse OS, but I forgot root's password, so I cannot login. But I want to view some files inside it. Is there anyway to do it, for example, view the vmdk by another virtual machine, can I do that?
Comment: I would recommend you simply follow the manual  and [recover that lost root password](https://en.opensuse.org/SDB:Recover_root_password)
Answer: How about libguestfs and especially its guestfish interactive console or guestmount mount tool?


Asp.NET Erro Click do Asp:button

Question: Tenho uma tela onde possuo alguns botões e ao clicar sobre os botões me devolve o erro na tela:

"Index was out of Range Must be non-negative and less than the size of
  the collection."

O mais estranho é que no evento click destes botões há um try/catch, e dentro do catch um método que loga os erros ocorridos no sistema.
Resumindo: não está entrando evento "Click" do botão..
Para dificultar, o erro só ocorre em produção, em desenvolvimento não.. e não tenho como acessar o ambiente de produção.
Fazendo alguns testes aqui descobri que, se eu acessar a pagina do sistema utilizando "https" os botões funcionam normalmente, já com o "http" da esse erro de "index was out...". Esse erro começou a ocorrer desde a última subida em produção.
Answer: O erro é característico de tentar acessar alguma posição do Array com um índice negativo.
Se o evento não chega no click, é porque antes de executar o evento Click, no fluxo da Page, sempre é executado o evento Page_Load. Então, pode haver algum código neste evento que esteja causando o erro.
Se postar o seu código, podemos solucionar com maior precisão.
Comment: Fazendo alguns testes aqui descobri que, se eu acessar a pagina do sistema utilizando "https" os botões funcionam normalmente, já com o "http" da esse erro de "index was out...".
Comment: Antes isso nao ocorria, sempre acessamos sem o "https", pq inclusive tinhamos problemas com isso..e desde a ultima subida para produção isso começou a ocorrer..tem ideia do pq disso? o pessoal de redes diz que é algo da aplicação..
Comment: Teria como enviar o código do que é feito no botão e no page_load?

Asp.NET Erro Click do Asp:button


R, plm, fitted values

Question: I try to use a GoF measure called MAPE mean absolute percentage error, I know there are some related answers that a$model[[1]]-a$residuals is the best way in the the plm package.
The problem is I use first differences and lagged variables, length(a$model[[1]]) is 3327 and length(a$residuals) is 2845.
Any ideas how I could still use percentage error measures?
Comment: What's the question here? How best to calculate this in R? Seems off-topic if so.
Comment: There is some statistical background to it because the number of residuals in a first-differenced model is not equal to the number of (original) observations.
Comment: couldn't find a \ command to write a dollar sign, any help?
Answer: For first-difference (and between) models, the model frame (what you get via model_object$model) is the original data and has more observations than the transformed data the first-differenced model is estimated on (you lose 1 observation per individual due to first-differencing). This is why the number of rows do not match the number of entries of the residual vector.
Use pmodel.response() to get the transformed (in this case first-differenced) response variable: pmodel.response(a) - a$residuals.
NB: For your use case, only use pmodel.response() for FD or between models, not for other model types.

R, plm, fitted values


Azure AD B2C logout issue

Question: Issue summary:
msal.logout() appears to log the user out, but after "logging out" the user can click "login" and be logged in again without being required to enter their username and password.
This is a serious security issue for user's who login to our application on a public computer, then logout thinking that they have prevented someone from accessing their account.
Frontend is using Angular-msal 1.0.0 (Angular-oauth2-oidc has the same issue, so I think it's not the problem of js library).
Azure AD B2C built in user flow and xml custom policy both have this logout issue when login with federated AAD tenant user.
Any help would be appreciated.
Thanks.
Answer: The MSAL library provides a logout method that clears the cache in browser storage and sends a sign-out request to Azure Active Directory (Azure AD). Request will be done against the end_session_endpoint URL obtained from the B2C policy metadata. Keep in mind single sign out is supported only by custom policies and that it's scoped to the same browser, not device.
Just in case you are still facing any issue an idea would be to redirect using &prompt=loginin your auth url will revoke your login request with out user session.
Comment: Thanks for your response.
I did use that logout method provided by MSAL library.
Also tried with &prompt=login, but still doesn't work.
Is the &prompt=login used for auth code flow? I'm using implicit flow.
Comment: This is a known issue in msal.js occurs due to browser extension cookie blockers / third party cookies disabled in browsers.

To fix this, MSAL.js v2 mitigates this in most scenarios by using the auth code flow instead of the implicit flow.
Comment: ` &prompt=login`  can be used in any flow and it will force the app to go to login page
Comment: Are you using custom policies? Are you using Application scoped SSO?
Comment: I'm using custom policies and Tenant scoped SSO.
Comment: Hi @BlueArena, Is the authentication happening in webview??
Comment: I found the root cause for this issue, there is an error when do the logout: Refused to display 'https://login.microsoftonline.com/common/oauth2/v2.0/logout' in a frame because it set 'X-Frame-Options' to 'deny'.
This prevent to display the logout page which can let you to choose which user account want to logout. I think without this it won't send a sign-out request to Azure AD.
Comment: Hi @HariKrishna--MSFTIdentity, Thank you very much.
Comment: I found a workaround for this issue, doesn't resolve the xframe issue, but it's working.
Add "postLogoutRedirectUri": "https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:4200" to the auth config.

Tried to use below logoutUrl and postLogoutRedirectUri, but not working.
"logoutUrl": "https://login.microsoftonline.com/common/oauth2/v2.0/logout",
"postLogoutRedirectUri": "http://localhost:4200/",
Comment: Have you tried changing the auth flow from implicit to auth code flow.
Comment: @HariKrishna--MSFTIdentity, I tried that before, seems auth code flow doesn't work with msal.js 1.0 and angular-oauth2-oidc 1.0
Comment: The MSAL library will now support the Authorization Code Flow with PKCE for Browser-Based Applications without a backend web server. Please refer [document](https://www.npmjs.com/package/@azure/msal-browser#implicit-flow-vs-authorization-code-flow-with-pkce) for more details.

Azure AD B2C logout issue


Auth Indentify nao funciona CakePhp

Question: Este mesmo código ja foi usado para outros projetos, e nao entendo pq aqui não funciona. O erro que me retorna é que o Usuarios e senha estão incorretas, ele nao passar do Auth->identify, e user_id e user_name me retorna NULL.  Já verifiquei tamanho da senha, os campos do html de input estao corretos e o usuario que estou entrando existe no banco.
AppController
public function initialize()
{

    ini_set('memory_limit', '256M');
    set_time_limit(0);

    // Inicializa principais componentes
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth');
    $this->loadComponent('Cookie');

    // Configura Data e Hora da aplicação
    setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
    date_default_timezone_set('America/Sao_Paulo');

    // Configura os padrões para o login
    $this->Auth->config(
        'loginAction', [
            'controller' => 'Login',
            'action' => 'index'
        ],
        'loginRedirect', [
            'controller' => 'Dashboard',
            'action' => 'index'
        ],
        'logoutRedirect', [
            'controller' => 'Public',
            'action' => 'index'
        ],
        'authenticate', [
            'Form' => [
                'userModel' => 'Users',
                'fields' => ['username' => 'email', 'password' => 'password']
            ]
        ],

        'storage', 'Session'
    );

    // Define variáveis
    $date_now = Time::now();

    // Disponibiliza dados para views
    $this->set('user_id', $this->Auth->user('id'));
    $this->set('user_username', $this->Auth->user('username'));
    $this->set('today', $date_now);

}

public function isAuthorized($user) {

      return true;

}

public function beforeRender(Event $event)
{
    // Define _serialize do tipo Json ou Xml
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);
    }

}

public function beforeFilter(Event $event)
{

    // Login
    $this->Auth->allow(['index']);
    $this->Auth->allow(['validatePassword']);

    // Register
    $this->Auth->allow(['registrarIntercambista']);
    $this->Auth->allow(['confirmarEmail']);
}

}
User.php
protected $_accessible = [
    '*' => true,
    'id' => false
];

/**
 * Fields that are excluded from JSON versions of the entity.
 *
 * @var array
 */
protected $_hidden = [
    'password'
];

protected function _setPassword($password)
{
  if (strlen($password) > 0) {
    return (new DefaultPasswordHasher)->hash($password);
  }
}

LoginController
if ($this->request->is('post')) {

        $username = $this->request->data['email'];
        $password = $this->request->data['password'];

        // Verificar expiração
        $date_now = Time::now();

        // Verifica e-mail
        if (Validation::email($username)) {

            // Identifica usuário
            $this->Auth->constructAuthenticate();
            $user = $this->Auth->identify();

            if ($user) {

                $this->Auth->setUser($user);

            }else{

            // E-mail inválido
            $result = array(
                'status' => 'usuario ou senha inválido!',
                'redirect' => ''
            );
        }else{

            // E-mail inválido
            $result = array(
                'status' => 'E-mail inválido!',
                'redirect' => ''
            );
        }

    }else{
        $result = array(
            'status' => 'no-post',
            'redirect' => ''
        );
    }

    $this->set(compact('result'));
}

Answer: Encontrei meu problema e era erro no codigo do App Controler, arrumado ele ficou assim:
$this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'userModel' => 'Users',
                'fields' => ['username' => 'email', 'password' => 'password']
            ]
        ],
        'loginAction' => [
            'controller' => 'Login',
            'action' => ''
        ],
        'loginRedirect' => [
            'controller' => 'Dashboard',
            'action' => ''
        ],
        'logoutRedirect' => [
            'controller' => 'Public',
            'action' => 'index'
        ],

        'storage', 'Session'
    ]);

Auth Indentify nao funciona CakePhp


Swift iOS posting file as parameter to PHP Webservice

Question: I am very new to iOS and swift in general and hope someone can help.  I am trying to create a very simple swift iOS app that will do an HTTP post with multiple parameters one of them being an image or audio file.  Please suggest better approaches if you see one, but this is simply a proof of concept at this point.  Obviously I'm posting so it isn't working from my swift app, but I have been able to get the PHP web service to work via other means (i.e. "Rest Client" ios app).
<code>    func uploadFile(filename:String) {
    println("uploading \(filename)")

    var docsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    var url = NSURL(fileURLWithPath: docsDir + "/" + filename)

    var request = NSMutableURLRequest(URL: NSURL(string: "http://www.somewebsite.com/testWS.php"))
    var audioData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe,error: nil)

    var bodyData: String = "filenames=Tesing123&userfile=\(audioData)"

    request.HTTPMethod = "POST"

    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
       {
            (response, data, error) in
           println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }
}
</code>
My PHP web service is:
<code><?php

$myparam = $_POST['userfile'];     //getting image Here
$mytextLabel= $_POST['filenames'];   //getting textLabe Here

$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['userfile']['tmp_name']);

echo basename( $_FILES['userfile']['name']);
echo $_POST['userfile'];

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {
    echo "The file ". basename( $_FILES['userfile']['name']) . " has been uploaded";
} else {
    echo "!!!!!There was an error uploading the file, please try again!";
}
?>
</code>
Thanks in advance.
Comment: You need too look into making a `multipart/form-data` post. See [TUTORIAL: POST TO WEB SERVER API IN SWIFT USING NSURLCONNECTION](http://www.brianjcoleman.com/tutorial-post-to-web-server-api-in-swift-using-nsurlconnection/) for an example.
Answer: I had same kind of issues time ago.
I recommend you to use some existing lib if you are not expert.
SwiftHTTP Should be fine
Otherwise have a look of:
Agent
Net
(I have had some issues with them as they were not made for multipart/form-data)


Best Setup with AWS ALB and Tomcat

Question: Our company currently operates a monolithic application that comprises multiple instances of Tomcat running on two servers. These instances are load balanced using Apache, where each instance listens on a different port and is then redirected to its respective endpoint (e.g., /payments, /orders, etc.).
We are in the process of migrating our infrastructure to AWS and considering replacing Apache with an Application Load Balancer (ALB). We would like to seek your opinion on whether this is a viable approach.
Additionally, we are considering creating individual EC2 instances for each Tomcat endpoint. For instance, having two servers with multiple instances dedicated to /payments, two servers for /orders, and so on. What are your thoughts on this approach?
Moreover, we are curious to know if ALB supports redirecting multiple ports to a single target. For instance, we would like to redirect ports 8090, 8091, 8092, and 8093 to the /payments endpoint.
Thanks!
Comment: In general your migration strategy is either "as is"  and one makes as few changes as possible to ensure a quick migration. Or alternatively you refactor your existing application deployment / infrastructure and migrate to a more cloud-native application deployment / infrastructure design. Moving away from apache fits better in that latter scenario and then you should probably also abandon  the concept of having a server with  multiple tomcat instances dedicated to /payments and launch as many EC2 instances as you need, each with only a single tomcat instance dedicated to /payments.
Answer: Using an ALB / Application Load Balancer sounds appropriate for this use case. It's correct for most http(s) load balancing use cases in AWS, though some edge cases it can't do.
The ALB has a fairly flexible architecture in terms of listeners for incoming connections/port and target groups. You should be able to do what you need. However, once you get into AWS and understand how things are set up I'm not sure you'll need to do that, but it depends how your solution is architected.
Having one server per Tomcat instance sounds sensible to me. Put one in each availability zone for redundancy. Be aware that if you enable cross zone load balancing (default ON if created in the console) the load balancer in AZ-A can send traffic to the container in AZ-B which incurs inter-AZ traffic fees. AWS says it tries to keep traffic within the availability zone where possible. Keep an eye on your bill, turn the feature off if needed. You should be considering autoscaling and health checks.
Instead of instances you should consider containers, which you can run on EC2 instances you manage or Fargate containers. Fargate containers cost a little more but AWS manages them, so it saves you some effort. AWS Elastic Container Service (ECS) is more than sufficient for most use cases, you don't need EKS / K8S and all the complexity it brings for most use cases.
You could also simply migrate your servers into AWS. That usually works, but in many cases is a first step to rearchitecting a solution to work in a more cloud native manner.
If you don't understand some of the terms in my answer you're welcome to ask questions, but I also suggest getting some training. AWS is a complex enterprise environment and it's easy to get things wrong, run up a large bill, or miss something that creates security issues. Training for the AWS Architect Associate certificate would be suitable. There are plenty of training providers around, I like Adrian Cantrill training especially for beginners, but there's also Cloud Guru and many others.

Best Setup with AWS ALB and Tomcat


linear combination of images gives me error

Question: let us consider following code
import  numpy as np

import cv2 as cv

imag1 =cv.imread('logos.jpg')
imag1 =cv.cvtColor(imag1,cv.COLOR_BGR2GRAY)
shape1 =imag1.shape
print(shape1)
imag2 =cv.imread('arduino.jpg')
imag2 =cv.cvtColor(imag2,cv.COLOR_BGR2GRAY)
shape2 =imag2.shape
print(shape2)

imag2 =cv.resize(imag2,(shape1[1],shape1[0]))

cv.imshow('logos',imag1)

cv.imshow('arduino',imag2)
result1 =cv.addWeighted(imag1,0.2,imag2,0.8,0)
cv.imshow('result1',result1)
alpha =0.5
result =alpha *imag1 + (1-alpha)*imag2
cv.imshow('result',result)
cv.waitKey(0)

built in function of python- cv.addWeighted  works fine, but when i am trying to implement second one, it gives me following error
Traceback (most recent call last):
  File "C:/Users/Dato/Downloads/python_environment/weighted.py", line 23, in <module>
    cv.imshow('result',result)
cv2.error: OpenCV(4.0.0) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:261: error: (-2:Unspecified error) in function '__cdecl cv::CvtHelper<struct cv::Set<1,-1,-1>,struct cv::Set<3,4,-1>,struct cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Unsupported depth of input image:
>     'VDepth::contains(depth)'
> where
>     'depth' is 6 (CV_64F)

size of images  are (223, 400) ,(223, 403), that why i applied resize function to make images equal to each other, but i can't understand what is the reason of error? thanks in advance
Answer: The second method results in values that can potentially be fractional values. Since intensity values are integer values between 0 and 255, you want to round the resulting values of your linear combination, and then set the data types as uint8.
result = alpha * imag1 + (1 - alpha) * imag2
result = np.around(result).astype(np.uint8)