Should class variables be initilized before subscribe method or after in Angular

Question: I have the method getAllDates that appends (inside the next handler) all the schedule dates from the server to class scope array variable  this.futureScheduleDateStrings. My question is - should I initialize that array to empty content before subscribe method or at the beginning of the next handler - I have noticed that if I initialize it before subscribe it has some duplicates values.
getAllDates() {
    this.futureScheduleDateStrings = [];
    this.accountService.getAllDates()
      .pipe(first())
      .subscribe({
        next: (value: ScheduleDateTimes) => {
          //this.futureScheduleDateStrings = [];
          this.scheduleDateTime = value.scheduleDateTimes;

          ...
        },
        error: error => {
          console.log();
        }
      });

Comment: I don't see how you assign the response data to `futureScheduleDateStrings` here. You mention that there is duplicate data, is it possible that you are appending the data to `futureScheduleDateStrings` and the observable is returned/fired for multiple times? This will result your `futureScheduleDateStrings` contains the value/data from previous Observable.
Comment: I always push never append
Comment: Same. `push` is adding the data into the array, but not re-assign the value. If you want fresh data for each time observable return, you should reset/reassign the array.
Answer: You might be experiencing double execution because of the double click on a button that calls getAllDates method. Try debounceTime(300) to prove it.
Also you don't need first if you are working solely with HTTP requests. Observable will automatically complete after the request is done.
Regarding the initialization of futureScheduleDateStrings: you have to initialize it immediately (either with property initializer or in type's constructor). Enable ESLint with recommended rules for your app and you won't need to ask such questions here, it will report all problems in your code immediately.
Answer: I think I have found the problem. Two immediate attempts to call the subscribe one after another initialize twice the variable futureScheduleDates to empty array.
Then each subscribe is called and no initialization is happening anymore - that is why there is duplicate. The only solution I see is to initialize this variable inside the next handler.
I don't have anything like mutext like in c#/c++.
Is there any other fix for that problem?
Comment: I am sorry but could you please describe the root of you problem in other words? I didn't understand what you mean by "Two immediate attempts to call the subscribe one after another initialize twice the variable futureScheduleDates to empty array". Obviously `subscribe` is called twice because your method `getAllDates` is called twice. So `subscribe` is not your problem (at least from the code snippet you posted). Also if an array is set to be empty in `subscribe` then it has to be empty because server returned no data.
Comment: "I don't have anything like mutext like in c#/c++" - you don't have "anything like mutext" in JS because it is single-threaded, there is nothing to synchronize.
Comment: Lets say I have three immediate calls to the function `getAllDates()`.
One gets through to the `next` handler of the `subscribe` and two others are stopped at the call to the `this.accountService.getAllDates()` - that is what I see using debugger.
When two calls stop at the call to `this.accountService.getAllDates()` the `futureScheduleDateStrings` is initialized twice to an empty array.
When both of them in a sequence (one after another) get to the handler `next` , the second one will see items that the first one put into the `futureScheduleDateStrings`.

Does this make more sense?
Comment: @Volodymyr Usarskyy Hi Volodymyr - is the question more clear after my last answer?


Loading a JSON file containing parameters used by the code in a javascript web page

Question: I'm developping a web UI in javascript. Data are stored in a remote DB, accessed by an API.
I need extra data that are not stored in the DB, and I can't create any table or store any structured data in it.
I started by creating arrays in the code but it quickly becomes unreadable and overwhelming, leading to an awful mix of code and data in my JS files.
So I created a JSON file to store them, looking like that.
{
    "version": "1.0",
    "encoding": "UTF-8",
    "arrays": {
        "array1": [
            ["key1","value1",0],
            ["key2","value2",1]
        ],
        "array2": [
            ["key1","value1",0],
            ["key2","value2",1]
        ]
    },
    "templates": {
        "template1": {
            "property1": 2,
            "property2": "value2",
            "property3": true
        },
        "template2": {
            "property1": 3,
            "property2": "value3",
            "property3": false
        }
    }
}

I coded a simple parser, loading the data in a global JSON object at the beginning of the code, with a synchronous XMLHttpRequest as I need the data to be available from multiple functions at any time during execution.
var jsonDB = JSON.parse(getXML('https://example.com/data.json'));
// Where getXML is a function using a sync XMLHttpRequest to get and return the file.

Then I can use these data as follow:
function X (param0, param1, param2) {
    if ( param0 == jsonDB[param1][param2].property1 ) {
        return jsonDB[param1][param2].property2;
    }
}

The JSON file is around 90 kbytes, loaded very quickly. From my perspetive, the architecture is good : code is clean, separated from this data ; and data are structured, easily maintained. From a user perspective, the load time is insignificant.
However, I'm getting an annoying warning:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

Then, I created a async xhr function to load the file. But the number of times it's called is so big that it ends up in unresolved requests and empty fields in the rendered HTML. I don't know how the async xhr is caching the JSON file, but the result is that responses are getting lost.
I eventually tried to used await/sync and Promises but I didn't mange to get something working as expected without rewritting the whole code, which is not an option.
I need to load a JSON file, once and only once, from the beggining of the code execution to make it available from anywhere, without getting a warning from the browser. Exactly like if it was a .js lib or a css file. It's ok the block execution for few ms but it's not ok to have a warning.
Can anyone please help me to solve this?
Note: I've seen many questions turning around loading JSON in JS on the site, but none was addressing this precise issue (JSON as variables) and all tests I've done with await/sync failed.
Comment: why don't you put your data in a js file, and then simply use `<script src="dataJSON.js" ...` in your pages ?
Comment: so just add them your name! `var jsonDB = {"version": "1.0", "encoding": "UTF-8", "arrays": {...`
Comment: damned, looks like it's working fine after a quick test. So many hours for `var jsonDB=...`... I feel stupid. Thank you Mister Jojo!
Comment: Because the file contains JSON formated data, no javascript. Can't be parsed by the interpreter. Moreover I'd like to keep the extension for my IDE.
Answer: The answer is so simple, I ashamed.

Add a variable declaration at the beginning of the JSON data file.

jsonDB = {"version": "1.0", "encoding": "UTF-8", "arrays": {...

Change the file extension to .js for correct interpretation in the IDE (I'm using Visual Studio Code). Although the IDE is still linting the JSON data correctly (as Javascript variable), there're 2 drawbacks : JSON syntax highlighting is not applying anymore ; Visual Studio Code 'Outline' panel is not usable anymore as the JSON is not interpreted, making navagation within data difficult.
Load the JSON file just like any other javascript file.


When is the setter allowed to leave his position?

Question: Every player has to stay in his position and may not violate the positioning rules until the opponent's server has touched the ball (of course, assuming that the referee has blowed his whistle).
Every setter in every game I've attended on FIVB level leaves his position earlier.
I think this is due to the velocity of the serve, so the setter has enough time to get to the net.
What are the rules in this "violation"? In particular, I am asking for

How many seconds before serving the setter may leave his position?
Is this standardese or FIVB-specific?
Does this only apply to the setter?
Answer: Your first statement is incorrect:

Every player has to stay on his position

There is no restriction on players moving before the serve (at least on the receiving team; the serving team will have to be careful of the screening rules). However, your second statement is correct:

may not violate the positioning rules until the opponent's server has touched the ball

The specific rule is 7.5.1 in the 2015-2016 rules:

The team commits a positional fault, if any player is not in his/her correct
  position at the moment the ball is hit by the server

with the rules for determining whether a player is in his/her correct position in section 7.4. So long as the setter and all other players are in their correct positions at the moment of the service hit, there is no fault even if they are running around like crazy.
Comment: And responding would be kind of you, just so that you know. :-)
Comment: I don't mean the *spot* but the *position*, that is, 1, 2, 3, etc., so my first statement is correct, IMHO. I'm well aware of the positioning system. I am asking for the rules describing setters leaving their position prior to the server touching the ball.
Comment: There are no such rules; see 7.5.1 as I've quoted.
Comment: On YouTube, there are plenty of matches and you can see the setter walking toward the net before the server has hit the ball. I'll provide you a link where it's clearly visible.
Comment: My answer apparently got deleted. Can you tell me why? My question was based on false assumptions, so I do not expect anybody to answer it. And IMHO, your answer does not answer my question. The most expressive comment was "There are no such rules [...]." Anyway, what about the *spot* - *position* thing?


neo4j windows desktop: Unrecoverable authentication error

Question: I run ne04j-desktop-1.0.6-setup.exe to install the desktop neo4j application, and it proceeds through the install up to the point where it opens, and then gives the message (in a red warning rectangle with only a dismiss button) "Unrecoverable authentication error".
How can I find out what the error is and try to fix it?
Answer: I had this problem too, try to put the comptability mode on Windows 7. If it don't work immediatly, try to reload the app by clicking on "Reload" in the "Developper" tab.


Im trying to get the amount of ram of my pc but im not getting the right amount why?

Question: In task manager now i see that in use 4.7gb of ram out of 6gb.
Im using this class to get my ram:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Management;

namespace ScreenVideoRecorder
{
    class GetMemory
    {
        public static List<UInt32> DisplayTotalRam()
        {
            List<UInt32> uints = new List<UInt32>();
            string Query = "SELECT MaxCapacity FROM Win32_PhysicalMemoryArray";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
            foreach (ManagementObject WniPART in searcher.Get())
            {
                UInt32 SizeinKB = Convert.ToUInt32(WniPART.Properties["MaxCapacity"].Value);
                UInt32 SizeinMB = SizeinKB / 1024;
                UInt32 SizeinGB = SizeinMB / 1024;
                //Console.WriteLine("Size in KB: {0}, Size in MB: {1}, Size in GB: {2}", SizeinKB, SizeinMB, SizeinGB);
                uints.Add(SizeinKB);
                uints.Add(SizeinMB);
                uints.Add(SizeinGB);
            }
            return uints;
        }
    }
}

And for the test in Form1 i did :
List<UInt32> uints = GetMemory.DisplayTotalRam();

I see now using a breakpoint in the units List :
index [0] i see: 33554432
index [1] i see: 32768
index [2] i see: 32

In task manager 4.7/6.0 (78%)
So why im getting 32 ? (3.2gb)
Comment: It might be (i'm not sure, never used it) because your app is compiled in "32 bits mode".
Comment: Also, it pays to read the documentation (From MSDN) : **MaxCapacity** - *Maximum memory size (in bytes) installable for this particular memory array.*  This is the max *installable* capacity - not *installed*.  http://msdn.microsoft.com/en-us/library/windows/desktop/aa394348%28v=vs.85%29.aspx
Comment: I would have a look here : http://stackoverflow.com/a/105109/327083  and here : http://stackoverflow.com/a/8463917/327083
Answer: On your system, memory-mapped I/O is taking up the last 0.8 GB of 4 GB of address space, which makes it unavailble to address RAM.  Therefore, when 4 GB of RAM is loaded in the machine, Windows reports that it has only 3.2 GB installed.
There are other systems where that memory-mapped I/O space is pushed out much higher than 4 GB to get around this.  A few years ago I had a Dell laptop with the same issue, so it's not uncommon.


By Central Limit Theorem, is this Normal?

Question: Trying to understand Central Limit Theorem via example.
My question is,

In a simple random sample of $1000$ physicists taken among all
  universities in a country, the number of papers published by the
  sampled physicists in the past year had a mean of $1.1$ and a standard deviation of
  $1.8$.

In this example, does the Central Limit Theorem say that the distribution of the number of papers published by the sampled faculty in the past year is roughly normal?
I know that the sample mean is close to the population mean and can be considered as the population mean. The sample size is also quite large, and I assume it's large enough to say the means are distributed roughly normal by CLT. However, the standard deviation is large. I know that on a normal the standard deviation are $+ - 1$, but i don't know how to use the standard deviation given.
If it's not normal then what shape is it?
Comment: what does SD stand for?
Comment: standard deviation
Comment: The size of the standard deviation does not really matter very much for the normal approximation, mostly because it is "scaled out" of the problem when you take the normal approximation. Specifically the normal approximation tells you that $\frac{\overline{X}-\mu}{\sigma \sqrt{n}}$ is approximately normally distributed with mean $0$ and variance $1$. In your example, $\mu=1.1,\sigma=1.8,n=1000$.
Comment: The standard deviation of a standard normal distributed is $\sigma=+1$. It´s a unique number. The following is not right:"...on a normal the standard deviation are +−1".
Comment: Since the number of papers cannot be negative, it seems "the number of papers" cannot have a "roughly normal" distribution.
Answer: There's no telling what distribution the number of papers per person has. That is not what the theorem is about. Here's the point. Since each value in the data set is a random variable, the sample mean $\overline{X}_n$ is itself a random variable, with an approximately normal distribution provided the sample is large. More precisely, when the sample size $n$ goes to infinity, $$\sqrt{n}\,\frac{\overline{X}_n-\mu}\sigma\to N\left( 0,\,1\right)$$
Comment: Please leave a comment if you downvote. I neutralized the downvote by upvoting.
Comment: I'm confused, if we suppose the number of papers published by the sampled faculty in the past year are i.i.d. and we let $S_n$ be the sum of all or i.i.d events, $X$, then the total number of papers published by the sampled faculty in the past year is roughly normal with mean = $1000 \cdot 1.1$ and standard deviation $\sqrt{1000} \cdot 1.8$. Is this not true by Central Limit Theorem?
Comment: @callculus "Neutralizing" downvotes (or upvotes) by upvoting (or downvoting) is a bad idea, as common sense indicates and as has been discussed several times on meta.
Comment: @Did Sorry, I haven´t known that. But what I know is that it has been discussed the topic downvoting without leaving a comment. Could it be changed  or it is technical impossible ?
Comment: @callculus Yes it was discussed, and the suggestion reappears periodically, with each time the conclusion that it would be impractical. In fact applying it would be a sure way to destroy the SE vote system. (As an aside, let me ask you this: would you be adamant as well that upvoters should leave a comment explaining each of their upvotes? If not, why?)
Comment: @callculus For example, in the present case, upvoters should explain why they think that the sentences "if I pick people at random, the average performance is itself random" and "the sample mean is approximately Normal, provided the sample is large" are useful, although, in every meaning I can give to them, they seem wrong (no, "the sample mean" is not "approximately normal", only the deviations of the sample mean from the mean are, if suitably renormalized).
Comment: @Did Given that $\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}\approx N\left( 0,\,1\right)$, why do you object to the approximation $\bar{X}\approx N \left( \mu,\, \frac{\sigma ^2}{n} \right)$?
Comment: Because the first formulation in your comment is correct while the second one is not. If one insists on stating that $\bar X_n$ converges in some sense, one should stick to the (true) result that $\bar X_n\to\mu$ almost surely. If one wants to state a CLT, one should look at the renormalized $\sqrt{n}(\bar X_n-\mu)$.
Comment: @Did My comment was never about convergence, only about the approximation that follows from it, which is what $\approx$ denotes. Ditto with my answer. The OP wanted to know whether the distribution is Normal (which is a common approximation); I said no, the sample mean is approximately Normal. Restating the convergence result is less likely to correct the misconception than explicitly drawing that contrast.
Comment: The trouble with the statement in your previous coment is that one should give a precise sense to the sign $\approx$ -- and then chaos ensues. To wit, the natural meaning of $U_n\approx V_n$ when convergence in distribution is involved is that $P(U_n<x)\sim P(V_n<x)$ for every fixed $x$, when $n\to\infty$. But then $\bar X_n\approx N(\mu,\tau_n^2)$ for every $\tau_n^2\to0$, not only $\tau_n^2=\frac{\sigma^2}n$... and actually $\bar X_n\approx Y_n$ for every sequence $(Y_n)$ with mean $\mu$ and vanishing variances. So, what is left of the assertion that ...
Comment: ... $\bar X_n\approx N(\mu,\frac{\sigma^2}n)$, one wonders. The other assertion I mentioned (which you do not comment on), stating that "if I pick people at random, the average performance is itself random", is bizarre as well since "the average performance" seems to refer to $\bar X_n$, but then, again, $\bar X_n$ is asymptotically *deterministic*, not random... In both cases, the confusion comes from insisting on stating an approximation result for $\bar X_n$ itself, not for $\sqrt{n}(\bar X_n-\mu)$. I am well aware that this (mis)step is often taken in (some) statistics courses ...
Comment: ... but, first, it is not rigorous, and second, it misleads the students -- hence my suggestion to avoid it altogether.
Comment: @Did I've edited viz. this suggestion.
Comment: Note that the correct normalization is $\sigma/\sqrt{n}$, not $\sigma \sqrt{n}$.
Comment: @Ian No, actually it is $\sqrt{n}(\bar X_n-\mu)$.
Comment: @Did I am talking about in the denominator of the test statistic (so that in the end you wind up with multiplying by $\overline{X}_n-\mu$ by $\sqrt{n}$ as you say). In other words you have either $\frac{\sum_{i=1}^n X_i - n \mu}{\sigma \sqrt{n}}$ or $\frac{\overline{X}_n-\mu}{\sigma/\sqrt{n}}$ as the test statistic. This is a common source of confusion (for example when talking about the normal approximation of the binomial). I tend to suggest that people don't memorize it, and just remember it as "shift and rescale so that the test statistic has mean zero and variance $1$".
Comment: At any rate, what is going on here is exactly like what happens in calculus. To leading order in $n^{-1}$, $\overline{X}_n$ is just $\mu$. The first correction to its distribution is described by CLT. To see this first correction through a limiting process, you must first subtract off the leading order term and then divide by the scale of the correction. This is just like how in calculus, to see the first order correction to $f(x+h)$ in $h$, you have to subtract off $f(x)$ and divide by $h$.
Comment: @Ian Quite relevant analogy. (I corrected the wrong normalization in the post.)


excel sheet creation and update

Question: I am looking for a way to create sheets in excel based on a list of cells
problem I have is that I would like the script to check if the list was updated and add the additional sheets and not re create all or delete the old copies
1) is it possible from excel (non VBA)
2) if not the code i have for creating a sheet is :
 but it will create new entrys if I re-run (and I am looking for update)
Sub AddSheets()
'Updateby Extendoffice 20161215
    Dim xRg As Excel.Range
    Dim wSh As Excel.Worksheet
    Dim wBk As Excel.Workbook
    Set wSh = ActiveSheet
    Set wBk = ActiveWorkbook
    Application.ScreenUpdating = False
    For Each xRg In wSh.Range("A1:A7")
        With wBk
            .Sheets.Add after:=.Sheets(.Sheets.Count)
            On Error Resume Next
            ActiveSheet.Name = xRg.Value
            If Err.Number = 1004 Then
              Debug.Print xRg.Value & " already used as a sheet name"
            End If
            On Error GoTo 0
        End With
    Next xRg
    Application.ScreenUpdating = True
End Sub

Comment: What do you mean by "Updated". Do you just want to run this multiple times, and only add new sheets if it doesn't already exist?
Comment: yes exactly ... and if there is no value in the cell of that range then skip it
Answer: Here's another option. I also added a part where it'll name the sheet the column A value. (You can remove that if needed).
Sub AddSheets()
'Updateby Extendoffice 20161215
Dim xRg     As Excel.Range
Dim wSh     As Excel.Worksheet
Dim wBk     As Excel.Workbook
Set wSh = ActiveSheet
Set wBk = ActiveWorkbook
Application.ScreenUpdating = False
For Each xRg In wSh.Range("A1:A7")
    With wBk
        If Not sheetExists(xRg.Value) and xRg <> "" Then
            .Sheets.Add after:=.Sheets(.Sheets.Count)
            ActiveSheet.Name = xRg.Value
        End If
    End With
Next xRg
Application.ScreenUpdating = True
End Sub

Function sheetExists(sheetToFind As String) As Boolean
'http://stackoverflow.com/a/6040454/4650297
Dim sheet As Worksheet
sheetExists = False
For Each sheet In Worksheets
    If sheetToFind = sheet.Name Then
        sheetExists = True
        Exit Function
    End If
Next sheet
End Function

Answer: Use this function to check if the worksheet already exists, then let it skip over it.
Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

So your code can be:
Sub AddSheets()
    'Updateby Extendoffice 20161215
    Dim xRg As Variant
    Dim wSh As Excel.Worksheet
    Dim wBk As Excel.Workbook
    Set wSh = ActiveSheet
    Set wBk = ActiveWorkbook
    Application.ScreenUpdating = False
    For Each xRg In wSh.Range("A1:A7")
        If Not IsError(xRg) Then
            If xRg <> "" Then
                If Not WorkSheetExists((xRg)) Then
                    With wBk
                       .Sheets.Add after:=.Sheets(.Sheets.Count)
                        ActiveSheet.Name = xRg.Value
                    End With
                End If
            End If
        End If
    Next xRg
    Application.ScreenUpdating = True
End Sub

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

Comment: Why do you have a "do nothing" block? Invert the condition and remove the redundant `Else`! ..and the redundant `Else` in the outer condition, too! ...and fix the indentation, too.
Comment: it works but i get a "type mismatch" error on each execution
Comment: Yup, I just fixed it. I had to change xRg to a variant instead of a range so that the function could take the argument. Try the updated code now.
Comment: Note that `Rx <> ""` will blow up with a *type mismatch* when `IsError(Rx)` is true.
Comment: Ha sorry I tried editing from mobile and the formatting was completely lost
Comment: sorry but not it dosent run at all - with the excel range it did
Comment: The function will never take the argument of the null string, so wheres the concern?
Comment: What null string? If the data (which the procedure doesn't control and is subject to user's whim) contains `#REF!` errors, or any other error value, comparing such a range against an empty string raises a run-time error (and ultimately spawns a new Stack Overflow question, that then gets closed as a duplicate).
Comment: Ah I see. I interpreted what he said earlier of a cell having "no value" as being blank. That being said, I'd hope he's using ISERROR to negate those #REF cells. Sorry, posting from mobile is tough-

excel sheet creation and update


How can I query on a custom content entity base fields?

Question: I am trying to write a entityQuery and add condition on the base fields I've defined.
The query:
$query = \Drupal::entityQuery('map_object')
    ->condition('body', 'Test')->execute();

And the error:
Drupal\Core\Entity\Query\QueryException: 'body' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

The definition:
    $fields['body'] = BaseFieldDefinition::create('text_long')
      ->setLabel(t('Body'))
      ->setDescription(t(''))
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'text_textfield',
        'weight' => 9,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

The column "body" does exists in the entities base table.
Comment: try to reinstall your module
Comment: Try running `drush entity-updates`
Comment: The entity needs no updates it says. @Clive
Comment: Reinstalling module didn't work either @AdrianCidAlmaguer
Comment: drush entity-updates is no more working with drupal 8.7
Answer: I was missing data_table in the Entity annotation. By adding that and update the entity it allowed me to query as expected.
 *   base_table = "map_object",
 *   data_table = "map_object_field_data",


How to flatten the result of a groupby operation in Pandas?

Question: Using a Pandas dataframe, is there a way to flatten the result of a groupby operation without having to use a temporary dataframe and then merge it to the original one?
Let's say I need to create a "result" column which depends on an aggregating operation, like in this scenario:
import pandas as pd

df = pd.DataFrame({'box': [1,1,1,2,2,3,3,3,3], 'item': ['apple', 'durian', 'pear', 'orange', 'banana', 'apple', 'pear', 'durian', 'orange']})

df['subindex'] = df.groupby('box').cumcount()+1

tmp_df = df.groupby('box')['subindex'].apply(lambda x: (1/x**2).sum()).reset_index(name='result')

df = pd.merge(df, tmp_df, how='inner', on='box')

Is there a way I can achieve the same thing in the last two lines in one line of code only, without having to merge two distinct dataframes?
Answer: We can combine two steps into one
df['result']=(df.groupby('box').cumcount()+1).groupby(df['box']).\
                  transform(lambda x : (1/x**2).sum())
0    1.361111
1    1.361111
2    1.361111
3    1.250000
4    1.250000
5    1.423611
6    1.423611
7    1.423611
8    1.423611
dtype: float64

Answer: As @YOBEN_S points out you can combine in to one statement, however the key to what you are looking for is transform.
import pandas as pd
df = pd.DataFrame({'box': [1,1,1,2,2,3,3,3,3], 'item': ['apple', 'durian', 'pear', 'orange', 'banana', 'apple', 'pear', 'durian', 'orange']})
df['subindex'] = df.groupby('box').cumcount()+1
df['result'] = df.groupby('box')['subindex'].transform(lambda x: (1/x**2).sum())
print(df)

Output:
   box    item  subindex    result
0    1   apple         1  1.361111
1    1  durian         2  1.361111
2    1    pear         3  1.361111
3    2  orange         1  1.250000
4    2  banana         2  1.250000
5    3   apple         1  1.423611
6    3    pear         2  1.423611
7    3  durian         3  1.423611
8    3  orange         4  1.423611

transform takes a column and applies as a function to that column and transforms those values into different values but it keeps the same shape and order of the original dataframe.


Objects in object oriented programming in objective c

Question: Newbie programmer here who has programmed in C before and I am now starting to learn object oriented programming since I want to program for iOS in the future.  I've read the Apple documentation and most of it is crystal clear, except that I am having trouble understanding objects, which are obviously supposed to be basic knowledge.  The Apple documentation reads as follows:
"All members of a class are able to perform the same methods and have matching sets of instance variables.  Two objects with equivalent data structures but different methods would not belong to the same class."
So my question is, if all objects have shared methods, and all objects have matching sets of instance variables, then what on earth is the difference between objects within the same class??  I thought objects were composed of just instance variable and methods
Thanks to anyone who answers
Comment: Objects do have ivars of their own. Although objects of the same class share the same methods (interface) and the same set of ivars, their ivars can have different values.
Comment: For most objective-C objects, code is shared, memory isn't.  Two objects of the same class will each have their own instance variables, but they will point to the same class to look up the code for  any messages  you send them.
Answer: I think your misunderstanding comes from Apple's use of the language "matching sets". An instance of a class has the same methods as every other instance and its own set of instance variables. So each instance is distinct from every other instance.


How to create User Account Registration form with Webform?

Question: I am using Drupal 7. I have Webform with 6 fields:

Your name
User name
password
Email
phone number
Website

If we submit it will store in database, but here I need username & password should store in "User Account Registration" form also.
We can add fields from Configuration -> People -> Account settings for other fields, but it doesn't work in this situation. I need to store the User name & password values to "User Account Form" and then to login with that username and password.
Comment: what is the reason for not using the profile fields instead of webform?
Answer: Storing the password as a regular Webform field is not nearly as secure as using Drupal's built-in user registration password. I would recommend instead of trying to create user registration via Webform, that you use something like Profile 2 to add additional information fields to the core registration form.
Comment: Is there no way to change the  #5 or #6].
Comment: Changing the input type of the HTML form element will cause it to display dots or stars rather than the characters being typed, but it won't affect the way Drupal stores the input in the database. The password field is stored (I believe) as a salted hash rather than as plaintext.
Comment: E-mailing passwords in plaintext is very bad security practice. A one-time token-protected link that allows the user to reset their password is preferred.


Prove that the associative property works when composing functions

Question: How do I show that if $h,g,f$ are functions, then $h\circ (g\circ f) = (h\circ g) \circ f$??
Comment: This is associativity. Not distributivity.
Comment: Are you aware of how to show that $(h\circ (g\circ f))(x) = h(g(f(x)))$?
Comment: Let x be an element.  Then y = f (x) is distinct.  And w=g(y) is distinct.  And z=h (w) is distinct. So $ h (g (f (x))=h\circ (g\circ f)(x)=z$.  And $h \circ g (y)=h (w)=z $ but $h\circ g (y)=[(h\circ g)\circ f](x) $.  So $h\circ (f\ circ g)(x)=(h\circ g)\circ f (x) $.
Answer: If you mean associativity, then it is mostly just writing down the definition of composition.
$$h((g \circ f)(x)) = h(g(f(x))) = (h \circ g)(f(x))$$
Answer: Let $x$ be arbitrary.  Let $f(x) =w$ which is distinct.  Let $g(w) = y$ and $h(y) = z$.
Then $(h\circ (g\circ f))(x) =h ((g\circ f)(x))=h (g(f(x)) = h (g(w))= h(y) = z$
And $z = h(y) = h(g(y)) = (h\circ g)(y) = (h\circ g)(f(x)) = ((h\circ g)\circ f)(x)$
So $(h\circ (g\circ f))(x)= ((h\circ g)\circ f)(x)$
Answer: First, observe that $g\circ f$ exists iff the image of $f$ is a subset of the domain of $g$, an then the domain of $g\circ f$ is the domain of $f$, and the image of $g\circ f$ is a subset of the image of $g$. In particular, assume that $(h\circ g)\circ f$ exists. Then obviously $h\circ g$ exists, and furthermore the image of $f$ is a subset of the domain of $h\circ g$. But the domain of $h\circ g$ is the domain of $g$, and therefore we get that $g\circ f$ exists. Now the image of $g\circ f$ is a subset of the image of $g$, which as we've seen is a subset of the domain of $h$. Therefore, since the subset relation is transitive, the image of $g\circ f$ is a subset of the domain of $h$, and thus $h\circ(g\circ f)$ exists and has the same domain.
An analogous argument shows that if $h\circ(g\circ f)$ exists, then so does $(h\circ g)\circ f$ with the same domain. What remains is to show that the function values are equal for all elements of that domain.
By definition, $(g\circ f)(x) = g(f(x))$ for all $x\in \mathrm{dom}(f)$. Therefore for any such $x$, we have
$$(h\circ(g\circ f))(x) = h((g\circ f)(x)) = h(g(f(x))) = (h\circ g)(f(x)) = ((h\circ g)\circ f)(x)$$
This concludes the proof.


Passar dado de um componente para outro em angular

Question: Tenho um componente que mostra uma imagem e um outro componente que deve alterar o src dessa imagem.
Tentei fazer o seguinte:
Perfil.component.ts
<code> alteraDadosPerfil(){

    this.perfilService.alteraDadosPerfil(this.perfil,this.croppedImage)
      .pipe(
        take(1)
      )
      .subscribe((res) => {

        if(this.croppedImage != null){ //Se foi alterado imagem então guarda a foto no localstorage e chama o método do serviço que altera a foto de perfil
          localStorage.setItem('foto', this.croppedImage);
          this.perfilService.alteraFotoPerfil(this.croppedImage);
        }
      },
      (err: HttpErrorResponse) => {
      })
    }
</code>
Perfil.service.ts
<code>fotoPerfil: Subject<any> = new Subject<any>();

  alteraFotoPerfil(base64Foto: string){
    this.fotoPerfil.next(base64Foto);
  }

Home.component.ts

avatarPerfil: string = null;

 ngOnInit(){

    this.avatarPerfil = localStorage.getItem('foto');
    this.nomeUsuarioLogado = localStorage.getItem('nome');
    this.emailUsuarioLogado = localStorage.getItem('emailUsuario');

    this.perfilService.fotoPerfil.subscribe(res => { //Não está entrando aqui dentro
      this.avatarPerfil = res
   })
  }
</code>
Comment: Remova o serviço de ambos e coloque somente no providers do módulo raiz da sua aplicação
Comment: Onde você está chamando o método alteraFotoPerfil?
Comment: É em uma função, eu sei que está chegando nessa função porque se eu colocar um console.log('teste') é printado no momento correto, mas por algum motivo o subscribe não recebe a alteração
Comment: Você está usando o Subject?
Comment: Sim, no perfilService eu declarei: fotoPerfil: Subject = new Subject();
Comment: Será que você não está chamando o unsubscribe em algum lugar antes?
Comment: eu não uso unsubscribe
Comment: Adiciona todo seu código envolvido no problema.
Comment: Em qual módulo está o Service?
Comment: Alterei a pergunta adicionando todo o código
Comment: O serviço é importado e adicionado no providers dos dois módulos (HomeComponent que é o componente que deve receber a foto de perfil e no componente PerfilComponent que deve mandar o dado para o homeComponent)
Comment: Isso funcionou, alguma explicação pra isso? Adicione uma resposta explicando para que eu possa dar como a resposta correta.
Comment: Sim, só um momento
Answer: No Angular temos o Injector que é responsável por criar o serviço e injetá-lo nos componentes. Todo o serviço é um singleton para o Injector. Quando você adiciona o serviço no módulo principal, você está registrando o serviço no Injector raiz da aplicação, ou seja, há somente um PerfilService para toda a aplicação, todos os componentes irão obter a mesma instância, a não ser que o serviço seja registrado em algum módulo filho ou componente, como o foi o caso do problema mencionado nos comentários, onde cada componente tinha uma instância diferente do serviço.
Recomendo a leitura: https://angular.io/guide/dependency-injection


Auto-populating Storm Invoice

Question: I'm using Storm for a bunch of its varying functionality, and figure it thus makes sense to use its Invoice module as the final part of a multi-part project (see previous SO post).
Everything in Storm Invoice seems like it needs to be entered on the fly, all the time. What I need to have happen is for a computed field from another node or a view to provide a price to the Invoice module, autopopulating some fields. Is this at all possible with Storm Invoice?
Addendum: If Storm isn't the best way to create dynamically-generated invoices from node CCK fields, please suggest an alternative.
Comment: Remember to link to projects like [Storm](http://drupal.org/project/storm), especially if they're not well known projects like Panels, Views, etc. That'll make it a lot easier to figure out what you're talking about.
Answer: I'm not sure but maybe the Computed Field can be used, you can even use it to fill another field.
If you are ready for some custom code (although Computed Field will probably require some code too), you can implement hook_nodeapi() when $op == 'prepare'(or hook_prepare() in Drupal 7). There you can pre-fill new Invoice node (when $node->nid is not set, the node is being created).
Answer: It isn't currently possible to auto-fill these fields in Storm Invoice.
If you're still looking to do this (realise this is an old question), then ask over at the issues queue and we can help find a solution.

Auto-populating Storm Invoice


Need to correct :checked event in css

Question: This is my code:

ENGLISH GRAMMAR
<input type="checkbox" id="drop-123" />

This text needs to be visible

This text needs to be visible text is to be visible  after clicking on ENGLISH GRAMMAR .But I am not being able to figure out my fault.
Answer: Can you please try adding it this way.
[id^=drop]:checked + #hot  {
  display: block
}

Answer: This has more to do with CSS specificity.
#hot{
display:none;
}
[id^=drop]:checked + div#hot { display: block; }

#id is more specific than the div tag.
Read
Answer: Use
#drop-123:checked + div {display:block;}
Comment: But I want use regular expression

Need to correct :checked event in css


Including images to HTML

Question: I'm trying to upload a particular image on my HTML. The image is in the same folder, the HTML file is also in the same folder. However, it still doesn't show me the image when I access the image on HTML.
The code for the image tag in HTML is:

Thanks in advance.
Comment: This should work, is the image named `Layout.jpg`?
Comment: You should have a closing `/`: ``. Furthermore, check the case of the file on the server - Windows servers ignore case, but Linux ones don't.
Comment: Tried both. Doesn't work :/. Also tried the closing /. Doesn't work
Answer: This will depend on your server. If your webpage is located at http://example.com/path/to/my/html, does the corresponding URL http://example.com/path/to/my/Layout.jpg work? It is possible that the server that you are using needs additional configuration to route the URL to the underlying image file. More details regarding your specific server / hosting platform would be needed to diagnose the issue.
Comment: The file is local. The server is on a Windows machine. I'm only trying to render an image by using     which means I'm trying to reference an object of jpg type in the same folder the html is in.
Comment: But which kind of server? For example, some servers need to be configured to serve files other than ones matching *.html. You may also need to look at the permissions of the file (if the file is not readable by the server, then there is no way for the server to read and render it).

Including images to HTML


Express res.write not waiting for array of promises to finish

Question: code
const upsertAll = async (types) => {
  let jobs = []
  types.map(type => {
    if (type == "1") jobs.push(asyncFunction1)
    if (type == "2") jobs.push(asyncFunction2)
    if (type == "3") jobs.push(asyncFunction3)
  })
  jobs.reduce((p, fn) => p.then(fn), Promise.resolve())
}

router.get('/api/generate', async (req, res) => {
  res.write(`${new Date().toISOString()} Generating metadata. Please wait...`);
  const filter = req.query.q.split(',');
  await upsertAll(filter)
  res.write(`${new Date().toISOString()} Done`);
  res.end();
});

I want to wait for all promises to complete one-by-one (sequentially like in a series manner)
Then I want express to send the second response message and end
But its not working, all res.write() messages are printing at the same time while the promises have not completed yet
i have also tried wrapping
res.write(`${new Date().toISOString()} Done`);res.end();

in a upsertAll(filter).then(() =>{}) block but it does not work
related thread 1 res.send is not waiting for my async function to finish before sending the response to the front end on my Express server app
related thread 2 https://dev.to/afifsohaili/dealing-with-promises-in-an-array-with-async-await-5d7g
Comment: see this example: https://playcode.io/791798/ your using map and reduce for no good reason
Comment: oh right yeah it wouldn't output until res.end is called after all middleware are called, it would be hanging until then, you prob want to use a web socket or SSE if you want a stream of text
Comment: map? use a simple for loop and actually call the function  `jobs.push(await asyncFunction1())`
Comment: the function calls do happen in async on the reduce line but the router method doesnt work as expected
Comment: link is back. thanks for the example. implementation works with console log statements but in my use case for some reason it does not work with express res (maybe process is blocking). I hit the endpoint and the method gets called but the first res.write never appears on the browser page. during the async, the page is still loading as the tab wheel icon is still spinning. only after the async finishes, the response messages render on the page
Answer: try for loop instead
const upsertAll = async (types) => {
  let jobs = []
  for (let i = 0; i < types.length; i++) {
    const element = types[i];
    if (type == "1") jobs.push(asyncFunction1)
    if (type == "2") jobs.push(asyncFunction2)
    if (type == "3") jobs.push(asyncFunction3)
  }
  const end = await Promise.all(jobs);
  return end
}

or
const upsertAll = async (types) => {
  let jobs = []
  for (let i = 0; i < types.length; i++) {
    const element = types[i];
    if (type == "1") jobs.push(await asyncFunction1)
    if (type == "2") jobs.push(await asyncFunction1)
    if (type == "3") jobs.push(await asyncFunction1)
  }
  return jobs
}


Fancybox AJAX - how to close dialog after postback

Question: I have a link on my ShowData.aspx page that I'm calling fancybox on.
Edit Data
My JQuery code is:
$("#editLink").fancybox({
                        'opacity': true,
                        'overlayShow': true,
                        'transitionIn': 'elastic',
                        'transitionOut': 'none'
                    });

The form EditData.aspx contains a save button. My problem is that after I click the save button the dialog does not close. Furthermore, after the save is performed on the server the client page redirects to EditData.aspx.
The expected outcome is that the dialog closes and I am returned to the parent page (ShowData.aspx).
Thanks!
Comment: Check your console. I bet there's an error elsewhere in your script.
Comment: Does that mean what I have is suppose to work as described? Don't I have to wire up the "close dialog" after the post back occurs? I'll check my console.
Comment: No console errors. I also noticed that the datepicker control does not work either. None of the JQuery stuff in EditData.aspx works when hosted in an ajax dialog.
Answer: I removed fancybox and found that this issue also occurs with regular JQuery dialogs. If you load a page that has a submit button (or posts back in any way) then your dialog will disappear and your main page will redirect to the dialog page. Here's a simple test:
HTML:

JQuery:
$(function () {
            $("#divClick").dialog({
                modal: true,
                open: function () {
                    $(this).load('Postback.aspx');
                },
                title: 'Ajax Page'
            });
        });

Postback.aspx:

    <form id="form1" runat="server">

    Enter Name:
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </form>

Is there a way to attach an event to the postback from the dialog?
Furthermore, I modified Postback.aspx to include jscolor.js (a JQuery plugin) to see if it would work, it did not work. Any JQuery functionality doesn't seem to work in a dialog.
Answer: I ended up using an iFrame. This seems to do the job.
MainPage.aspx

JQuery:
 $(function () {
       $("#divClick").dialog({
          modal: true,
          title: 'iFrame Page',
          width: 500,
          height: 500
       });
   });

JQuery plugins in Postback.aspx work well and posting back doesn't close the dialog and redirect the main page.


How to access jQuery plugin added through libraries API

Question: I'm working on a Drupal 7 module to integrate an existing jQuery plugin (smallworld.js). I've added it successfully through the Libraries 2.x API in my module:
<code>$libraries['smallworld.js'] = array(
    'name' => 'SmallWorld.js',
    'vendor url' => 'http://mikefowler.me/smallworld.js/',
    'download url' => 'https://github.com/mikefowler/smallworld.js',
    'version' => '1.0', //no version actually defined in code
    'files' => array(
      'js' => array('src/smallworld.js'),
      'js' => array('src/smallworld.jquery.js'),
    ),
  );
</code>
and have confirmed that the files are loading correctly. However, when I try and access the file in my Drupal jQuery, ex:
<code>(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) {
      $.getJSON('/sites/all/libraries/smallworld.js/dist/world.json', function (data) {
        $('.map').smallworld({
          geojson: data,
        });
      });
    }
  };
}(jQuery));
</code>
It doesn't trigger, giving me the console error message "Smallworld is not a constructer."
The two files it is loading are the Smallworld library and a smaller jquery wrapper that registers the library as a jquery plugin:
<code>  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {
        $(this).data('smallworld', new Smallworld(this, opts));
        return this;
      });
    }
  });
