Python Google Drive API oauth2 - Save authorization consent for user

Question: I am creating a MacOS app that creates a custom folder hierarchy in a given Google Team Drive/folder. Each time I run the app, it opens a browser and asks for the user to sign in and allow the app to access. On accept, the app creates the folders and works as intended. However, it does this each time and I am having a difficult time trying to find out how to save the "user's consent" so that they should only have to allow consent once, the first time they run the app. I've tried a number of different options and I am getting nowhere, so I really appreciate any help.
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/drive']
API_SERVICE_NAME = 'drive'
API_VERSION = 'v3'

def get_authenticated_service():
    client_secrets = args["secrets"] #client_secrets.json file passed as "secrets" argument

    flow = InstalledAppFlow.from_client_secrets_file(client_secrets, SCOPES)

    credentials = flow.run_local_server(host='localhost',
                                    port=8080,
                                    authorization_prompt_message='Please visit this URL: {url}',
                                    success_message='The auth flow is complete; you may close this window.',
                                    open_browser=True)

    return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

if __name__ == '__main__':
    service = get_authenticated_service()
    name = format_client_name()
    create_folders(service, name)

I tried working with the Google API Client Libraries here (https://developers.google.com/api-client-library/python/guide/aaa_oauth), where it shows Storage, however it doesn't have any instruction with google.oauth, since you can't use oauth2client storage with google.oauth. I feel like it's something simple, but I've hit a wall.
Answer: You can use oauth2client.file.Storage to store the credentials in a credentials.json file for future retrieval. The function checks for valid credentials stored locally before running an authentication flow.
I've attached an example below from the following repo:
https://github.com/gsuitedevs/python-samples/blob/master/drive/quickstart/quickstart.py
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START drive_quickstart]
"""
Shows basic usage of the Drive v3 API.
Creates a Drive v3 API service and prints the names and ids of the last 10 files
the user has access to.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

# Call the Drive v3 API
results = service.files().list(
    pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print('{0} ({1})'.format(item['name'], item['id']))
# [END drive_quickstart]

Comment: Thanks! I had tried that before, but was having issues with it conflicting with my ArgumentParser. After doing some more digging, I was able to find why it was. `run_flow` was attempting to use the argument parser that I had created for the python script. I had to give it a "dummy" arg parser to make it ignore what I was passing to the script. `flags = tools.argparser.parse_args(args=[])` `creds = tools.run_flow(flow, store, flags)` fixed this issue. (http://oauth2client.readthedocs.io/en/latest/_modules/oauth2client/tools.html#run_flow)
Comment: No worries, glad to hear that you fixed your issue


Switch case checkbox

Question: Preciso que, ao marcar as opções de um checkbox, seja informada uma frase diferente, mesmo que eu marque dois ou mais checkbox diferentes. Neste caso a baixo, usei switch mas estou com dificuldades para serem dadas as respostas corretas. Como posso fazer isso?
Segue o código:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Avatarizador :)</title>

    <form action="" method="post">
        <input type="checkbox" name="erea" value="SSA"> Salvador

        <input type="checkbox" name="erea" value="BRI"> Brisas

        <input type="checkbox" name="erea" value="PTS"> Pontes

        <input type="checkbox" name="erea" value="PTV"> Porto Velho

        <input type="submit" value="Avatarizar">
    </form>

    <?PHP

        /*

        $image_path = "salvador.png";
        $image_path = "brisas.png";
        $image_path = "pontes.png";
        $image_path = "portovelho.png";

        $image_path = "salvador_pontes.png";
        $image_path = "brisas_pontes.png";

        $image_path = "salvador_pontes_portovelho.png";
        $image_path = "brisas_pontes_portovelho.png";

        */

    $e = isset($_POST["erea"])?$_POST["erea"]:"XX";
        switch ($e) {

            /* Pontes + Porto Velho */
            case "PTS":
                $r = "Pontes";
                break;
            case "PTV":
                $r = "Porto Velho";
                break;
            case "PTS":
            case "PTV":
                $r = "Pontes + Porto Velho";
                break;

            /* Salvador */
            case "SSA":
                $r = "Salvador";
                break;
            case "SSA":
            case "PTS":
                $r = "Salvador + Pontes";
                break;
            case "SSA":
            case "PTV":
                $r = "Salvador + Porto Velho";
                break;
            case "SSA":
            case "PTS":
            case "PTV":
                $r = "Salvador + Pontes + Porto Velho";
                break;

            /* Brisas */
            case "BRI":
                $r = "Brisas";
                break;
            case "BRI":
            case "PTS":
                $r = "Brisas + Pontes";
                break;
            case "BRI":
            case "PTV":
                $r = "Brisas + Porto Velho";
                break;
            case "BRI":
            case "PTS":
            case "PTV":
                $r = "Brisas + Pontes + Porto Velho";
                break;
            default:
               $r = ""; /* Avatar Puro */
       }
       echo "Voce escolheu por o selo de $r";
    ?>

Answer: Para gerar sua frase com base nos valores selecionados, você pode fazer dessa forma.
 $('input[type=button]').bind('click',function(){

    var resultado = '';
        $('input[type=checkbox]:checked').each(function() {
        if(resultado!=''){resultado += "+";}
        resultado += $(this).val();
    });

    alert(resultado);

  });

Veja se ajuda você.
Exemplo funcionando aqui.
Comment: Aqui na empresa pastebin é bloqueado, vc nao consegue jogar no fiddler? ai posso ajudalo
Comment: Mas preciso que ele mostre as frases que estão dentro do case, não o que está escrito nos valores. Depois eu ainda vou ter que substituir cada frase por um $image_path = "nome.png"; nos case, onde um código vai selecionar as fotos corretas para se transformarem em marca d'água.

Pode ver o site que estou modificando aqui: http://ilhas.16mb.com/
Comment: Se você vai suibstituir cada frase pq nao faz isso com os valores do checkbox em vez das frases, ou vc tem algum "Porto Velho.jpg" com espaco em branco e tudo mais?
Como vc vai fazer com as N variacoes que vc pode ter nessa concatenacao de valores seleiconados.
Comment: https://jsfiddle.net/eeuzj8ra/2/  veja um novo exemplo aqui, pégando os textos que vc quer.
Comment: Estou tentando recriar isso: http://pastebin.com/FJ4s2pC4
Comment: https://jsfiddle.net/nrcdwpy4/2/
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/33587/discussion-between-andre-and-rboschini).

Switch case checkbox


How to structure git repository for a client-server project

Question: I will be doing a project that will have a distinct server side (.NET) and client side (JavaScript) which can be developed separately. Does it make more sense to have them as 2 separate git repositories or should they be rather one? What advantages / disadvantages do these approaches have?
Answer: I'd recommend placing the code in two separate folders within the same git repository.
Main reason being that if you make changes to the server that require changes in the client it's easy to see the changes to both in the same change set.
If the client and server code were separate repositories you've have to try and determine manually which change set on the server corresponded to which change set in the client code base.
Comment: Git subtrees helps with this a bit, you can have separate repositories but the files are mirrored and versioned in the encompassing repository.
Answer: Personnaly, i create two big folders, one for the client side and the other for the server.
For the client side (I use symfony), I use apache alias. So it's more simple and it's centralized.
Having two repository is the same but it's not as simple to switch between branches.
For example, you change the security protocol. You will edit the two sides. So a branch is a good soluton.
If you've two separated repositories, you cannot use the same branch.


Help proving improper integral converges

Question: The problem we are given is: Let $f$ be differentiable and nonzero on [1,$\infty$). If $\lim_{x\to\infty}(\frac{xf'(x)}{f(x)})$ exists in $\bar{\mathbb{R}}$ and is less than $-1$, show that $\int_1^{\infty} f$ converges.
We are given the hint to consider $\frac{xf(x)}{\int_1^x f(x)}$ as $x\to\infty$.
Despite this hint, I am at a lost for where to begin. I tried applying the Limit Comparison Test to no avail. Can anyone give me an idea of where to begin?
Answer: Hint:
Since $f$ is differentiable (hence, continuous) and non-zero, either $f(x) > 0$ or $f(x) < 0$ for all $x \in [1,\infty)$. If $\int_1^\infty f$ fails to converge, either $$\lim_{x \to \infty} \int_1^x f(t) \, dt = +\infty \text{   or  } \lim_{x \to \infty} \int_1^x f(t) \, dt = -\infty$$
Apply L'Hopital's rule to obtain
$$\tag{*}\lim_{x \to \infty} \frac{xf(x)}{\int_1 ^x f(t) \, dt} = \lim_{x \to \infty} \frac{f(x) + xf'(x)}{f(x)} = 1 + \lim_{x \to \infty} \frac{xf'(x)}{f(x)}  < 0$$
and find a contradiction by showing the LHS of (*) must be positive.
Comment: The phrase non-zero applies to $f'$ or $f$? Actually I was thinking about applying to $f$, and struggling with the result.
Comment: @user284331: The statement is $f$ is nonzero -- an important assumption since it appears in the denominator of $xf'/f$.  The limit using L'Hopital can be shown to be negative -- leading to the ultimate contradiction.
Comment: I still fail to see the point. And one thing, why must $\lim_{x\rightarrow\infty}xf(x)=\infty$, this is needed before doing L'Hopital.
Comment: @user28331:  Added to answer.  You only need the denominator to go to $\pm \infty$ to apply L'Hopital's rule.  It applies to the case $0/0$ or anything$/\infty$.
Comment: So if $f(x)$ is negative (positive) on $[1,\infty)$, then $\int_1^{\infty}f(t)dt$ must also be negative (positive)?
Comment: @Chubwagon: Yes - that is correct and helps complete the answer.
Comment: L'hopital for anything$/\infty $? Never heard of that..
Comment: I was not the down voter. I said that I have never heard of that to get some reference from you. I already looked it up and saw nothing about it. So could you please send me some link?
Comment: @Shashi:  Apologies. See for example https://math.stackexchange.com/a/2136053/148510
Comment: Very nice, thank you! I increased the range of my knowledge. +1
Comment: @Shashi: You're welcome.  This is not well known but it comes up here frequently.  I'll look for a another reference.
Comment: @Shashi: See General Proof (case 2) in Wikepedia: https://en.wikipedia.org/wiki/L%27H%C3%B4pital%27s_rule
Comment: Yes I see it. I only read the first sentences. My bad! Thanks again!


Multiple regression: Strength measure changes by student but is constant over time

Question: Disclaimer: This is the first time I use this forum, so please let me know if my question is not clear or if you need more information.
I have data which looks like this:

I want to run the regression:
lm(formula = SCORE ~ STRENGTH, data = mydata), in order to find out if higher STRENGTH of the student (NAME) leads to a higher test score.
Note that the STRENGTH score changes by student but is constant over time. I was wondering if this regression setup is valid, or if the fact that I have no time variation is a problem in a time series regression? Would this allow me to test whether or not higher strength explains higher test scores?
Thank you very much for your help and suggestions.
Glenn
Comment: Ah, I understand, I missed that you were only looking at three students!
Comment: Generally, it's possible to have an independent variable that does not change with time. However, the study design is not clear. What are "period"? And if they are some kind of time, how did you determine Jim will be measured again at 4 and 5? Overall, I think you need very succinctly tell us how the time (both the time for strength score measurement and time of score measurement) is decided. As of now, the least I can say is that if all the Jims here are the same Jim, then your linear model is inadequate because it overlooks personal-level clustering.
Comment: *"Note that the STRENGTH score changes by student but is constant over time"* what does that mean?
Comment: I mean that Max, Jim, and Bob have different scores (0.3, 0.5, 0.8), but that this score stays constant from period 1 to period 11 for the three students. Hope that makes it clearer.
Comment: I should clarify that I misleadingly used 'score' in my reply to you. I was referring to the STRENGTH values.
Comment: I understood what you meant, as will other users who see the question.
Comment: Thank you @Penguin_Knight. So PERIOD is a timestamp observation (dd-mm-yyyy hh:mm:ss), when a student started an exercise. I have many more students than just the three I provided here. The STRENGTH value is determined once for each student and does not change thereafter. For example, a fitness value that is obtained. The observations are runs completed by students, hence JIM might do two runs in a row, for example a morning and evening run. Bob might only do an evening run. I take your clustering point. I could use the felm() function an cluster by NAME.
Answer: The code lm(formula = SCORE ~ STRENGTH, data = mydata) assumes the data agrees to the following model ($Y=$ score and $X = $ strength)
$$Y_i = \beta_0 + \beta_1 \cdot x_i+\epsilon_i$$
where the $\epsilon_i$ are independent and $\mathrm{Var}[\epsilon_i] = \sigma^2$.
You would like to test whether $\beta_1 > 0$.
I would say that the assumptions seem unreasonable in your case, since the samples are not independent. I think the least-squares estimates are still unbiased but the variance estimate of $\hat \beta_1$ won't.
I think you could get an understanding of the issue by making the setting more extreme. Say you have 100 samples of Bob's strength and score, and one sample of Jim's strenght and score. If you ignore this fact and perform linear regression the point estimate of $\beta_1$ could be spot on but the variance estimate would be severly underestimated.
I've tried some code and I don't think you will be able to detect a significant difference (or increase)...
m <- matrix(c(0.81,0.67,0.98,0.23,0.17,0.38,0.49,0.11,0.73,0.27,0.51,0.3,0.5,0.8,0.5,0.5,0.8,0.3,0.3,0.5,0.3,0.8),ncol=2)
m <- as.data.frame(m)
m <- cbind.data.frame(m,c("M","J","B","J","J","B", "M", "M","J", "M","B"))
colnames(m) <- c("score","strength","name")
m

lm.fit <- lm(score~strength,data=m)
summary(lm.fit) #2 sided test unable to reject the null

Comment: Thank you @dietervdf. Would cluster-adjusted SEs help to address the potential within-cluster correlation, i.e. that the observations within each student group are not i.i.d.? Assume the STRENGTH value is determined once for each student and does not change thereafter. For example, a fitness value that is obtained and matched to each student observation. What I really try to answer is if I can have an independent variable (STRENGTH) that differs by student but does not change with time assuming I am able to account for possible independence issues etc.?
Comment: I'm not experienced with this cluster-adjusted SE's, but I've reading through it for the last hour or so. That seems like the way to go. `plm` seems to be  capable `R` package.


Run java application from command line with external jar files

Question: I have an external jar file(have package structure), which contains the main class, and I can run the app from command line like this:
java -jar example.jar

But I still have another test.class file outside this jar file, and some classes inside this jar file will invoke the methods in test.class. How can I specify the test.class file to be used by jar file in command line?  Tried many ways, always show:
NoClassDefFoundError for test.class

NB: the test.class file also use class files in example.jar file, has its own package structure.
I know I can put them together in one jar file, unfortunately I need separate the test.class file.
Comment: Read up on Classpaths in the oracle tutorial.
Answer: If the class is in bin directory :
java -cp xxx.jar;bin pck1.pck2.MainClass

If the class is in the current directory :
java -cp xxx.jar;. pck1.pck2.MainClass

and so on...
More info in the manual, please read it at least one time... ;-)
Comment: *"Assume test.class file is in the same folder with example.jar file"*  How about you 'pick up the ball & run with it' rather than try to get us to code this to your exact specification?
Comment: Seriously how hard is `java.exe -?`
Comment: @Aubin I was asking LifeOnCodes lol. This question could have been summed up for him if he had just done `java.exe -?`.
Comment: Sorry, not in workspace, no bin directory. Assume test.class file is in the same folder with example.jar file
Comment: I think I forgot to mention one important thing: the test.class also use the class files in example.jar, and has its own package structure too...and you use ; to separate class path to search the class files?
Comment: It works. I want to stress that the options `-cp xxx.jar;.` should come before the class containing the main method, otherwise the annoying "Error: Could not find or load main class" appears.
Answer: In Linux System
Compile and Run Java Program along with External JARs.
javac -cp </path/jar1>:<path/jar2>:<path/jar3> MainClass.java

If Compiler throws deprecation warning. You can recompile with -Xlint:deprecation argument.
javac -Xlint:deprecation -cp </path/jar1>:<path/jar2>:<path/jar3> MainClass.java

Finally, run the Java Program:
java -cp </path/jar1>:<path/jar2>:<path/jar3>:. MainClass

If you want to run Java Process in Background. You can use nohup.
nohup java -cp </path/jar1>:<path/jar2>:<path/jar3>:. MainClass &

Answer: You can use following commands to run java main class or java jar file:
java -Djava.ext.dirs=E:\lib  E:\Executable\MyMainClass

java -Djava.ext.dirs=E:\lib  E:\Executable\purging.jar


Method invocation may produce NullPointerException

Question: Eu estou usando geocoder para transformar o endereço do edit text em Longitude e Latitude. Ai ele ta fazendo certinho e salvando no banco a lat e lng, mas ele da uma exception que nao causa nenhum problema no app, mas fica dando o erro na tela e tenho que apertar ok toda vez, e ele diz que é por causa do adresses.get(0) que fica dando um nullpointerException, como ajeito?
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        addresses = geocoder.getFromLocationName(stringLocal, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Address address = addresses.get(0);
    double longitude = address.getLongitude();
    double latitude = address.getLatitude();

Answer: A causa é que você não trata a exceção no s eu try/catch. A variável addresses vai ficar nula e o método vai continuar executando.
Uma possível codificação correta para esse código seria:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocationName(stringLocal, 1);
} catch (IOException e) {
    //mostra mensagem de erro
    return; //sai do método já que não consegue calcular
}

Address address = addresses.get(0);
double longitude = address.getLongitude();
double latitude = address.getLatitude();

Outra possibilidade seria:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocationName(stringLocal, 1);
    Address address = addresses.get(0);
    double longitude = address.getLongitude();
    double latitude = address.getLatitude();
} catch (IOException e) {
    //mostra mensagem de erro
    return; //sai do método já que não consegue calcular
}

Não se esqueça que também pode ocorrer um erro se a lista não trouxer nenhum elemento. Então é sempre bom verificar se ela não é vazia. Exemplo:
public void mostrarCoordenadas() {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocationName(stringLocal, 1);
        if (!addresses.isEmpty()) {
            Address address = addresses.get(0);
            double longitude = address.getLongitude();
            double latitude = address.getLatitude();
            //exibe latitude e longitude
        } else {
            //mostra erro amigável
        }
    } catch (IOException e) {
        //mostra erro amigável
    }
}

Comment: Deu certo, muito obrigado!


determining range of values of TypedArray item

Question: According to the documentation on the Uint8ClampedArray,

The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead.

Other TypedArrays function similarly. Given any typed array amongst the types listed, is there a way to programmatically derive the max/min value possible to store therein?
Something along the lines of:
Uint8ClampedArray().maxItemValue // returns 255

Comment: [`BYTES_PER_ELEMENT`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) might help, but you still need to distinguish signed from unsigned types.
Comment: Do you want the max of **every** type (even floats)? Do you want the min as well (for signed types)?
Comment: yeah, I saw that too... it might ultimately be most efficient to just do a switch statement on the name property, but it'd be nice not to have to do that.
Comment: Why on the `.name` property? You can switch on the functions themselves if you want.
Comment: every type that a TypedArray might hold, min and max, yes.
Answer: I'd use the following:
function maxElementValue(arr) {
    const c = arr.constructor;
    const test = c.of(-1.5)[0];
    if (test > 0) // unsigned integers
        return test;
    //  return 0xFFFFFFFF >>> (32 - 8 * c.BYTES_PER_ELEMENT);
    //  return Math.pow(2, 8 * c.BYTES_PER_ELEMENT) - 1;
    if (test == -1) // signed integers
        return 0x7FFFFFFF >>> (32 - 8 * c.BYTES_PER_ELEMENT);
    //  return Math.pow(2, 8 * c.BYTES_PER_ELEMENT - 1) - 1;
    if (test == 0) // clamped
        return 0xFF; // there's only one of these
    if (test == -1.5)
        throw new TypeError("floats are not supported");
    throw new TypeError("weirdly behaving typed array");
}

Comment: nice! this seems like it works as expected. I *think* I can figure out the minimum value part on my own.


Two-way ANOVA doesn't detect differences between conditions in a specific group?

Question: OK, so let's say we have independent variables Condition (A or B) and Race (1 or 2 or 3). Then say we have a dependent variable X. We can run a two-way ANOVA to find out if there's an effect due to Condition alone (do people in A differ from people in B on variable X), Race alone (do people of race 1, 2 and 3 differ from each other on variable X), and interaction Condition*Race (does Condition and Race interact). However, let's say that the condition has a strong effect only on race 3 (And this is something I am looking to detect). This will be obvious if I run a t-test for Condition A (Race 3) vs. Condition B (Race 3) on variable X. But the ANOVA isn't used to test for this, correct?
Answer: Correct, ANOVA will tell you there differences among group means but not which. To find out which you can use a t-test or a Tukey multiple comparison test. If you are doing this in R you can use TukeyHSD() function on the anova object and it will perform the MCP for you.
Comment: I would add that there is multiple a posteriori test that help you find differences among group. Tukey is very restrictive. There's also the LSmeans. But you can do those a posteriori test only on independent variables found significant in the ANOVA.


Can't use core database in IOS5

Question: I am working with a core database, it is working in IOS 6 but when I trying to test it on IOS 5. It does not do anything. Let me explain what I'm doing.
First I do this in my viewWillAppear.
<code>- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"view appeared");
    [super viewWillAppear:animated];
    if (!self.genkDatabase) {
        NSLog(@"comes to here");
        NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        url = [url URLByAppendingPathComponent:@"Default appGenk Database2"];
        // url is now "<Documents Directory>/Default Photo Database"
        self.genkDatabase = [[UIManagedDocument alloc] initWithFileURL:url]; // setter will create this for us on disk
        NSLog(@"database created on disk");
    }

}
</code>
Then it comes in the UseDocument method.
<code>- (void)useDocument
{
    NSLog(@"Comses in the use document");
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.genkDatabase.fileURL path]]) {
        // does not exist on disk, so create it
        [self.genkDatabase saveToURL:self.genkDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            NSLog(@"create");
            [self setupFetchedResultsController];
           [self fetchGenkDataIntoDocument:self.genkDatabase];

        }];
    } else if (self.genkDatabase.documentState == UIDocumentStateClosed) {
        NSLog(@"closed news");
        // exists on disk, but we need to open it
        [self.genkDatabase openWithCompletionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
        }];
    } else if (self.genkDatabase.documentState == UIDocumentStateNormal) {
        NSLog(@"normal");
        // already open and ready to use
        [self setupFetchedResultsController];
    }

}
</code>
And finally it goes into the setDatabase Method.
<code>- (void)setGenkDatabase:(UIManagedDocument *)genkDatabase
{
    if (_genkDatabase != genkDatabase) {
        _genkDatabase = genkDatabase;
        [self useDocument];
    }
    NSLog(@"Comes in the setdatabase methode.");
}
</code>
Doing all this gives the following log.
<code>2012-10-22 10:42:47.444 RacingGenk[4786:c07] view appeared
2012-10-22 10:42:47.445 RacingGenk[4786:c07] comes to here
2012-10-22 10:42:47.459 RacingGenk[4786:c07] Comses in the use document
2012-10-22 10:42:47.460 RacingGenk[4786:c07] Comes in the setdatabase methode.
2012-10-22 10:42:47.461 RacingGenk[4786:c07] database created on disk
</code>
Like you can see it does not print the create log in my use document. So it isn't able to execute the method FetchDataIntoDocument.
Can anybody help me with this problem. I am searching at this problem for ages for now.
Many thanks in advace.
Stef
Answer: Are you testing with the simulator or on the device?
The simulator is case-insensitive - the device is case-sensitive on file access, remember that!
But beside from that the documentation for NSFileManager recommends not checking to see if files exist, and instead just trying to read the file and handle any errors gracefully (e.g. file not found error). So just try loading the file instead of checking to see if it exists.
And i don't see any file extension for your database file! It just states ""Default appGenk Database2".
Is this already the file name or jut another subdirectory so far?
EDIT:
You can try the following code:
<code>- (void) setupStore {
    NSString* storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"mydatabase.sqlite"];

    // Set up the store.
    NSFileManager* fileManager = [NSFileManager defaultManager];
    // If the expected store doesn't exist, create one.
    if (![fileManager fileExistsAtPath: storePath]) {
        // create your store here!
    }
}

- (NSString*) applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
</code>
"mydatabase.sqlite" is the name of the database-file you expect to be present in your documents directory.
If you would like to see a full-fledged example on how to set-up a core data persistent store you could check out apples own iPhoneCoreDataRecipes example. Just take a look at the

RecipesAppDelegate.m

implementation.
Comment: I'm testing on simulator. What extentions should Default appGenk Database2 have? could you maybe have some code ?
Comment: Hi Sarah! I added some code that may help, otherwise check out the linked example!

Can't use core database in IOS5


Property of a transient Markov chain

Question: An irreducible Markov chain on a countable state space $S$ is recurrent if one of the following equivalent statements holds:

There exists a finite set $A \subset S$ such that $P_x[T_A<\infty]=1$ for every $x \in A$;
$P_x[T_x<\infty]=1$ for every $x$ in $S$.

Here $T_A=\min\{n\geq 1:X_n \in A\}$ for any $A \subset S$. And an irreducible Markov chain is transient if it is not recurrent.
How can we show the following result?

Suppose that the Markov chain $X$ is irreducible and transient. Then there exists a finite set $A \subset S$ and a point $x\in S$ such that $P_x[\tau_A<\infty]<1$, where $\tau_A=\min\{n\geq 0:X_n \in A\}$.

Thanks for any comments!
Comment: The two definitions of recurrence you've given are not, in general, equivalent (consider, for instance, the random walk on $\mathbb{Z}$ that always takes a step to the right, which satisfies $1$ for $A=\{x+1\}$, but not $2.$) Maybe this is just because you haven't written clearly in what sense these statements are uniform. Also, what's your question? You haven't actually written a result, because you haven't stated any assumptions. Do you want to prove that for a transient irreducible Markov chain and any finite $A\subseteq S$, there exists some $x\in S$ such that $P_x[\tau_A<\infty]<1$?
Comment: @WoolierThanThou Sorry for the confusion before. I've corrected my question. Your guess is right. Could you give me some hints?
Comment: As you've written the question, recurrence means that there exists a finite $A$ such that $P_x[T_A<\infty]=1$ for every $x$ (via the first definition). The Markov chain is transient if it is not recurrent so, as you've written it, you can simply negate the above property, right?
Comment: @WoolierThanThou I think the problem is that $\tau_A$ and $T_A$ have slightly different definitions.
Comment: The difference is null. $P_x[T_A=0]=1_{(x\in A)}$ by definition, so no property of the Markov chain plays into this probability. Hence, $P_x[T_A<\infty]=1$ for all $x$ if and only if $P_x[T_A<\infty]=1$ for all $x\not\in A$.
Comment: And, mind you, when you start the process at $x\not \in A$, then $T_A=\tau_A$.
Comment: @WoolierThanThou If I negate the first statement of the definition, then I get that there exists a finite set $A \subset S$ and an $x \in A$ such that $P_x[T_A<\infty]<1$. But still, I have $P_x[\tau_A<\infty]=1$. How can I find an $x \in A^c$ such that $P_x[\tau_A<\infty]=1$?
Answer: Okay, I see your worry now. It's not actually that bad, though.
So assume that your Markov Chain is transient, i.e., for any finite set $A\subseteq S$, there exists some $x\in S$ such that $P_x[T_A<\infty]<1$. All we have to argue is that there must, in particular, exist such a choice of $x\in S\setminus A$, since for such an $x$ we have $P_x[\tau_A<\infty]=P_x[T_A<\infty]$.
Indeed, assume that $P_x[T_A<\infty]=1$ for all $x\not \in A$ and let $x_0\in A$. We wish to prove that $P_{x_0}[T_A<\infty]=1$ since this would mean that the Markov Chain is, in fact, recurrent. Let $(X_n)_{n\in \mathbb{N}_0}$ denote the Markov chain starting at $X_0=x_0$.
Now, if $X_1\in A$, then clearly $T_A<\infty$, and thus, we get that
$$
P_{x_0}(T_A=\infty)=\sum_{x\in S} 1_{x\not \in A} P_x(T_A=\infty) P_{x_0}(X_1=x)=0
$$
We conclude that $P_{x_0}(T_A<\infty)=1$.
Hence, for a given finite $A\subseteq S,$ if there exists some $x\in S$ such that $P_x[T_A<\infty]<1,$ there must exist some $x'\in S\setminus A$ such that $P_{x'}[T_a<\infty]<1$ and hence,
$$
P_{x'}[\tau_A<\infty]=P_{x'}[T_A<\infty]<1
$$

Property of a transient Markov chain


Almost extended Euclidean algorithm - $ax+by=\gcd(a,b)+2$

Question: So I have this equation: $$\eta+2=2g+1n,$$ where $g,n \in \mathbb{N}_{\geq 0}$ and $\eta \in \mathbb{N}_{>0}$. I want to find all possible integer-valued 2-tuples $(g,n)$ that satisfy this equation, e.g. $(g,n)_{|_{\eta=1}} = \{(0,3),(1,1)\}$.
I immediately thought of Diophantine equations/Chinese remainder thm./Bezout/extended Euclidean algorithm.. but
1.) I don't have $ax+by=\gcd(a,b)$ for extended Euclidean algorithm.
2.) I cannot use Pell's equation, $x^2-ny^2=1$, since my $n$ wouldn't be a nonsquare positive number.
3.) Re-writing the equation as $1=\frac{2}{\eta+2}g+\frac{1}{\eta+2}n$ is no good as a Diophantine equation since the fractions are no longer integers.
My last attempt was trying to use the extended Euclidean algorithm in a finite field, like $\mathcal{Z}/(\eta+1)\mathcal{Z} = \{\overline{0},\overline{1},\ldots,\overline{\eta}\}$ s.t. $\overline{\eta+2} \equiv \overline{1}$. But I'm not strong in number theory and am unsure of whether this is even the best approach (if it is one that is even valid).
Lastly I would like to implement this in Maxima and iterate over integer values of $\eta$ from $\eta=1$ to $\eta=10$ (or more).
Thanks!!
NOTE
I know I could do something like,
for(g=0;g<\eta+2;g++){

for(n=0;n<\eta+2;n++){

if (2g+n=eta+2)

then ans[s]: [g,n]

else

print("bad")

which is a bad mix of Maxima and C. If ther isn't a better way, this will be my "brute" force method.
Comment: You do not need to implement the extended Euclidean algorithm, as the relevant coefficients $a=1$ and $b=2$ do not change. Only $\eta$ changes. And you can guess $sa +tb=1$ here, see my answer below.
Answer: $(g,n)$ is a solution to your problem if and only if $$\begin{cases} 0\le g\le\left\lfloor {\eta\over 2}\right\rfloor+1\\ n=\eta+2-2g\end{cases}$$
And I sincerely see no better way to describe them (because this allows you to generate each of them in constant time). For a single $\eta$, you just have to make $g$ range from $0$ to $\left\lfloor{\eta\over 2}\right\rfloor+1$ and calculate the corresponding $n$-s.
Of course, one could try be smart about it and notice that, for instance, if $\left\{(g_1,n_1),\cdots,(g_k,n_k)\right\}$ are the solutions for $\eta=2\mu$, then the solutions for $\eta+1=2\mu+1$ are $\left\{(g_1,n_1+1),\cdots,(g_k,n_k+1)\right\}$ and the solutions for $\eta+2=2\mu+2$ are $\left\{(0,\eta+2),(g_1+1,n_1+2),\cdots,(g_k+1,n_k+2)\right\}$. This might help, but as far as I know this does not drop significantly the complexity of the algorithm: if you aim to write down all the solutions for $1\le\eta\le M$, then you need to write down $\sim {M^2\over 4}$ couplets of integers. As long as you generate them in constant time, you neither lose nor gain anything.
Comment: So you would recommend then the double for loop approach?
Comment: Well, I added some speculation on some recursive properties of the solutions (maybe a recursion on the even values of $\eta$ and, afterwards, another sub-routine to derive the solutions for odd values of $\eta$ from those, but I don't really see the gain in doing that).
Comment: Yes, I also do not see the point. Thanks to your answer I don't have to waste time (though its interesting) trying to implement the extended Euclidean or something like that. :)
Answer: 1. Looking for all integer solutions:
This equation
$$
1 N + 2 G = \eta+2 \quad (*)
$$
is a linear Diophantine equation
$$
a X + b Y = c \quad (**)
$$
and thus subject to the known solution algorithms. Critical is $d = \gcd(a,b) = \gcd(1,2) = 1$. If $d|c=\eta + 2$, then $(*)$ has infinite many solutions. As $d = 1$ this is always the case.
For a particular solution one solves the equation
$$
sa + tb = d \Rightarrow s + 2 t = 1 \quad (\#)
$$
in unknown integers $s$ and $t$ either by using the extended Euclidean algorithm once, or by guessing. Of course $s = 1$, $t=0$ is a solution of $(\#)$.
This leads to the particular solution
$$
(N_0, G_0) = ((c/d) s, (c/d) t) = (\eta+2, 0)
$$
which we could have guessed as well, but we want to execute the systematic algorithm.
Finally the algorithm gives us all solutions as
\begin{align}
(N, G)
&= (N_0 + t (b/d), G_0 - t (a/d))  \quad (t \in \mathbb{Z}) \\
&= (\eta + 2+ 2t, -t) \quad (t \in \mathbb{Z})
\end{align}
Test:
$$
\eta + 2 + 2t + 2 (-t) = \eta + 2
$$
which we might have guessed as well.
The nice thing about the algorithm and its theory is that it tells us that these are all solutions and we get all those solutions nicely parameterized in a linear fashion. So we are finished, regarding integer solutions $(N,G)$.
2. Restricting to non-negative Integers:
Now lets look at the restriction to non-negative integer solutions. This simply means restricting the parameter $t$ according to $-t \ge 0$ for feasible $G$ solutions. To simplify, we switch the direction of the parameter and thus to a non-negative parameter $t \ge 0$ and general solution:
$$
(N, G) = (\eta + 2 - 2t, t) \quad (t \in \mathbb{Z})
$$
where $\eta + 2 - 2t \ge 0$ for feasible $N$ choices. This gives
$$
0 \le t \le \frac{\eta + 2}{2} \quad \wedge \quad t \in \mathbb{Z}
$$
Test:
$\eta = 0$, then we loop $t$ from $0$ upwards, while $t \le 2/2=1$, thus $t=0$ and $t=1$ with the solutions $(N,G) = (2-2t,t)$ thus $(2,0)$ and $(0,1)$.
$\eta = 1$, then we loop $t$ from $0$ upwards, while $t \le 3/2=1+1/2$, thus $t=0$ and $t=1$ with the solutions $(N,G) = (3-2t,t)$, thus $(3,0)$ and $(1,1)$.
$\eta = 2$, then we loop $t$ from $0$ upwards, while $t \le 4/2=2$, thus $t=0$, $t=1$ and $t=2$ with the solutions $(N,G) = (4-2t,t)$, thus $(4,0)$, $(2,1)$ and $(0,2)$.
$\eta = 42$, then we loop $t$ from $0$ upwards, while $t \le 44/2=22$, thus $t=0, t=1. \ldots, t=22$ with the solutions $(N,G) = (44-2t,t)$, thus $(44,0), (42,1), \ldots, (0,22)$.
&c.
Comment: This is awesome! I saw briefly something that looked like parameterizing but I gave up when I failed to see the equation as a linear Diophantine equation. Very impressive, and cool - wish I could accept both answers, but I already wrote the code with 2 loops instead of one!
Comment: No problem. I learned the algorithm myself a few weeks ago, attending a lecture course on elementary number theory, and I am impressed how often such problems arise. I also like that the algorithm stresses the similarity to solving continous linear equations, splitting it into homogenous and particular equation.
Comment: By chance did your lecture course use the book by Forman & Rash? I've been doing some interesting reading in this great, accessible book...
Comment: The course recommends a book from U. Dudley and one from W.W.Adams and L.J. Goldstein.
Comment: Thanks for the references!
Answer: $g, n \ge 0, \quad \eta > 0$

$\eta+2=2g+1n$
$2g = 2 + \eta - n$
$ g = 1 + \dfrac{\eta - n}{2}$
We need to have
\begin{align}
   g &\ge 0\\
   1 + \dfrac{\eta - n}{2} &\ge 0\\
   \eta - n &\ge -2\\
   n &\le \eta + 2
\end{align}
$ \text{Then the acceptable values of n are $\mathbf S = $}
\begin{cases}
 \{0, 2, 4, \dots, \eta + 2\} & \text{If $\eta$ is even}\\
 \{1, 3, 5, \dots, \eta + 2\} & \text{If $\eta$ is odd}\\
\end{cases}$
and the solutions are $(g,n) = \left(1 + \dfrac{\eta - n}{2}, n \right)$
for all $n \in \mathbf S$.
I don't know Maxima, so think of this as pseudo-code.
firstn = if(even(eta), 0, 1)

for(n=firstn, s=0; n<eta+2; n+=2, s++){

   ans[s]: [1 + (eta-n)/2,n]

}


difference between 2 dataframe

Question: Hi i have a very simple question. Why when I do something like that:
import pandas as pd

x1 = pd.DataFrame(np.random.randn(100), columns=['Test'], index=pd.date_range(start='1/1/2018', periods=100))
x2 = pd.DataFrame(np.random.randn(100), columns=['Test2'], index=pd.date_range(start='1/1/2018', periods=100))

z=x1-x2

whereas I was waiting for z containing the difference of x1 and x2, I get a dataframe which has 2 columns:
    Test    Test2
2018-01-01  NaN NaN
2018-01-02  NaN NaN
2018-01-03  NaN NaN
2018-01-04  NaN NaN
2018-01-05  NaN NaN
... ... ...
2018-04-06  NaN NaN
2018-04-07  NaN NaN
2018-04-08  NaN NaN
2018-04-09  NaN NaN
2018-04-10  NaN NaN
100 rows × 2 columns

Thx
Comment: when subtracting on df's, it looks to match the index and column values, and since your column values are different, it returns NaN
Answer: Your columns don't align. Not common columns are found so pandas replaces both missing columns by NaNs.
You should use Series operations:
z = x1['Test']-x2['Test2']

Output:
2018-01-01    1.336094
2018-01-02    0.690228
2018-01-03    1.234907
2018-01-04   -1.536592
2018-01-05   -0.320620
                ...
2018-04-06    2.839609
2018-04-07    0.124360
2018-04-08   -2.229654
2018-04-09   -1.721601
2018-04-10   -1.704309
Freq: D, Length: 100, dtype: float64

Or rename one of the columns:
z = x1-x2.rename(columns={'Test2': 'Test'})

Output:
                Test
2018-01-01  1.336094
2018-01-02  0.690228
2018-01-03  1.234907
2018-01-04 -1.536592
2018-01-05 -0.320620
...              ...
2018-04-06  2.839609
2018-04-07  0.124360
2018-04-08 -2.229654
2018-04-09 -1.721601
2018-04-10 -1.704309

[100 rows x 1 columns]

Comment: and if they are series ?
Comment: @jacques if they are Series, then the operation will occur without alignment on the columns (there are no columns), but alignment on the index will still occur.

difference between 2 dataframe


ubercart - many "in checkout" orders

Question: I have a problem that too many of the orders coming in don't get completed and remain in checkout. It appears as though it doesn't even try to send to paypal.
I don't think that the issue is that the form is failing validation because of 2 reasons:

wouldn't most of these people try to correct their info and submit again?
i have also javascript validation on the page.

This issue has been with me for quite some time, and I would LOVE to get rid of it...
Answer: In checkout is a stage when someone adds something to the cart but does not go through the checkout process. It has nothing to do with the way your site functions. Just the user didn't want to checkout.
This problem (most likely) is Shopping Cart Abandonment (Google it).
UC Followup is a module that helps users push through "Adondoned Carts".
http://www.drupalmodules.com/module/ubercart-followup
Comment: I have the same problem. The functionality is all good. Only thing is if someone fills in invalid fields on the checkout page, he stays on the checkout page and the order is still logged in to "in checkout" mode.

Now if this person fills in the correct information clicks review order again, second order is created "in checkout".
Answer: If you do not mind to alter the core code there is a solution http://www.ubercart.org/forum/support/6399/many_incomplete_orders_in_checkout_status_what_could_it_be

ubercart - many "in checkout" orders


Prove that the set of square matrices $A(x)=\begin{pmatrix} 2x+y & x \\ 3x & 2x+3y \\ \end{pmatrix}$ for $x,y\in [0,1]$ is a compact set.

Question: Prove that the set of square matrices $A(x)=\begin{pmatrix} 2x+y & x \\ 3x & 2x+3y \\ \end{pmatrix}$ for $x,y\in [0,1]$ is a compact set.(Take into consideration metric $d_2...$)
I was thinking to show that this is a linear image between normed spaces, but am not sure how to do that because of $x$ and $y$ thereby showing that it is a continuous function. And everyone knows that the continuous map of a compact set is compact. Could it be that $A(x)$ is accually $A(x,y)$? Its very clear on my page that its $A(x).$
Comment: a matrix function is continuous if each component is continuous
Comment: I need proof of that. :D
Comment: Ultimately it comes down to the fact that all norms on finite dimensional spaces induce the product topology (in particular, they are equivalent).
Comment: @RogerFederer the space of matrices is finite dimensional. don't you have some theorem that says every pair of norms on a finite dimensional space is equivalent?
Comment: I honestly do not have these theorems.
Comment: $|e_i^T (A(x,y)-A(x^*, y^*)) e_j| \le \|A(x,y)-A(x^*, y^*)\| \|e_i\| \|e_j\| to 0$ for $(x,y)\to (x^*, y^*)$ implies that each components of $A$ is continuous
Comment: as for the question, yes continuous image of a compact set is compact again.
Comment: Consider the set $A :=\{{(2x+y,x,3y,2x+3y):x,y\in [0,1]}\}\subset \mathbb{R}^4$. It is enough to show that $A$ is closed and bounded, i think you can proceed.
Answer: The map $x \mapsto A(x)$ is continuous.  The interval $[0,1]$ is compact.  You are now done.  Note that all norms on a finite dimensional space are equivalent.
Comment: All four components are continuous, therefore the map itself is continuous.
Comment: I still do not know why $A(x)$ is continuous. Dont know how to prove this.


Reducing file size of styled images

Question: I always thought styled images are smaller than original ones in file size. So the main reason for styling was to reduce the file size. But today I noticed it isn't always the case. For example:
I downloaded an image abcd.jpg from facebook and then uploaded it to my Drupal website.
Originally the image was 405.3 kB which is 2048px X 1536px.
After downloading the same image from my drupal website the image is 698 kB which is 1100px X 845px.
Style Effect:(Scale width 1100)

And when I checked I found the same in most of the cases. Can anything be done about it without compromising image quality?
Answer: It's in the nature of image compression that compressing an already compressed image can result in larger filesize. The image-toolkit (be it GD or image magick) can not know on what level the image is already compressed and will try to make the best of it (following the quality setting that No Sssweat describes). So you may want to try to set this to 100% to prevent repeated compression.
Further reading:

Efficient Image Resizing With ImageMagick
In search of the most optimized image in Drupal 7
Answer: You can always lower the image toolkit quality
Comment: Thanks. But it will reduce image quality. Looking for something that does not compromise image quality.
Answer: You may choose to use the reSmush.it image style optimizer module, see https://www.drupal.org/project/resmushit
It uses the eponymous service (see https://www.resmush.it/) which optimizes image size without affecting its quality. This optimization service is free (contrary to many other ones).

Reducing file size of styled images


Erro de mapeamento hibernate

Question: Boa tarde pessoa, poderiam me ajudar em um erro de mapeamento?
Classe Event:
@Entity
@Table(name = "EVENT")
public class Event {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", unique = true, nullable = false)
    private long idEvent;

    @Column(name = "name", nullable = false, length = 80)
    @NotBlank
    private String name;

    @Column(name = "DATE_HOUR", nullable = false)
    @NotBlank
    private Date dateHour;

    @Column(name = "AMOUNT_TICKET", nullable = false)
    @NotBlank
    private int amountTicket;

    @Column(name = "VALUE_TICKET", nullable = false)
    @NotBlank
    private double valueTicket;

    @Column(name = "EVENT_EXPIRE", nullable = false)
    @NotBlank
    private Date eventExpire;

    @Column(name = "description", nullable = false, length = 300)
    @NotBlank
    @Lob
    private String description;

    @ManyToOne
    @JoinColumn(name = "EVENT_PLACE", nullable = false)
    private EventPlace place;

    @OneToMany(mappedBy = "event", cascade = CascadeType.ALL)
    private List<Ticket> ticket = new ArrayList<>();

    public long getIdEvent() {
        return idEvent;
    }

    public void setIdEvent(long idEvent) {
        this.idEvent = idEvent;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDateHour() {
        return dateHour;
    }

    public void setDateHour(Date dateHour) {
        this.dateHour = dateHour;
    }

    public int getAmountTicket() {
        return amountTicket;
    }

    public void setAmountTicket(int amountTicket) {
        this.amountTicket = amountTicket;
    }

    public double getValueTicket() {
        return valueTicket;
    }

    public void setValueTicket(double valueTicket) {
        this.valueTicket = valueTicket;
    }

    public Date getEventExpire() {
        return eventExpire;
    }

    public void setEventExpire(Date eventExpire) {
        this.eventExpire = eventExpire;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public EventPlace getPlace() {
        return place;
    }

    public void setPlace(EventPlace place) {
        this.place = place;
    }

    public List<Ticket> getTicket() {
        return ticket;
    }

    public void setTicket(List<Ticket> ticket) {
        this.ticket = ticket;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

Classe PlaceEvent:
@Entity
@Table(name = "EVENT_PLACE")
public class EventPlace {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private long idPlace;

    @Column(name = "NAME", nullable = false, length = 150)
    @NotBlank
    private String name;

    @Column(name = "ADDRESS", nullable = false, length = 150)
    @NotBlank
    private String address;

    @Column(name = "CAPACITY")
    private int capacity;

    @Column(name = "cep", nullable = false, length = 35)
    private String cep;

    @OneToMany(mappedBy = "eventplace", cascade = CascadeType.ALL)
    private List<Event> event = new ArrayList<>();

    public long getIdPlace() {
        return idPlace;
    }

    public void setIdPlace(long idPlace) {
        this.idPlace = idPlace;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getCapacity() {
        return capacity;
    }

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public List<Event> getEvent() {
        return event;
    }

    public void setEvent(List<Event> event) {
        this.event = event;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

O erro gerado no console:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.qintess.apirest.queEvento.models.Event.eventplace in com.qintess.apirest.queEvento.models.EventPlace.event
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at com.qintess.apirest.queEvento.ApirestQueEventoApplication.main(ApirestQueEventoApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_241]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.6.RELEASE.jar:2.2.6.RELEASE]
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.qintess.apirest.queEvento.models.Event.eventplace in com.qintess.apirest.queEvento.models.EventPlace.event
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:844) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:795) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1693) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1661) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1202) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1233) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
    ... 21 common frames omitted

Answer: O problema do código era no mapeamento dos relacionamentos. Além disso, troquei o @NotBlank por @NotNull nos atributos do tipo Date e Integer. O @NotBlank não indicado para esses tipos.
Coloquei o exemplo no Github com um teste unitário para persistir em um banco.
public class EventPlace {
        @OneToMany(mappedBy = "place")
        private List<Event> event = new ArrayList<>();
    }

    public class Event {
        @ManyToOne
        @JoinColumn(name = "EVENT_PLACE_IDPLACE", referencedColumnName = "id")
        private EventPlace place;
    }

//classes completas
@Entity
@Table(name = "EVENT_PLACE")
public class EventPlace {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private long idPlace;

    @Column(name = "NAME", nullable = false, length = 150)
    @NotBlank
    private String name;

    @Column(name = "ADDRESS", nullable = false, length = 150)
    @NotBlank
    private String address;

    @Column(name = "CAPACITY")
    private int capacity;

    @Column(name = "cep", nullable = false, length = 35)
    private String cep;

    @OneToMany(mappedBy = "place")
    private List<Event> event = new ArrayList<>();

    //getters and setters

}

    @Entity
    @Table(name = "EVENT")
    public class Event {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID", unique = true, nullable = false)
        private long idEvent;

        @Column(name = "name", nullable = false, length = 80)
        @NotBlank
        private String name;

        @Column(name = "DATE_HOUR", nullable = false)
        @NotNull
        private Date dateHour;

        @Column(name = "AMOUNT_TICKET", nullable = false)
        @NotNull
        private int amountTicket;

        @Column(name = "VALUE_TICKET", nullable = false)
        @NotNull
        private Double valueTicket;

        @Column(name = "EVENT_EXPIRE", nullable = false)
        @NotNull
        private Date eventExpire;

        @Column(name = "description", nullable = false, length = 300)
        @NotBlank
        @Lob
        private String description;

        @ManyToOne
        @JoinColumn(name = "EVENT_PLACE_IDPLACE", referencedColumnName = "id")
        private EventPlace place;

    //getters and setters
}

Erro de mapeamento hibernate


Creation and display of song setlists

Question: I am using Drupal version 7.42 and a content type used for information regarding Concert setlists. It includes labels for:

Date.
Venue.
Location.
Setlist.
Description.
Lineup.

I will give you an idea of what I am looking to achieve in the end regarding its display. I also have a content type for the Songs.
Each performance listing will be different. I will have some listings that show Songs known to be performed yet the Setlist isn't complete. I will have some listings that show songs known to be performed in:

Set 1.
Set 2.
Encore.
etc.

Also, some performances may have more than one encore, so I also will have performances noted with Encore 1, Encore 2, etc. if the listing requires it.
How do I manage to get the display of the setlist to show a label above the songs indicating the song placement?
I thought having multiple fields in the content type (Set 1, Encore, Encore 1, Encore 2, etc) does the trick. But with time mulling over this one I am thinking is it possible to be achieved by just having one setlist field (Setlist) instead of multiple setlist fields in the content section?
Below is an example of the display I am describing for site viewers to see when visiting a performance page. Each song listed in a performance page at the moment uses Entity Reference to link to its unique song within the Songs content type.

Set:

Song 1
Song 2
Song 3

Encore 1:

Song 4
Song 5

Encore 2:

Song 6

Any suggestions?
Comment: Are you aware that the rule around here (on this site) is like "1 question at a time"? It's fine to ask (post) multiple questions at once though (and linking from one question to another as like a related or followup question) ... By splitting your questions, you also have a choice of picking (= marking as accepted) the answer that best fits for a specific question. That's not possible by posting the 3 questions together ... Maybe you should MOVE question 2 and 3 to a separated one? Even if it was only because otherwise your question may be put on hold with reason like (eg) "Too broad" ...
Comment: @Pierre.Vriens fixed. sorry about the mishap. thank you for the tips!
Comment: OK, thank you for taking my advice ... Now we are cooking! Next: let's start to think about an answer ... PS: where did the other 2 questions go ???
Comment: @Pierre.Vriens i understand your reasoning and took your advice about splitting up questions, so i removed them for now. i will ask the other two later on once this one gets answered. one question at a time.
Comment: I tried to improve the formatting of your question, please review/check it, and further adapt/refine where appropriate. Worst case: perform a "rollback" (to completely undo my edits). PS: while doing so, I also posted an answer ... Curious about your feedback about it ...
Comment: I think it might help if you also (briefly) explain what you mean by "performance" (and "performance listing"). Also, the "set" and "encore" occurrences are a (very little) bit hard to understand, maybe you can think of some replacement of it (at least the "Encore", the French for "some more" ???). Also: "setlists" and "listings", so many "list"-things ...
Comment: is **set**, **encore 1** and **encore 2** seperate entity references fields?
Comment: @Pierre.Vriens thank you. i will review your module and see if it fits my idea. thank you. by "performance" i am talking about a concert performance - the show that is performed. set, encore and all tie into song placement of a set list. an artist will perform a main set then usually take a break for an encore where they perform a few more songs. also, thank you for formatting my question to make it easier for the eyes. my mistake.
Comment: @NoSssweat Yes. I have the following separate entity reference fields within the Tour content type:

**Set 1** (also known as the main set of a concert performance)
**Set 2** (i have this one in the event an artist has two sets within a performance)
**Encore** (i have this field in the event the show has strictly one encore)
**Encore 1** (the field is to mark the first encore if another one takes place after it)
**Encore 2** (the field marks the second encore)
Comment: Aha, now I get the "encore" part of it, it's really like in French ... But around here they just call that "bis", "bis", "bis" (variation: "we want more", "we want more" ...). PS: not "my" module (I'm just a co-maintainer) ...
Answer: Below is a possible approach you may want to consider. It's using "State" names (like Florida, Illinois, etc.) instead of "Set 1, Set 2, etc" and "Cities" instead of "Songs".
If I was to implement this in a Drupal site, I'd use either of these "displays":

Option 1 - Master detail with nested blocks
Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".

Option 2 - Report that filters based on some lookup
Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "How did you do that?!?!" ... then this is the answer: that's really a piece of cake using the Forena module. Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead, but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).
Disclosure: I'm a co-maintainer of Forena.
Answer: Views tree

This module provides a tree-based style plugin for Views. It is
equivalent to the tree-based style template from Views 1.
It is based off of the list style. Although it generates a nested
view, there is still only a single query run for the view making it
quite performant.
Compatibility
This module has been tested and used with the following
relationship-oriented modules:

Taxonomy (in core) - parent/child relationships References - node and
user references Relation
references between any entities (D7 only)
Entity reference - references between any entities (D7 only)
Organic Groups (D7 only)

Example:

Creation and display of song setlists


Creating loop to parse table data in scrapy

Question: I am trying to loop through the table rows with the following HTML. I am using the following xpath selector //*[@id="employee-table"]/tbody/tr but it doesn't work.

 Name 	 Year 	 Title 	 Agency 	 Location 	 Salary

A G. Bharatkumar	2015	Medical Officer	Veterans Health Administration	Wisconsin	$335,000

A Rafael Roure	2015	Medical Officer	Veterans Health Administration	Florida	$333,634

Aaron S. Dumont	2015	Medical Officer	Veterans Health Administration	Louisiana	$330,302

Aaron T. Andrews	2015	Medical Officer	Veterans Health Administration	Florida	$350,000

Abdolali Elmi	2015	Medical Officer	Veterans Health Administration	West Virginia	$325,056

Abdul A. Haleem	2015	Medical Officer	Veterans Health Administration	Missouri	$351,056

Abner M. Ward	2015	Medical Officer	Veterans Health Administration	Hawaii	$337,756

Adam C. Cohen	2015	Medical Officer	Veterans Health Administration	Indiana	$340,000

Adam J. Bakker	2015	Medical Officer	Veterans Health Administration	Minnesota	$325,980

Adam S. Bracha	2015	Medical Officer	Veterans Health Administration	Florida	$335,000

Comment: It worked for me using `lxml` => `r = tree.xpath('//*[@id="employee-table"]/tbody/tr')`
Comment: Try using this selector `//*[@id="employee-table"]/tbody/tr[@role="row"]`
Answer: Try //*[@id="employee-table"]/tr
The reason of why your xpath doesn't work is becuase of tbody. You have to remove it and check if you get that result that you want.
You can read this in scrapy documentation: http://doc.scrapy.org/en/0.14/topics/firefox.html

Firefox, in particular, is known for adding
 elements to
  tables. Scrapy, on the other hand, does not modify the original page
  HTML, so you won't be able to extract any data if you use
 in
  your XPath expressions.


Dropzone.js/jQuery conflict

Question: I've got an app that has a Dropzone.js zone (two actually, on one page) alongside some custom jQuery. The custom jQuery (below) works fine.
function changeImage() {
  var self = $(this),
      src = this.value,
      thumbs = self.closest('.form-group').siblings('.selector_thumbnails');

 thumbs
     .find('img')
     .hide()
     .filter('#' + src)
     .show();
}

$('.thumbnail_selector')
    .change(changeImage)
    .trigger('change');

The corresponding HTML is as follows:

    <%= f.input :cover_id, collection: @covers.reverse, as: :select, include_blank: true, input_html: { class: 'thumbnail_selector' } %>

      <% @covers.each do |cover| %>
        <%= image_tag(cover.cover(:cropped), id: cover.id, class: 'thumbnail') %>
      <% end %>

All that, though, prevents Dropzone from working. If I remove that code Dropzone works fine. What am I missing?
Here's my console (which is a Dropzone error, seemingly caused by the above JS):
Comment: Are you sure `'#' + src` isn't evaluated to just `#`?
Comment: Not 100%, and I'm not too sure how to check. The functions works as wanted, though—and each image I'm switching to has an ID of `this.value` seen above.
Comment: Run `console.info('#' + src)` and look at the console output.
Comment: Yeah, correct: `#132` and similar.
Comment: Oh, goddammit, I figured it out. The include_blank in the select was breaking the jQuery. How embarrassing.
Comment: Ids cant start with a number. `#a123` would be valid, `#123` isn't.
Answer: The problem was that the jQuery was trying to read the .value of the include_blank: true setting. So, solution:
function changeImage() {
  var self = $(this),
      src = this.value,
      thumbs = self.closest('.form-group').siblings('.selector_thumbnails');

  if (src) {
    thumbs.find('img').hide().filter('#' + src).show();
  } else {
    thumbs.find('img').hide();
  }
}

Done.

Dropzone.js/jQuery conflict


Exponential Diophantine: $2^{3x}+17=y^2$

Question: Is there a way of solving the following equation, in integers $(x,y)$, by hand? :
$2^{3x}+17=y^2$.
You can also try: $2^{2x}+17=y^2$ or more generally $2^x+17=y^2$; each of these has at least 1 solution.
I used the elliptic curve $x^3+17=y^2$ to make this, since it had 3 solutions where $x$ is a power of 2. These are:
$(x,y)\in \{(2,\pm5), (4,\pm9), (8,\pm23)\}$.
Comment: Have you tried subtracting $16$ from both sides, then factoring them ?
Comment: Are you asking a question here, or are you just giving us orders?
Comment: It seems likely you know more about the problem than was stated.  Such "questions" make it especially hard to guess what your real motivation is in asking, and discourage the Reader from making any lengthy response that might be redundant (or beyond your level of interest).
Comment: Perhaps you could add the "3 solutions where $x$ is a power of 2", referring to the last statement of your Question (using $x$ in a different sense than in the rest of the body and title).
Answer: $2^x+17=y^2$ leads to the three elliptic curves $y^2=u^3+17$, $y^2=2u^3+17$, and $y^2=4u^3+17$ (depending on $x$ modulo $3$). There are standard techniques for solving these, that is, for finding all the integral solutions. Indeed, you can write each one as a Mordell equation, $Y^2=U^3+k$; for example, from $y^2=4u^3+17$ we get $16y^2=64u^3+272$, so $Y^2=U^3+272$. Solutions to Mordell equations for various ranges of values of $k$ have been tabulated, and it should be easy to find the tables by searching the web for "Mordell equation".
$2^{2x}+17=y^2$ is easy. It's $y^2-r^2=17$, which has only the solutions $y=\pm9$, $r=\pm8$, so $x=3$.
Comment: Sure there is. It says on that page there is one known solution, $x=8$.


maven-surefire-plugin and ReportNG cannot change stylesheet for the test report

Question: I like to change style (use another .css than reportng.css) on the standard report from ReportNG using Maven. My pom.xlm  looks like this
...
<code><build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                  <configuration>
                    <properties>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>false</value>
                        </property>
                        <property>
                            <name>listener</name>
                            <value>org.uncommons.reportng.HTMLReporter,org.testng.reporters.EmailableReporter</value>                             </property>

                    </properties>
                    <systemProperties>
                        <property>
                            <name>org.uncommons.reportng.title</name>
                            <value>My own titel in Test Report</value>
                        </property>
                        <property>
                            <name>org.uncommons.reportng.stylesheet</name>
                            <value>${project.basedir}/src/report/resources/MyTestReport.css</value>
                        </property>
                    </systemProperties>
</code>
...
I can change title but when I try to do the same with systemproperty org.uncommons.reportng.stylesheet I just get the default report. Have some one had the same problem and how did you solve it?
Best regards
Annika
Answer: I thought I had the same problem because I was expecting to see the CSS file I specified embedded on all pages.
Instead, it looks like ReportNG takes the styles from the css you specify (MyTestReport.css in your example above) and puts it into the generated custom.css file that is embedded on all pages.
Check **/surefire-reports/html/custom.css. Your styles should be there (assuming the path to your CSS is correct).


TypeError: this._connection.open is not a function

Question: Estou fazendo atividade para aprender sobre o NodeJS e o MongoDB, e durante o projeto, tenho o erro abaixo:
TypeError: this._connection.open is not a function

Como ainda estou em fase de aprendizado, não consegui entender bem, mas me parece que o problema é com o "open".
O arquivo UsuariosDAO, tem o seguinte código:
function UsuariosDAO(connection){
    this._connection = connection();
}

UsuariosDAO.prototype.inserirUsuario = function(usuario){
    this._connection.open( function(err, mongoclient){
        mongoclient.collection("usuarios", function(err, collection){
            collection.insert(usuario);

            mongoclient.close();
        });
    });
}

module.exports = function(){
    return UsuariosDAO;
}

E parte do arquivo cadastro.js que aparece relacionado no erro:
var connection = application.config.dbConnection;
var UsuariosDAO = new application.app.models.UsuariosDAO(connection);

UsuariosDAO.inserirUsuario(dadosForm);

Enfim, qual seria a melhor solução para este problema?
Comment: O erro é claro, a propriedade `open` não é uma função, logo ao chama-la causa essa exceção. Não da pra ajudar mais que isso sem ter o resto do código relacionado a `_connection`
Comment: Poste o código na sua pergunta... Não dá pra ajudar sem ver onde está o erro!
Comment: Acabei de modificar a pergunta, inserindo o código.
Answer: Consegui resolver após remover a versão mais recente do módulo npm do MongoDB e instalando a versão a seguir:
npm install --save firstname.lastname@example.com


efficient db operations

Question: Here is the scenario I am researching a solution for at work. We have a table in postgres which stores events happening on network. Currently the way it works is, rows get inserted as network events come and at the same time older records which match the specific timestamp get deleted in order to keep table size limited to some 10,000 records. Basically, similar idea as log rotation. Network events come in burst of thousands at a time, hence rate of transaction is too high which causes performance degradation, after sometime either server just crashes or becomes very slow, on top of that, customer is asking to keep table size up to million records which is going to accelerate performance degradation (since we have to keep deleting record matching specific timestamp) and cause space management  issue. We are using simple JDBC to read/write on table.  Can tech community out there suggest better performing way to handle inserts and deletes in this table?
Comment: Do you have any numbers on the magnitude here ? 10k or even 2 million records is in itself very little. Then again it's quite a lot if you get bursts of 2 million records every second, while 2 million per hour isn't so much. Also, provide the DB schema for this table, including the indexes you have and typical queries you do will help a lot in suggesting improvements.
Answer: I think I would use partitioned tables, perhaps 10 x total desired size, inserting into the newest, and dropping the oldest partition.
http://www.postgresql.org/docs/9.0/static/ddl-partitioning.html
This makes load on "dropping oldest" much smaller than query and delete.
Update: I agree with nos' comment though, the inserts/deletes may not be your bottleneck.  Maybe some investigation first.
Comment: I would settle for 24 partions, 1 partition for every hour of the day. And then use TRUNCATE on the partitions that can be emptied because TRUNCATE doesn't need VACUUM.
Comment: Thanks a lot for quick and very helpful responses. I just started here last week, I will investigate more on our db schema, indexes, queries and what else can be bottleneck and soon will post all the details.
Answer: Some things you could try -

Write to a log, have a separate batch proc. write to the table.
Keep the writes as they are, do the deletes periodically or at times of lower traffic.
Do the writes to a buffer/cache, have the actual db writes happen from the buffer.

A few general suggestions -

Since you're deleting based on timestamp, make sure the timestamp is indexed. You could also do this with a counter / auto-incremented rowId (e.g. delete where id< currentId -1000000).
Also, JDBC batch write is much faster than individual row writes (order of magnitude speedup, easily). Batch writing 100 rows at a time will help tremendously, if you can buffer the writes.

efficient db operations


All possible combinations for large numbers in R

Question: Image i have a sequence like this:
seq <- rep(0:9, 10)

I want to know all possible combinations of this sequence. For sure, command combn isn't working:
> comb <- combn(seq, 10)
Error in matrix(r, nrow = len.r, ncol = count) :
  invalid 'ncol' value (too large or NA)
In addition: Warning message:
In combn(seq, 10) : NAs introduced by coercion to integer range

Can you give me a hint how to make my own function for all possible combinations?
Comment: There are 10^10 possible combinations, that is probably why it is giving the error.
Comment: @Lesley , do you mean all combinations of the vector  c(0,1,2,3,4,5,6,7,8,9) ?
Comment: @ytk, absolutely yes, and would be nice to avoid this problem. Unfortunately, I don't know how and need  a little push to keep going.
Comment: @Koba, yes. I have to get all possible numbers from 0 to 9, for example:
1234567890
3216549870 and so on...
Comment: That should be permutations instead of combinations. package `gtools`. `gtools::permutations(10,10,0:9)` # R version 3.5.3 [is-there-an-r-function-to-get-the-number-of-permutations-of-n-objects-take-k-pn](https://stackoverflow.com/questions/2871763/is-there-an-r-function-to-get-the-number-of-permutations-of-n-objects-take-k-pn/56436850#56436850)

or package `prob`. `prob::permsn(0:9,10)`
Answer: Based on your reply to the comment , here is one thing you can do . You need the combinat package installed for this to work.
library(combinat)
seq <- c(1,2,3,4,5,6,7,8,9,0)
permn(seq)


IBM ServerRaid 8K and Sata1 issue

Question: I have a X3400 with 8 x (43w7598 250GB SATA 3GB/S HDD) set in the frontal bay and connected to ServeRaid 8K controller.
The raid array works well but, even if I set the controller PHY to 3.0 (rather then Auto or 1.5), all the disks negotiate 1.5Gb/s with the controller.
This sounds really weird to me because the disk are WD Caviar Black Sata2 disks (bought from IBM).
The firmware is the latest available from IBM (accordingly to the IBM ServeRaid matrix). Any tip?
Comment: same here. Even IBM can't (doesn't want) answer. It could even be that we see 1.5 but it works at 3.0. It's hard to say because they are in raid and I can't compare the speed with any other similar hardware
Comment: I have the same issue on an x366 w/ ServeRaid 6 and two drives (WD I think, not sure). They were previously physically limited (jumper) on another system, but even without the jumper, it doesn't work faster...
Answer: The reason your Sata drives are running at 1.5Gb/s vs 3.0Gb/s on your server is because their was a bug in the backplane that caused 30 second freezes under heavy workloads. I have an X3650 which I believe has the same backplane as yours. I'm also running Serveraid 8k.
They found out that the SAS expander that bridges to the Sata devices had a limitation that prevented it from operating at 3.0Gb speeds on SATA II devices. Here is the actual link to the article.
http://www-947.ibm.com/systems/support/supportsite.wss/docdisplay?lndocid=MIGR-5071075&brandind=5000008
It really sucks because I spent a lot of money loading up the server with a couple of X25-E SSD drives, only to find out that they're stuck running at SATA1 which not only limits the performance, but cripples IO bandwidth on the HDD itself.
Comment: thank you very much for pointing me to that page. I'm not sure if the backplane is the same but I was pretty sure that there was something wrong.
You are right, this sucks and I'm tired to deal with several thousands dollars servers with any kind of hardware issue: and this happens with HP and IBM ... it seems that is considered "normal" by any brand ... China effect?
Answer: Tell me about it. It's almost more cost effective to just build a server with off the shelf products. I'm going to look into an external enclosure to see if I can run SAS drives on the server and SATAII SSD's on an external enclosure.
Comment: if you are looking for an external enclosure I suggest products like this http://www.lindy.it/storage-system-19-sas-sata-raid-3u-16-alloggiamenti/21953.html attached to a ServeRaid with multilane ports. Careful: often ServeRaid don't support disks bigger than 1TB

IBM ServerRaid 8K and Sata1 issue


Am I intepreting the repeat signs correctly?

Question: So this is a pretty simple question, but I haven't found anything that looks exactly like the piece of music I'm trying to learn, so I have to ask. Am I interpreting the repeat signs in this image correctly if I:

Play section 1
Go back to the beginning of the piece
Play section 1 and section 2
Go back to the "right-facing" repeat sign at the beginning of section 2
Play section 2 through to the end
Comment: Just wait 'til you get to  "del Segno a Coda"  :-) .
Comment: I think you got the answer you needed, but a tip for the future: add measure numbers. @Richard's answer basically applied that. With measure numbers you will play measures 1,1,2,2. And as Carl Witthoft points out, there are more complex repeat symbols like 'segno' and 'coda'... and 'volta' endings, etc. Listing the exact performance using measure numbers will make those repeats perfectly clear.
Answer: Exactly correct!
Put another way, you'll be performing the numbered sections as "1122" before proceeding to whatever music (if there is any) that succeeds the closing repeat at the end of Section 2.
Comment: @tim I would think it's like a courtesy accidental,not necessary to write because it is implied but is there as a reminder or to make it clearer for the performer.
Comment: Richard, thanks very much. I hadn't even thought of what it would mean if there was more music after section 2 (there isn't in the piece I'm learning), but that extra information makes it even clearer! Thanks again!
Comment: A thought occurred - why have some songs had a repeat sign placed after the clef sign? Seems superfluous - just bad writing?


What is meant by "large scale tonal organization?"

Question: I found this in a CD liner note.  "the work shows the influence of Beethoven in its dramatic contrasts and its feeling for large scale tonal organization."
What does this mean?
TIA
Answer: "Large scale tonal organization" refers to planned key relations extended in time. Relating the first and last movement in symphonies for example. Mozart and Beethoven did this a lot.


Fresh install of Rocky 8, networking is not working correctly

Question: I am "upgrading" a server from CentOS 7 to Rocky 8. This server is a 1U Supermicro SYS-1029U-TRT, works as part of an HPC, and has two Ethernet and one Infiniband networking interfaces. One of the Ethernet interfaces is for the HPC, the other is used for the server room network and Internet access.
After bringing up a VM copy of the CentOS server I started a fresh install of Rocky 8. I reused the previous partition table and mdadm RAID that was already configured and formatted each partition. After the install and initial set up of the networking interfaces the server is exceptionally slow when dealing with any network traffic through the "external" interface. This issue was never evident under CentOS and has multiple symptoms.

DNS queries do not get completed. This is seen especially well when
running a ping on a host on the local network or attempting to
download a file from the Internet or a local web server via curl or
wget.
Pings to and from the server, using IP only, will either
fail or start working after some, usually about 4, packets fail.
SSH connections to the server mostly fail with some attempts getting
a password prompt but the login never completes.

I have attempted a number of troubleshooting steps with no apparent fix yet.

I verified that the IP settings, routing table, and resolv.conf were all correct.
I disconnected both of the HPC network interfaces. I also tried with the interfaces connected but deactivated, with no configuration, and with them connected and configured.
I verified that the Ethernet drivers were correct for the hardware. The system includes two 10Gbps Intel X540-AT2 interfaces which is using the kernel's ixgbe driver. I also downloaded and installed the latest version of Intel's driver.
I verified that the switch port is properly configured, including the VLAN and MTU settings.
I tested the other two interfaces via ping both to and from the server and both showed no issues.
I disconnected the interface from the usual switch and used a new cable to connect it to a nearby switch on the same VLAN.

None of those steps changed a single thing. I'm out of ideas and am looking for further possible reasons for why this is occurring. If any information is needed I'll gladly add it as requested.
A previous issue that was not reported when CentOS 7 was installed is that sometimes a SSH connection would "pause" for up to a minute before being usable again. This is similar to the current issues to make me think this is a hardware issue.
Here are some ip command outputs, ip a and ip route, to show how things are configured. Also when configuring in nmtui I enabled the "Never use this network for default route", "Ignore automatically obtained routes", and "Ignore automatically obtained DNS parameters" settings on the eno2 and ib0 connections. None of these settings are enabled on the eno1 connection.
<code>[root@hostname ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether ac:1f:6b:c9:b3:6e brd ff:ff:ff:ff:ff:ff
    altname enp24s0f0
    inet 10.0.21.150/22 brd 10.0.23.255 scope global noprefixroute eno1
       valid_lft forever preferred_lft forever
3: eno2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether ac:1f:6b:c9:b3:6f brd ff:ff:ff:ff:ff:ff
    altname enp24s0f1
    inet 10.33.0.110/22 brd 10.33.3.255 scope global noprefixroute eno2
       valid_lft forever preferred_lft forever
4: ib0: eno2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 4092 qdisc mq state UP group default qlen 256
    link/infiniband 00:00:01:20:fe:80:00:00:00:00:00:00:0c:42:a1:03:00:c0:af:08 brd 00:ff:ff:ff:ff:12:40:1b:ff:ff:00:00:00:00:00:00:ff:ff:ff:ff
    inet 10.33.4.110/22 brd 10.33.7.255 scope global noprefixroute ib0
       valid_lft forever preferred_lft forever
[root@hostname ~]# ip route
default via 10.0.20.1 dev eno1 proto static metric 100
10.0.20.0/22 dev eno1 proto kernel scope link src 10.0.21.150 metric 100
10.33.0.0/22 dev eno2 proto kernel scope link src 10.33.0.110 metric 101
10.33.4.0/22 dev ib0 proto kernel scope link src 10.33.4.110 metric 150
</code>
Edit1: Added more info, the CentOS issue.
Edit2: Added requested ip command outputs and some nmtui settings.
Comment: What's the output of `ip route` and `ip a`?
Answer: This was found to be a true networking issue, conflicting MAC addresses.
When I created the VM copy I duplicate the MAC address of the interface from the hardware with the intention to change it after the VM was verified as working. Then I forgot to change it.
Removing the duplicated MAC address from the VM and allowing it to be randomized solved the issue.


Stored procedure transferring new records to linked server losing connection

Question: Let me preface this by saying I am not a sql expert.  Thanks in advance for reviewing my question.
I am having some trouble with a stored procedure that periodically loses it's connection to a linked server in the middle of transferring new records to a table there (a lot of records).  I'm wondering about some things.
First, is there a better way to complete the task that is faster and more efficient?
And second, is there a way to better handle the loss of connection attempting to re-try the previous step in an effort to continue where it left off, possibly after waiting 15 or so minutes in case there is some temporary disconnect with the linked server (that may last more than what is allowed before terminating)?
Also I'm curious, when something like the highlighted step takes place, if the sql is being executed against the linked server, and the connection is lost, does sql attempt to reconnect and continue for a timeout period or since this is a compare statement does it just break?  I don't really understand how it works.
Here is the section where connection loss is most common, usually occurring in the first insert statement (first step within begin catch block):
<code>UPDATE [LINKEDSERVER.XYZ.COM].dest_database1.dbo.run
  SET last_result = 32
  WHERE type = 158;

BEGIN TRY
    INSERT INTO [LINKEDSERVER.XYZ.COM].[dest_database2].dbo.table1 ( CID , BID , Question1 , Question2 , Question3 , Question4 , Question5 , Question6 , Question7 , Question8 , Question9 , Question10 , Comments , EmailAddress , Name , Address , Address2 , City , State , Zip )
    SELECT src.CID , src.BID , src.Question1 , src.Question2 , src.Question3 , src.Question4 , src.Question5 , src.Question6 , src.Question7 , src.Question8 , src.Question9 , src.Question10 , src.Comments , src.EmailAddress , src.Name , src.Address , src.Address2 , src.City , src.State , src.Zip
      FROM table1 AS src LEFT OUTER JOIN [LINKEDSERVER.XYZ.COM].[dest_database2].dbo.table1 AS dst ON src.CID = dst.CID AND src.BID = dst.BID
      WHERE dst.CID IS NULL;

    INSERT INTO [LINKEDSERVER.XYZ.COM].[dest_database2].dbo.table2 ( CID , AccountNumber , Name , Address , Address2 , City , State , Zip , BShort, EmailAddress )
    SELECT src.CID , src.AccountNumber , src.Name , src.Address , src.Address2 , src.City , src.State , src.Zip , src.BShort, src.EmailAddress
      FROM table2 AS src LEFT OUTER JOIN [LINKEDSERVER.XYZ.COM].[dest_database2].dbo.table2 AS dst ON src.BShort = dst.BShort
      WHERE dst.BShort IS NULL;
END TRY
BEGIN CATCH
    SELECT @ErrorCode = @@Error;
    SELECT @ErrorResult = 109;
    SELECT @ErrorMessage = 'Failed Copy ' + CAST ( @ErrorCode AS varchar ) ;
    GOTO ExitWithError;
END CATCH;

INSERT INTO [LINKEDSERVER.XYZ.COM].dest_database1.dbo.system_log ( notes , log_type , source_type , parent_id )
VALUES ( 'Copied tables xyz ' , 45 , 58 , 0 ) ;

UPDATE [LINKEDSERVER.XYZ.COM].dest_database1.dbo.run
  SET last_result = 31
  WHERE type = 158;
</code>
I understand that if the connection is lost, my catch block doesn't execute, so ExitWithError isn't used.  And I think I understand when the connection is lost, a rollback occurs (not sure how/if this works with linked servers because some of the records are transferred when this happens), and it just quits executing everything - because neither the catch is executed or the statements after the entire begin catch block.  I was hoping to, in the event this occurs, log something so that the stored procedure, when it runs again (set to run every 30 min until successful), it can pick up where it left off, because I have code in the beginning that looks for the last status/log entries and determines what to do.  Is there a better way to handle this?
Answer: So first tip, Do the stored procedure from the other server (destination) if you can.  In other words switch the local and the linked server.  The reason is I have had significantly improved performance to a DML (insert/update/delete) command from a Linked Server to a local table.  When doing the DML into a linked table the performance stinks!
Next effectively use the ids, are they sequential?  Can you just take the MAX of what is at the destination server instead of having to Join large tables between the servers?
If you cannot count on sequential then you can build a temp table on the source server and filter there instead of trying to do it across tables.  If just ids you can also try to pass XML in nvarchar format back and forth.  Or you can maintain a tracking table on the source so you know what ids have already been processed using the OUTPUT inserted.id INTO .... from your insert statement.
Finally set your procedure to batch/cut up and do the transactions in smaller chunks such as SELECT TOP x# of records at a time.  You can still place the whole thing in a while loop so that it does it all in one execution of the proc, but then you can do your transactions in smaller more manageable pieces.
Comment: The source server is behind a very secure firewall and can't be exposed so that the other server could instead pull the data. At least I think that's the case.

The IDs are not numeric or sequential. But maybe I can create a new one that is.  I will look into this, thanks for the suggestion.

Your 3rd and 4th suggestions are interesting.  Can you give me a little more detail on the use of OUTPUT inserted.id INTO...

Also, do you have any idea of what actually happens when connectivity is lost? Does sql just stop executing or is there a way to handle it better?

Thanks very much.
Comment: when you loose the connectivity your transaction is rolled back and your temp tables are cleared from memory. here is a link on output inserted.id into http://stackoverflow.com/questions/6292154/output-to-temporary-table-in-sql-server-2005.  AS far as 3 or 4 they are kind of big topics but I might come back to it eventually if I have time this weekend.  As far as firewall I would recommend checking it would be a huge performance impact to pull from a linked server rather than push to a linked server.
Comment: how many records are you talking about being in your source and destination?
Comment: 2 mil in one, 12 mil in another, on each source and destination


localStorage - save input value after Spotify Access Token refresh

Question: I'm making a ReactJS app and I'm trying to save the search input value after my Spotify API refreshes and gets the access token. For example, here are the steps:

Learner searches a term
The Spotify API goes fetches the access token and refreshes the page

From step two, I would like the search term to be still inside the search input field (after the refresh).
Here is my attempt:
constructor(props){
    super(props);

    this.state = {
        term: ''
    };

    ...

    document.getElementById('search-input') = window.localStorage['term'];
}

...
search(){
    this.props.onSearch(this.state.term);
    window.localStorage['term'] = this.state.term;
}

...
    render(){
        return (

                  <input id="search-input" onChange={this.handleTermChange} autoFocus/>
                  SEARCH

        );
    }

Thanks for the help!
Answer: Rather than setting and getting your localStorage value with window.localStorage['term'], you'll want to use the built-in get and set methods.
localStorage.setItem(key, value)
localStorage.getItem(key)

Here's an example from MDN.