</code>
Does this wrapper also needed to be added to the same Drupal jquery namespace? If a jquery library is added through Libraries API, is there special namespacing to consider when accessing it?
Comment: You did not say what went wrong. It seemed like you were heading that way after the second code example. Did you load the library on the page to be output or attach it to a render array? Is there a browser console error?
Comment: absolutely right @cilefen, I've updated it with the console error I am seeing and the code for the wrapper that I am guessing is the problem.
Comment: Are src/smallworld.jquery.js and src/jquery.js added to the page after jquery.js?
Comment: @cilefen - yes, checking the network pane in chrome debugger shows both files loaded after Drupal loads jquery.js
Answer: Found the problem - this library comes with two separate files, one that is a straightup javascript library and another in jquery that registers the file as a plugin (smallworld.jquery.js)
<code>  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {

      $(this).data('smallworld', new Smallworld(this, opts));
      return this;
    });
</code>
To get this to work, I had to take the whole 'register' script and add it to the jquery file script I created for the module, ex:
<code>(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) { ...
</code>


EDIT: ODE Derivation

Question: Let
$k'(t)=sAk(t)^{\alpha}-(n+{\delta})k(t)$.
Substitute
$x(t)=k(t)^{(1-{\alpha})}$.
One obtains the linear ODE
$x'(t)=(1-{\alpha})sA-(1-{\alpha})(n+{\delta})x(t)$.
How do we get there step-by-step; I'm confused in particular about the coefficient $(1-{\alpha})$?
Thank you for your help!
Comment: This is a Bernoulli type ODE. Look it up on wikipedia they should have a detailed derivation.
Answer: Consider the equation
$$
k'(t) = sA[k(t)]^a - (n + \delta)k(t)\tag 1
$$
Putting
$$
x(t) = [k(t)]^{1-a}\tag 2
$$
Differentiating (Derivative of Composite Functions/Chain Rule) we find
$$
x'(t)=(1 - a)[k(t)]^{1-a-1}k'(t)=(1 - a)[k(t)]^{- a}k'(t)
$$
and multiplying by $[k(t)]^{a}$
$$
x'(t)[k(t)]^{a}=(1 - a)k'(t)
$$
that is $$k'(t)=\frac{x'(t)[k(t)]^{a}}{(1 - a)}\tag 3$$ and substituting (3) in (1) we have
$$
\frac{x'(t)[k(t)]^{a}}{1 - a}= sA[k(t)]^a - (n + \delta)k(t)
$$
Dividing by $[k(t)]^{a}$ and multiplying by $1-a$ we have
$$
x'(t)= (1 - a)sA[k(t)]^a[k(t)]^{-a} - (1 - a)(n + \delta)k(t)[k(t)]^{-a}
$$
and observing that $k(t)[k(t)]^{-a}=[k(t)]^{1-a}=x(t)$ we finally have
$$
x'(t)= (1 - a)sA - (1 - a)(n + \delta)x(t)
$$
Comment: Quite a clear one after all; Thanks!

EDIT: ODE Derivation


Is weather.com still running Drupal?

Question: There have been news items in 2013 about weather.com moving to Drupal. I have been reading How to tell if a site is using Drupal 7 and I have been unable to find out if the site is still running on Drupal.
How can I find out if weather.com is still running Drupal?
Comment: see: https://austin2014.drupal.org/session/migrating-worlds-largest-website-drupal-weathercom
Comment: This question appears to be off-topic because if you check http://drupal.stackexchange.com/help/on-topic all on topic questions are about something you want to do.
Comment: Welcome to Drupal Answers! I am sorry, but we are not going to open a new question for each site that could use Drupal.
Answer: I use buildwith chrome plugin and Appspector, it does not looks like they use drupal CMS.
Answer: There is usually some CDATA starting with
<code><!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings
</code>
Or the files and folders are in a /sites/all/.. directory that are the major drupal give aways.
It does not look like weather.com uses drupal.
Answer: Is not Drupal. IMHO is a custom php framework based on YUI library.

Is weather.com still running Drupal?


Isomoprhic and equal symbol for abelian groups

Question: Let $A$ and $B$ be two abelian groups and $A$ and $B$ are isomorphic. Moreover suppose that $A$ and $B$ are not the subgroups of the same group. Is it correct to write $A = B$? Thank you.
Comment: Definitely no. {}{}{}
Comment: When they are equal, meaning having the same elements.
Comment: @ Rubertos, Thank you. I was wondering, is there some situation where we can write equal?
Answer: You should never, ever claim the statement "$A=B$" is true unless $A$ is literally, element-for-element, the same thing as $B$...
... until you are mathematically experienced enough to abuse the notation $=$ responsibly.
Comment: While abuse of notation is fine in certain things, I hold that this is not one of them (but I didn't downvote).
Comment: Responsible use would at least require the groups to be *canonically* isomorphic, I suppose
Comment: @ Thank you Zev Chonoles. This makes sense.
Comment: $A = B$ is the assertion that $A$ and $B$ are equal. It is perfectly correct to use this expression when it is false, as in "Assume, for a contradiction that $A = B$, ..."
Comment: @Rob: Well, I don't disagree, though I feel it's *implied* that I only meant "saying the statement is true". Nevertheless I've edited.
Answer: Definitely no. Even more, the collection of all groups isomorphic to an abelian group $G$ is a proper class.
Let $G$ an abelian group and $X$ be a set.
Then, you can define a natural operations on $G\times\{X\}$ so that $G\cong G\times \{X\}$. ( Define as $(g,X)(h,X)=(gh,X)$)
So for different two sets $X,Y$, $G\times \{X\}\cong G\times \{Y\}$, but they are obviously not equal.
Comment: @ Rubertos Thank you. I got it.
Comment: What has the fact that that an isomorphism class of groups is a proper class got to do with the legitimacy or truth of the assertion that $A = B$ for two particular groups?
Comment: @RobArthan I just wanted to emphasize that "set equality" is a completely different matter..
Answer: It is certainly correct to write $A = B$, in the same way that it is perfectly correct to write $1 = 2$. These are meaningful statements even if they are false.
That said, if you want to assert that $A$ and $B$ are isomorphic, then the standard notations are $A \simeq B$ or $A \stackrel{\sim}{=} B$ and not $A = B$.
Comment: Why the down vote?
Comment: @ Thank you Rob Arthan. I got it (But the down vote not by me. )


Run SpringLiquibase BEFORE Hibernate

Question: I'm using SpringLiquibase to apply my liquibase update automatically during the application startup. In general this works fine, but when I set hibernate.hbm2ddl.auto to "validate" then hibernate starts to complain about the database scheme before liquibase seems to have the chance to apply the updates.
My configuration looks like this:
<code>@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = "com.myapp")
@PropertySource(value = {"classpath:myapp.properties"})
@EnableJpaRepositories("com.myapp")
public class MyappConfig {

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driver"));
        dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(env.getRequiredProperty("jdbc.password"));

        return dataSource;
    }

    @Bean
    public SpringLiquibase liquibase() {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(dataSource());
        liquibase.setChangeLog("classpath:liquibase/liquibase-master-changelog.xml");
        return liquibase;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("com.myapp");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();

        String[] propertyNames = new String[]{"hibernate.dialect", "hibernate.show_sql", "hibernate.hbm2ddl.auto"};

        for (String propertyName : propertyNames) {
            properties.put(propertyName, env.getRequiredProperty(propertyName));
        }
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

}
</code>
Is there any way to get liquibase to apply its updates BEFORE hibernate tries to validate the schema?
Comment: You might try adding a `@DependsOn("liquibase")` to your `entityManagerFactory` bean definition.
Comment: How can i do the thing with `@DependsOn("liquibase") ` if I have the beans declared in `applicationContext.xml` ?
Comment: @MoroianuAlexandru you can move the config of liquibase to applicationContext.xml too
Comment: Thanks @M. Deinum & VinhNT I solved it by applying depends-on in applicationContext.xml... defined following code in xml: `` [...]
Answer: Thanks to  M. Deinum I was able to solve this by using
<code>@Bean
@DependsOn("liquibase")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
   [...]
}
</code>
The <code>@DependsOn</code> makes sure that liquibase is run before Hibernates schema validation.
Comment: How do I do this in Spring-Boot using Spring-JPA? When I do mvn install, liquibase is getting executed first. But when I start application, hibernate ddl is run first.

Run SpringLiquibase BEFORE Hibernate


Erro ao acessar alteração de Estado que possui um País

Question: Eu tenho um cadastro de estado, que possui um País. Ele cadastra normal, só que ocorre erro ao acessar a alteração do estado.

Não sei se está correto, mas pelo que eu entendi, algo do país está vindo vazio. Como que eu corrijo isso. Eu não estou conseguindo.
A arquitetura que estou utilizando é a MVC. e estou programando em Delphi.
No meu sistema, todos os cadastros que possuem outros cadastros, ocorre esse erro.
Tanto que no cadastro de cidade, eu nem consigo adicionar o estado porque ocorre esse mesmo erro, mas falando do estado.
DAO ESTADOS:
function daoEstados.carregar(pObj: TObject): string;
var mEstado : Estados; mPais : Paises;
begin
  mEstado:= Estados( pObj );
  mPais:= mEstado.getoPais;

  mEstado.setCodigo( aDM.QEstados.FieldByName('CODESTADO').Value );
  mEstado.setEstado( aDM.QEstados.FieldByName('ESTADO').AsString );
  mEstado.setUF( aDM.QEstados.FieldByName('UF').AsString );

  mPais.setCodigo( aDM.QEstados.FieldByName('CODPAIS').Value );
  mPais.setPais( aDM.QPaises.FieldByName('PAIS').AsString );
  mPais.setDDI( aDM.QPaises.FieldByName('DDI').AsString );
  mPais.setSigla( aDM.QPaises.FieldByName('SIGLA').AsString );

  mEstado.setDataCad( aDM.QEstados.FieldByName('DATACAD').AsDateTime );
end;

Na CONTROLLER ESTADOS:
function ctrlEstados.carregar(pObj: TObject): string;
var mPais : Paises; AFilter: TFilterSearch; tipoConsulta : TTipoConsulta;
begin
  aDaoEstados.carregar( pObj );

  mPais:= Estados( pObj ).getoPais;
  aCtrlPaises.pesquisar(AFilter, IntToStr(mPais.getCodigo));
  aCtrlPaises.carregar( oEstado.getoPais );
end;

Ela chama o método pesquisa da controller país, que chama da dao:
msql:= '';

case AFilter.TipoConsulta of

 TpCCodigo:
 begin
   msql:= 'SELECT * FROM PAISES WHERE CODPAIS =' + IntToStr(
   AFilter.Codigo );
 end;

 TpCParam:
 begin
   msql:= ( 'SELECT * FROM PAISES WHERE PAIS LIKE ' + QuotedStr(
 '%' + AFilter.Parametro + '%' ) );
 end;

 TpCDDI:
 begin
   msql:= ( 'SELECT * FROM PAISES WHERE DDI LIKE ' + QuotedStr(
 '%' + AFilter.DDI + '%' ) );
 end;

 TpCMoeda:
 begin
   msql:= ( 'SELECT * FROM PAISES WHERE MOEDA LIKE ' + QuotedStr(
  '%' + AFilter.Moeda + '%' ) );
 end;

 TpCTODOS:
 begin
   msql:= 'SELECT * FROM PAISES ORDER BY CODPAIS';
 end;

end;

aDM.QPaises.Active:= false;
aDM.QPaises.SQL.Text:=msql;
aDM.QPaises.Open;
result:= '';

Nesse método pesquisar, fiz um case para saber o tipo de filtro que está selecionado para consulta.
Só que quando chega nessa parte:
aDM.QPaises.Open;

É que ocorre o erro.
Comment: Qual código que ao ser executado gera esse erro?
Comment: Ocorre erro na Dao País. AQUI
    aDM.QPaises.Active:= false;
    aDM.QPaises.SQL.Text:=msql;
    aDM.QPaises.Open; -> AQUI
    result:= '';
Na Controller Estado tem esse método:
function ctrlEstados.carregar(pObj: TObject): string;
var mPais : Paises; AFilter: TFilterSearch; tipoConsulta : TTipoConsulta;
begin
  aDaoEstados.carregar( pObj );
  mPais:= Estados( pObj ).getoPais;
  aCtrlPaises.pesquisar(AFilter, IntToStr(mPais.getCodigo));
  aCtrlPaises.carregar( oEstado.getoPais );
end;
Ele acessa o método pesquisar da controller, que nele vai chamar a pesquisa da DAO do País.
Answer:
Não sei se está correto, mas pelo que eu entendi, algo do país está
vindo vazio. Como que eu corrijo isso. Eu não estou conseguindo.

A mensagem de erro apresentada:

Comand [QPaises] text must be not empty

Traduzindo a mensagem de erro apresentada, temos:

O texto do comando de QPaises não deve estar vazio.

O Problema:
O problema é que a variável msql não está recebendo um novo valor, essa variável inicia vazia e caso não satisfaça a condição case AFilter.TipoConsulta of, não receberá uma novo valor, permanecendo vazia.
Uma possível correção:
Para corrigir, na controller país inicie a variável de forma genérica:
substitua o trecho:
msql = '';

por
msql = 'SELECT * FROM PAISES';

Dessa forma, se alguma condição não satisfizer o case, você terá uma consulta padrão a ser executada.
aDM.QPaises.Active:= false;
aDM.QPaises.SQL.Text:=msql;
aDM.QPaises.Open;

Como não estava fazendo nenhuma verificação antes de atribuir o msql, tudo indica que está sendo atribuído um valor vazio e o erro está sendo gerado.
Outra correção possível:
aDM.QPaises.Active:= false;
if msql <> '' Then
   aDM.QPaises.SQL.Text:=msql
else
   aDM.QPaises.SQL.Text:= 'SELECT * FROM PAISES';  //Sua consulta padrão
aDM.QPaises.Open;

Comment: Muito obrigada. Deu certo. Nossa que alívio kkkkkk


Retirar ?resize= da url da imagem

Question: Após alguns testes com o gtmetrix percebi que as imagens demoram para carregar quando são redimensionadas a partir da url, com o método "?resize=(dimensões)" no final da mesma.
Exemplo:
meudomininio.com/imagem.jpg (20ms)
meudomininio.com/imagem.jpg?resize=100,400 (500ms)
A minha pergunta é como desativar essa configuração, visto que o desempenho do site cai.
Uso o wordpress. Plugins EWWW e Fastern Cache ativados, .htacess configurado
Answer: A regra geral é remover todos os plugins suspeitos (como os que você citou) e ver se o problema persiste. Caso resolva, adicione um por um novamente até achar o "culpado".
Uma vez achando o plugin que está causando a lentidão, busque infos dele e tente achar a configuração para não gerar thumbs dinamicamente. Muitos usam a biblioteca "timthumb".
Caso não dê certo, tente achar por algum redirecionamento configurado em seu .htaccess, será algo parecido com isso:
<code>RewriteRule ^images/([0-9]+)/([a-z0-9.]+)?$ /tt.php?src=/images/$2&w=$1
</code>
Resolvido
O plugin "Jetpack" estava sendo utilizado. Ele é o responsável por colocar esse "?resize=(dimensões)" na url quando o otimizar imagem está ativado. Desativando essa função resolveu o problema.
Answer: Utilizo o Wordpress. Descobri que o plugin "Jetpack" é o responsável por colocar esse "?resize=(dimensões)" na url quando o otimizar imagem está ativado.
Então desativei essa função do plugin e tudo foi resolvido.

Retirar ?resize= da url da imagem


Repeat LAST action from Jubula Testcase

Question: I am using Jubula to test a big softwaretool. Since the UI got updated Jubula has some big problems. The test quit's at a position (let's say after Step A), after I was trying to figure out whats the problem, I didn't find a problem and Jubula quits at a totally different position, some times before and some times after position A. It's seams to be really random if, and if, where it quits.
Now I got known to the eventhandler (before, I never was used to use them). Since there are much testcases and in every Testcase much much actions (at least 50) and Jubula is always "stopping" at different, the problem is not solved to add an eventhandler which always does the same thing (lets say clicks on a button) because some times Jubula shall click on button A and some times on B, in other cases he has to select something from a "dropdown-menu".
NOW my question: Is it possible to force Jubula, to repeat the LAST DONE action?
Since I started to watch closely on the reports, I noticed that the buttons are already displayed and jubula just doesn't click on them. (i tried to wait until they appear before i click on 'em, but it still didn't work)
I would be really really happy if there is a solution (even if it's "difficult" or hard to realize because I need to add much components.)
Answer: There is a "difficult" solution, if you know how to build Jubula from it's sources.
Jubula does not have a STEP_BACK event handler so you have introduce a STEP_BACK entry in ReentryProperty.java. After that, modify Traverser.java next() method to handle this new entry. You could also contact Bredex GmbH with such a feature request, they quickly respond to every mail.
But I would rather try to make sure Jubula finds those buttons; create a custom case (i.e. Sure_Click) that clicks on button but has a RETRY event-handler with a few hundred millisecs holdback.
If you have access to the AUT's code then try setting setData("TEST_COMP_NAME", "unique_id") for each widget Jubula has to find. It is the most/only stable way to locate widgets.

Repeat LAST action from Jubula Testcase


Erro de certificado SSL ao utilizar pip install no raspberry

Question: Estou tentando instalar a biblioteca opencv para utilizá-lo em um projeto num dispositivo raspberry com raspbian e quando utilizo o comando pip recebo o seguinte erro:
(venv) pi@raspberrypi:~/teste $ pip install opencv-python
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting opencv-python
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1056)'))': /simple/opencv-python/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1056)'))': /simple/opencv-python/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1056)'))': /simple/opencv-python/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1056)'))': /simple/opencv-python/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1056)'))': /simple/opencv-python/
  Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

Depois de realizar algumas pesquisas percebi que o erro pode ser causado pela data e hora incorreta no dispositivo, como não tenho domínio na utilização do raspbian, ajuda para acertar data e hora serão bem vindas. Caso esse seja uma possível solução.
Answer: O link utilizado pelo pip https://www.piwheels.org/simple parece ser recente (utilizado em 17/04/2020) e o certificado de segurança utilizado por ele parece ainda não ser reconhecido com confiável. Para burlar essa verificação de segurança basta fazer como no exemplo:
pip install picamera --trusted-host www.piwheels.org


Number Theory Question, Relative Primes

Question: We have 16 random, consecutive natural numbers, like(2,3,...,17).
Prove that we can always choose one of them, which is relative prime to the other 15.
In other words, for any kind of n, we have, n,n+1,...n+15, and from that one of them is relative prime to the other 15.
I tried thinking in a way that 8 of them must be divisible with 2, so 8 of them are not good.
At least 5 of them is divisible with 3, and so on, but I can't really prove why you can always have 1.
Comment: have a look here : http://math.stackexchange.com/questions/1140703/given-any-10-consecutive-positive-integers-does-there-exist-one-integer-whic/1140723#1140723
Comment: What does random natural numbers means?
Comment: I meant that now matter what 16 following natural numbers you choose, there is always one with the following attitude.
Comment: See [this answer](https://math.stackexchange.com/a/3080859/242) for literature on this problem.
Answer: Hopefully I didn't make any mistake in counting.
Assume by contradiction that this is not true.
Then, there are $\binom{16}{2}=120$ pairs of numbers. Now, for each pair their $gcd$ is not one, therefore they are divisible by a prime $p$.
Moreover, if $p|m,k$ then $p|m-k \leq 15$ therefore $p \in \{ 2,3,5,7,11,13 \}$.
Now define $A_p:= \{ (m,k)| n \leq m,k \leq n+15 , p|m,k\}$. We know that
$$A_2 \cup A_3 \cup A_5 \cup A_7 \cup A_{11} \cup A_{13}$$
has 120 elements.
There are exactly $8$ numbers divisible by $2$, therefore there are $\binom{8}{2}=28$ elements in $A_2$.
There are at most $6$ numbers divisible by $3$, therefore there are at most $\binom{6}{2}=15$ elements in $A_3$.
There are at most $4$ numbers divisible by $5$, therefore there are at most $\binom{4}{2}=6$ elements in $A_5$.
There are at most $3$ numbers divisible by $7$, therefore there are at most $\binom{3}{2}=3$ elements in $A_7$.
There are at most $2$ numbers divisible by $11$, therefore there are at most $\binom{2}{2}=1$ elements in $A_{11}$.
There are at most $2$ numbers divisible by $13$, therefore there are at most $\binom{2}{2}=1$ elements in $A_{13}$.
Therefore there are at most $28+15+6+3+1+1=54$ elements in
$$A_2 \cup A_3 \cup A_5 \cup A_7 \cup A_{11} \cup A_{13}$$

Number Theory Question, Relative Primes


Views Exposed form in block : how to add a ajax results counter?

Question: I implemented a view as following :

a page display with an extensive exposed filters form (Better exposed filters), ajax enabled, let's call it the landing page
a clone of it, in a second page display with exactly the same fields, but few exposed filters instead (quick search form)
that clone has exactly the same path, Exposed form in block is set to yes

I display the clone created block (quick search form) on homepage : submitting its form redirects to landing page with correct results and the complete exposed filters. This is fine.
Question :
I need to display a results count next to the exposed form block, which refreshes each time you change a exposed filter value in the form.
The Global: Result summary in header or footer doesn't work because  footer and header aren't displayed together with the exposed block, they only come with the full view display.
How could solve that, either with UI or programmatically ? Below some ideas to begin, there might be a good and straight way :

force the results count header to be displayed next to exposed block ?
add a markup to the form with ajax results ?
create another block ?

EDIT
I tried several approaches based on Shreya answer below, but the blocking point is always the same, I need to execute the view to get result count, but as soon as I do, it returns an Allowed memory size exhausted.
in template.php :
function shoot_preprocess_views_exposed_form(&$vars){

  if($vars['form']['#id'] == 'views-exposed-form-customer-products-list-search-block') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->execute();
    $count = count( $view->result );
    $vars['count'] = $count;
  }
}

in views-exposed-form--MY_VIEW.tpl.php
print 'There are:'. $count. 'results';

And other tries with views_get_current_view() or views_get_view_result() in the tpl, also tried within form alter :
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-my-view-my-display') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->get_total_rows = true;
    $view->pre_execute();
    $view->preview('MY_DISPLAY');
    $view->execute();
    $content = $view->total_rows;
  }
  $form['submit']['#value'] = 'Voir les'. $content.' résultats';
}

Any clue to explain why I can't execute the view, or how to return count in that context ?
Comment: you can alter the the exposed form tpl and print the total count
Comment: Next to exposed form block means ..before the views results are displayed ..am i correct
Comment: Yes, I want to display a result counter next to exposed form, before submitting and redirecting to results page. Counter refreshed whenever any exposed filter is changed...
Comment: $view = views_get_view('my_view'); $view->set_display("page_1"); ///$view->set_arguments($er); $view->get_total_rows = true; $view->pre_execute(); $view->execute(); $content = $view->total_rows; $form['mymodule'] = array( '#type' => 'textfield', '#title' => t('title'), '#value' => $content, ); this works – Use form alter
Comment: @Shreya, tks but if I understand your proposal, it doesn't work. Wherever I execute the view in exposed block context, it ends with a memory size exceeded. And I try with a very very simple basic view and few results for dev purpose. Please edit your answer to expose the last solution you think is working
Answer:
Create a folder structure as sites/all/themes/example_theme/templates/views

2.Create a file named views-exposed-form.vars where you use MYTHEME_preprocess_views_exposed_form. Code snippet below:
function example_theme_preprocess_views_exposed_form(&$vars){
  if($vars['form']['#id'] == 'views-exposed-form-exaample-page') {
    $views_rows = views_get_view_result('my_custom_view', 'page');
$count_rows = count($views_rows);
   $vars['count'] = $count_rows;
  }

}

Then you can override the exposed filter tpl. To override the
exposed form template for a particular view, you need to create a
template in the following name pattern,
views-exposed-form--view_name.tpl.php
and print the $count variable wherever you want to place the count.
Once you add the template clear the cache.
Comment: Did you try this?? And keep use ajax to Yes
Comment: Yes I tried this pm, thanks for your answer. First, I had never heard of .vars files before (assuming  `.vars.php`). Googling gives results almost especifically in [Bootstrap context](http://drupal-bootstrap.org/api/bootstrap/docs!registry!README.md/7#theme-preprocess) . I tried anyway, but the code isn't processed.
Comment: So I tried to put that function in `template.php`. Then another problem is, you can count rows of any display of the view except for the currently exposed block, it returns memory fatal error. I made extensive tries, changing the display with exposed form block but it's always the same. you can't execute and count the one exposed.
Comment: $view = views_get_current_view() did you try this
Comment: No, but I tried `$view = views_get_view('customer_products_list');
    $view->set_display('partir');
    $view->execute();
    $count = count( $view->result );` and it gives same error when I execute the view. What about the .vars.php file first please ?
Comment: I've just tried `views_get_current_view()` but in that context it s not a vierw context and returns no view
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39297/discussion-between-shreya-shetty-and-kojo).
Answer: You could try a front-end approach.
In the views header you can show the total results (Global: Result Summary) in a hidden div and, using js, take the value from there and print it wherever you want.

Edit: I misuderstood your implemmentation. You could try using a block
  with exactly the same filters (hidden with css) you need, showing
  nothing but a header. You can adjust it
  to work with ajax, so the results will be refreshed and use js to
  change the filters with those changed in the exposed form in the
  block.
Comment: well as explained in question me the header is not showing up With an exposed form block display. No html output.
Comment: I've got many views with exposed forms in blocks and that doesn't have any effect in headers appearing or not. You could try using mefibs module which kind of improves better exposed filters.
Comment: please read again my implementation. The header would appear in the main part of The View not in the exposed form block. and in order to have Xposed filters both in the block and in the target view, I have 2 displays not one. i'll have a look at that module but I would prefer coding because I already have a bunch of modules, this might be an overkill. Thank you
Comment: sorry, I changed my answer. I hope it can help.


When The Center and Abelianization are Isomorphic

Question: Suppose that $G$ is a non-Abelian Lie group.  Is there a characterization of such groups $G$ for which
$$
Z(G)\cong G/[G,G]?
$$
(Besides the case where $G$ is itself Abelian)?
Comment: Then I must ask:  why do you care?
Comment: To see if it Z(G) ever becomes functorial (when restricted)...out of curiosity
Comment: What are some non-abelian examples of this?
Comment: I can't think of any non-trivial ones
Answer: Here is an important example. For any field $K$ of characteristic zero, the abelianization of $GL_n(K)$ is $K^{\times}$ since its commutator subgroup is $SL_n(K)$. Furthermore the center is given by $\lbrace\lambda I\mid \lambda \in K^{\times}\rbrace \cong K^{\times}$.
More generally, this holds for Lie groups of the form $S_1\times \cdots \times S_r\times T$ with semisimple $S_i$ and abelian $T$.
Comment: Huh, interesting..
Comment: I didn't know this, very interesting.  Would you happen to have a reference, I'd love to look at the proof :)
Comment: We have $GL_n(\Bbb C)=S\times \Bbb C^{\times}$ and $[S,S]=S$. The center is $\Bbb C^{\times}$. This is all for the proof. For the center see [this question](https://math.stackexchange.com/questions/299626/the-center-of-operatornamegln-k).


error with constring in c# while connecting database

Question:
A network-related or instance-specific
  error occurred while establishing a
  connection to SQL Server. The server
  was not found or was not accessible.
  Verify that the instance name is
  correct and that SQL Server is
  configured to allow remote
  connections. (provider: Named Pipes
  Provider, error: 40 - Could not open a
  connection to SQL Server)

The problem is the database property showing connection string data source as "xyz\sqlexpress"
..if i put the same connection string it wil show the error as "escape sequence used"(\)...if i modify connection string as only "xyz" then it wil give above given error...so please suggest me some solution for this...
"i have allowed remote connection"   and what is exactly this instance name?
Answer: You need to escape the backslash character:
If you construct the connection string in code:
<code>"DataSource=xyz\\sqlexpress"
</code>
In your configuration file:
<code>"DataSource=xyz\sqlexpress"
</code>
Answer: If your connection string contains a backslash ("\"), you need to double it up ("xyz\\sqlexpress") or escape it with @ (@"xyz\sqlexpress").


Django sem visualização de models no admin de usuario comum mesmo tendo permissões e estando no mesmo grupo

Question: Boa tarde,
Então estou tentando dar permissões que já vem no django para um usuário comum que mesmo pertencendo ao grupo não consegue acessar os models que é concedido a ele. Alguém teve esse problema da não visualização de models no admin. versão do python 2.7 e django 1.10
já tenho as conf do settings como  'django.contrib.auth','django.contrib.auth.middleware.AuthenticationMiddleware'
no models eu tenho apenas:
class Paciente(models.Model):
    nome = models.CharField(max_length=60)
    data_nascimento = models.DateField()
    def __str__(self):
        return self.nome
    class Meta:
        verbose_name = "Paciente"
        verbose_name_plural = "Pacientes"

e no admin tenho:
class PacienteAdmin(ModelAdmin):
    list_display = ('nome','data_nascimento')

admin.site.register(Paciente, PacienteAdmin)

apenas isso e mesmo assim sem visualização do mesmo.
obrigada desde já.
Answer: Fiz um teste com seu codigo e funciona perfeitamente, o único erro que vejo no código que vc postou aqui é no fragmento (admin.py):
class PacienteAdmin(ModelAdmin):
   list_display = ('nome','data_nascimento')

Troque a linha:
class PacienteAdmin(ModelAdmin):

Para:
class Paciente(models.Model):

Se não funcionar, tente seguir os passos:
1) (linha de comando)
$ django-admin startproject myproject .

2) (linha de comando)
$ ./manage.py migrate

3) (linha de comando)
$ ./manage.py createsuperuser

4) (linha de comando)
$ ./manage.py startapp myapp

Após esses passos, a árvore do seu projeto devera parecer com a figura abaixo:

5) Edit o arquivo models.py no diretorio myapp para que fique assim:
from django.db import models

class Paciente(models.Model):
    nome = models.CharField(max_length=60)
    data_nascimento = models.DateField()
    def __str__(self):
        return self.nome
    class Meta:
        verbose_name = "Paciente"
        verbose_name_plural = "Pacientes"

6) Edit o arquivo admin em myapp, para que fique assim:
from django.contrib import admin
from .models import Paciente

class PacienteAdmin(admin.ModelAdmin):
    list_display = ('nome','data_nascimento')

admin.site.register(Paciente, PacienteAdmin)

7) Edite o arquivo settings.py para adiconar myapp, então a seção INSTALLED_APPS, deverá ficar assim:
INSTALLED_APPS = [
    'myapp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Após esses passos, execute o projeto com runserver, entre em admin, crie um grupo e um usuario, dê permissao para que o usuario possa incluir mas não possa deletar pacientes. Se eu não cometi nenhum erro ao postar aqui e voce seguiu todos os passos corretamente, o resultado será o esperado.
Obs.:
O exemplo expresso aqui foi testado (e aprovado :-)) em um ambiente Linux.
Comment: Muitoo obrigada, resolvido o problema, acabei criando um outro projeto e feito os passos para verificar onde estava o erro.


Conditions for "$AA^T=A^TA$ implies $A$ symmetric" to hold.

Question: This claim arose in this question Show that $A$ is symmetric, with $A \in M_n(\mathbb R)$ where it is assumed additionally that $AA^TA$ is symmetric.
I'm considering weakening hypotheses.
Let $A$ be a real matrix such that $AA^T=A^TA$. This implies that $A$ is normal.
According to the spectral theorem (for complex-valued normal matrices), $$A=UDU^*$$ for some complex diagonal matrix $D$ and complex unitary matrix $U$.
I am not sure I can infer from here that $D$ and $U$ must have real entries. Nevertheless, if $A$ has real eigenvalues, then $D$ must have real entries.

Are real eigenvalues sufficient to prove that $U$ has real entries ?
Is there a way to circumvent the use of the spectral theorem ?
Can you think of other hypotheses for the result to hold ?
Is the claim " $AA^T=A^TA$ implies $A$ symmetric" true for any real $A$ without conditions on eigenvalues ? (EDIT: Answer is no.)
Comment: $A$ symmetric $\implies$ $A$ normal. Converse may not be true.
Answer: The claim isn't true. Take for example an orthogonal matrix $O$ so we have
$$OO^T=O^TO=I_n$$
and $O$ isn't symmetric.
Comment: What about the eigenvalues of $O$ ? Are they real ?
Comment: Not necessary. Take for example this matrix
$$\left(\begin{array}\\
\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{array}\right)$$
Comment: For $2*2$ matrices, orthogonal matrices are either symmetric, or they have complex eigenvalues (their imaginary part is $|sin(\theta)|$). Is is true for higher dimensions? Can you disprove the stronger claim that if $A$ has real eigenvalues, then $A$ is symmetric ?
Comment: Short and sweet, Sami!