text:
Q: How recover deleted files from other computer? I moved a html file from my computer to another and accidentally deleted it from that computer which I accessed from my computer like this: \\name\folder
As a result the file did not go recycle bin. I tried ntfsundelete and it did found the file on my computer but when I recovered, it looks like as if you opened binary file with notepad. I then tried Recuva and it says that part of the file is overwritten.
Is there any chance to recover it? Can I recover it from another computer?

A: Your best bet would be to turn the computer off now and then run something like GetDataBack NTFS in various modes (undelete, systematic damage, sequential damage) and see if you can recover the file. Depending on how big the hard drive is you're going to be there for a while.

*

*DO NOT USE THAT HARD DRIVE, if you access it for anything other than reading then you are at risk of overwriting the file more (Make sure you know what "read" is, don't browse the drive: explorer.exe writes metadata, thumbs.db etc)

*If the file has been overwritten... the file has been overwritten. Restore from a backup.

A: If data recovery didn't work on your PC, try the PC you moved the file from. No, you cannot do this remotely. (Or at least, shouldn't).
Personally I like the command line tool findntfs.
As taspeotis says, you should be careful not to write to the drive. If it is the system drive, you should not boot it as lots of disk writes occur at boot. Ideally, mount the drive in read-only mode.
There are lots of threads on superuser about data recovery.

A: No way, you can't recover deleted files from the other computer but the one that you deleted your data and files from.
There are some 3rd party recovery tool that claim they can do the job for you. You may try! Like Recuva - Freeware.


text:
Q: Access "create emails" tracking for compiling data In Access there is a feature called "Create email" whereby you can select a table and send rows to users to fill in data.
When they reply to the email, Access automatically updates with the data they have entered.
Thats great if each user only has one or two rows of data to fill in, but if they need to fill in a large quantity of data, they might only get round to filling in a few records at a time, and potentially not in the same order as is in the database.
How can users keep track of what they have updated and what they havn't?
Does this functionality exist or is this something that Access can't handle?
Many thanks
John

A: Hardly anything can handle this, because you have no control of what the user may do with your e-mail. Further, you often have to rely on one e-mail client only like Outlook which never will be true in real life where people read mail on all sort of devices.
The best option is to forward a link to a site where the user can input data and where you have full validation of these, and where the collected data are ready for import in your database in a controlled manner.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't deploy using serverless framework from Windows 10 Attempt to deploy via serverless framework using Windows 10 fails:

C:\Users\xxxxxx>sls deploy --verbose  Serverless: Packaging
  service...  Serverless: Excluding development dependencies...
Error --------------------------------------------------
EPERM: operation not permitted, scandir
  'C:\Users\xxxxxx\AppData\Local\ElevatedDiagnostics'  For debugging
  logs, run again after setting the "SLS_DEBUG=*" environment variable.

Your Environment Information -----------------------------  OS: win32
  Node Version: 6.11.2  Serverless Version: 1.19.0
Tried again with command prompt under elevated privileges:

EBUSY: resource busy or locked, scandir
  'C:\Users\xxxxxx\AppData\Local\Microsoft\InputPersonalization\TextHarvester\WaitList.dat'

I assumed there was a permissions issue at first so I retried with the command prompt at full admin mode but just ran into the the second error.  My research suggested an issue with windows search so I turned it off (and also all background apps). Trying again (and again) I just ran into more similar issues and am unable to deploy anything. Anyone had similar issues and found a way around them?

A: I worked it out finally, so in case anyone else encounters this issue here is a summary.  There seem to be 2 issues:

*

*Don't create functions in your root folder.  Create a specific folder for your serverless function i.e. not in C:\Users\nnnnnn> but within your regular document storage.  In Windows 10 it works nicely if you use a OneDrive folder, with the benefit that your function(s) are also then replicated to other dev machines that you might use (and are automatically backed up offsite).

*More importantly, the serverless framework seems to have an issue if you attempt to deploy to a region other than the default region set in your aws CLI configuration.  I've no idea why this should be since the credentials I use with the AWS CLI are authorised for all regions.  I also have no idea why the issue should result in serverless attempting to access a whole series of windows files for which it has no authority but nevertheless...
In my case, I primarily use region ap-southeast-2.  By default, SLS CREATE generates a serverless.yml using a default US region.  If this is left as-is, there is then a mismatch between the deployment region and your AWS CLI region.  Not good.  To avoid the minor pain of having to specify a deployment region in the SLS deploy command, just update the deployment region in the serverless.yml file to match the CLI region.
Now works a treat...


text:
Q: How to send html template as mail using groovy I am using JavaMail API 1.4.4 to send mails. So far I am able to send the mail, but actually I need to send HTML content so that when the mail is received it processes the html tags.
Example: if I have a table code in my message it should process the html code and present it in the mail
My Code
import java.io.File;
import java.util.*
import javax.mail.*
import javax.mail.internet.*
import javax.activation.*

class Mail {
  static void sendMail(mailProp) {
    // Get system properties
    Properties properties = System.getProperties()

    // Setup mail server
    properties.setProperty("mail.smtp.host", mailProp.host)

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties)

    try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session)

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(mailProp.from))

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(mailProp.to))

      // Set Subject: header field
      message.setSubject("My Subject!")

      // Now set the actual message
      message.setText(createMessage())

      // Send message
      Transport.send(message)
      System.out.println("Sent message successfully....")
    }
    catch( MessagingException mex ) {
        mex.printStackTrace()
    }
  }

  static def createMessage() {
    def message="""
This is actual message
"""
  }

  static main(args) {
    AppProperties.load()

    def mailProp=[:]
    mailProp.host=AppProperties.get("host")
    mailProp.from=AppProperties.get("sender")
    mailProp.to=AppProperties.get("receiver")
    mailProp.server=AppProperties.get("mailserver")

    sendMail(mailProp)
  }
}

A: A Groovier way of sending might be:
try {
  // Create a default MimeMessage object.
  new MimeMessage(session).with { message ->
    // From, Subject and Content
    from = new InternetAddress( mailProp.from )
    subject = "My Subject!"
    setContent createMessage(), 'text/html'

    // Add recipients
    addRecipient( Message.RecipientType.TO, new InternetAddress( mailProp.to ) )

    // Send the message
    Transport.send( message )

    println "Sent successfully"
  }
}
catch( MessagingException mex ) {
    mex.printStackTrace()
}

A: Use setContent
message.setContent("
This is actual message
", "text/html")

A: Use message.setText(createHtmlMessage(), "utf-8", "html");


text:
Q: Does my program crash even before reaching main()? I am trying to port a project including both SDL and WxWidgets to MacOS X with XCode 3.1.2. The project is fairly big, but I finally got it to compile successfully. However, it exits immediately after starting it with the message "MyApplication has exited with status 99".
For debugging purposes, I changed my main function to look like this:
int main(int argc, char *argv[])
{
    cout <<"hello world";
    cout <<"and goodbye";
    throw "test";
}

I also added breakpoints to all three main function lines. However, the debugger does still not break and the application still exits right after startup.
The debug console output looks as follows:

(gdb) run [Switching to process 94140
  local thread 0x3607] Running…
Debugger stopped. Can't find test.xml
  !
Debugger stopped. Program exited with
  status value:99.(gdb)

I do not know what file "can't find test.xml" refers to, why XCode is looking for it in the first place or if it is related to my problem at all.
This is my first XCode project, so I am clueless on how to proceed. Any hints would be greatly appreciated.

A: SDL uses some hack around your main function.
It's likely that your main code is never reached.
Try breaking on "start" and stepping from there - AFAIK "start" is the entry point to any macho executable.
What you're seeing looks like your binary exits with error code "99".
You may want to look for error code 99 in SDL or WX.
Later edit: from SDL site: The header file "SDL_main.h" remaps your main() function to the SDL_main() function with a function macro.

A: You probably don't have the right project settings. Which project template did you choose?

A: In the end I found that there was a different main() function in a unit test file from a third party library I had included by mistake.

A: And I expect that test.xml is a data file for that unit test, and it may have expected it in a default directory.  Project > Edit Active Executable and make sure that the working directory on launch is where the code expects it to be (root, project directory, or executable directory).
I have to say, though, that I don't recommend learning a new tool by porting source code you're unfamiliar with to it.  You are going to have a hard time telling what problems are due to learning Xcode from what problems are due to the odd expectations of SDL/WxWidgets.


text:
Q: Broken Process Pool error using fbProphet cross validation I'm using facebook's Prophet library to do a forecast, but before I put it in production I want to validate it using the included cross validation package. I have a machine with 64GB RAM and Ryzen 9 5950X. I get this error: "BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending." after hours of computing.
Needless to say its frustrating, but when I look for it I can't find anyone with the same issue specifically. Many people run into this error using the "concurrent.futures" library, I assume this is built into the prophet package. The most common reason people give for this error is a lack of memory. But this is not the case for me. The memory usage never went above 20GB (so well within the limit).
I've tried on a different machine that runs a totally different platform, and it also had the same error.
This is my code:
#%%
start = time.time()
prophet = Prophet(yearly_seasonality=False,
                  weekly_seasonality=True,
                  daily_seasonality=True,
                  interval_width=0.9)
prophet.add_country_holidays('Netherlands')
prophet.fit(df.reset_index())
prophet_time = time.time() - start

#%%
start = time.time()
prophet_cv = cross_validation(prophet, initial='1788 days', period='24 hours', horizon = '24 hours', parallel = 'processes')
prophet_cv_time = time.time() - start

and this is my df:
df.reset_index()
                       ds       y
0     2015-08-09 22:00:00   30.60
1     2015-08-09 23:00:00   27.19
2     2015-08-10 00:00:00   25.49
3     2015-08-10 01:00:00   24.77
4     2015-08-10 02:00:00   24.45
                  ...     ...
52651 2021-08-11 17:00:00  127.77
52652 2021-08-11 18:00:00  139.87
52653 2021-08-11 19:00:00  125.01
52654 2021-08-11 20:00:00  117.00
52655 2021-08-11 21:00:00  103.00

[52656 rows x 2 columns]

When I run my code you can see it should retrain the model 405 times and produce a 24 hour forecast every time.
INFO:fbprophet:Making 405 forecasts with cutoffs between 2020-07-02 21:00:00 and 2021-08-10 21:00:00
INFO:fbprophet:Applying in parallel with <concurrent.futures.process.ProcessPoolExecutor object at 0x00000260E14325B0>

Any help with this issue will be greatly appreciated!
Kind regards


text:
Q: envio de e-mail em java não mostra o erro quando não consegue enviar o mesmo Criei um sistema onde o próprio usuário se cadastra e a senha é enviada por email.
Caso não consiga enviar o email , gera um erro e não cria o usuário, notificando o mesmo.
Estava funcionando enquanto estava utilizando servidor de email próprio.
Recentemente passei a utilizar uma conta do Gmail para enviar os emails.
A partir daí a função não gera mais erro quando o Gmail não consegue entregar a mensagem.
Com isso o usuário não sabe que ocorreu um problema e não recebe a senha.
import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

// ... Demais imports

@ViewScoped
public class Mailer implements Serializable{

    private static final long serialVersionUID = 1L;

    @Inject
    private PropriedadesEmail propriedadesEmail;

    private String mailTo;
    private String mailCC;
    private String mailSubject;
    private String mailBody;

    public void sendMail() throws NegocioException {

        try{
            MimeMessage generateMailMessage = propriedadesEmail.mineMessage(); // new MimeMessage(getMailSession);

            generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(this.mailTo));
            if(this.mailCC != null)
                generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(this.mailCC));

            generateMailMessage.setSubject(this.mailSubject);
            generateMailMessage.setFrom(propriedadesEmail.getMailUsername());

            generateMailMessage.setContent(this.mailBody, "text/html");

            Transport transport = propriedadesEmail.getMailSession().getTransport("smtp");

            transport.connect( propriedadesEmail.getMailServerHost()
                                  ,propriedadesEmail.getMailUsername()
                                  ,propriedadesEmail.getMailPassword()
                                 );

            transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            System.out.println("-------- ERRO AddressException e "+e.getMessage());
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("-------- ERRO MessagingException e "+e.getMessage());
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        }

    }

    // ... Demais metodos e clases
}

Classe PropriedadesEmail
@ApplicationScoped
public class PropriedadesEmail implements Serializable{

    private static final long serialVersionUID = 1L;

    private String  mailServerHost;
    private String  mailServerPort;
    private String  mailEnableSsl;
    private String  mailEnableStarttls;
    private String  mailAuth;
    private String  mailUsername;
    private String  mailPassword;
    private Session mailSession;

    @PostConstruct
    private void init(){
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));
            mailServerHost      = props.getProperty("mail.server.host");
            mailServerPort      = props.getProperty("mail.server.port");
            mailEnableSsl       = props.getProperty("mail.enable.ssl");
            mailEnableStarttls  = props.getProperty("mail.enable.starttls");
            mailAuth            = props.getProperty("mail.auth");
            mailUsername        = props.getProperty("mail.username");
            mailPassword        = props.getProperty("mail.password");

            mailSession             = Session.getDefaultInstance(mailServerProperties(), null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador");
        }
    }

    public MimeMessage mineMessage() {
        return new MimeMessage(this.getMailSession());
    }

    private Properties mailServerProperties() {
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));

            Properties mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.port", this.getMailServerPort());
            mailServerProperties.put("mail.smtp.auth", this.getMailAuth());
            mailServerProperties.put("mail.smtp.starttls.enable", this.getMailEnableStarttls());

            return mailServerProperties;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador");
        }
    }

mail.properties
mail.server.host=smtp.gmail.com
mail.server.port=587
mail.enable.ssl=false
mail.enable.starttls=true
mail.auth=true
mail.username=peroladooeste.portaldoaluno@gmail.com
mail.password=*******************

Email retornado com o erro no gmail.

Mail Delivery Subsystem
Endereço não encontrado A mensagem não foi entregue para
  teste.002.error1@transportesalvorada.com.br porque o endereço não foi
  encontrado. Verifique se há erros de digitação ou espaços
  desnecessários e tente novamente.
A resposta do servidor remoto foi: 550 5.1.1
  : Recipient address
  rejected: User unknown in virtual mailbox table
Final-Recipient: rfc822; teste.002.error1@transportesalvorada.com.br
  Action: failed Status: 5.1.1 Remote-MTA: dns;
  mail2.transportesalvorada.com.br. (201.148.108.74, the server  for the
  domain transportesalvorada.com.br.) Diagnostic-Code: smtp; 550 5.1.1
  : Recipient address
  rejected: User unknown in virtual mailbox table Last-Attempt-Date:
  Wed, 08 Mar 2017 05:53:40 -0800 (PST)

A: O problema em questão é o e-mail ser digitado errado. ( não que o e-mail seja inválido, ele simplesmente é um e-mail válido que não existe)

Uma coisa simples que você pode fazer que não resolve completamente mas pode
  minimizar que as pessoas digitem e-mail errado é pôr pra digitarem duas
  vezes e dar erro se os dois campos não estiverem iguais, além da verificação com expressão regular sobre a validade do e-mail.

De acordo com o e-mail que o Gmail te enviou, o e-mail teste.002.error1@transportesalvorada.com.br não existe.
Não deu erro porque o e-mail foi enviado corretamente. Só que pra um endereço que não existe.
Quando seu e-mail chegou no servidor do domínio transportesalvorada.com.br esse servidor olhou na tabela de e-mails e viu que esse e-mail não existia e enviou a resposta pro gmail falando que o mesmo não existia. A resposta foi pro gmail pq o e-mail enviado saiu do servidor de lá.
Se o carteiro leva uma carta pra uma residência em que o endereço está errado ela retorna pro remetente. Perceba que a carta foi enviada e quem enviou só ficou sabendo que o endereço estava errado depois que a carta voltou.
Se apenas fazer a pessoa conferir se está digitando certo não é suficiente, você pode tentar procurar algum serviço para validar e-mails antes de enviá-los. Segue um serviço: http://www.verifyemailaddress.org/email-verification-api.html
Testando no site http://www.verifyemailaddress.org/ vi que o e-mail teste.002.error1@transportesalvorada.com.br não existia, mas teste.002@transportesalvorada.com.br existe.
Esse site envia um e-mail e inicia uma conversa entre servidores para verificar se o e-mail existe.
MX record found: mail2.transportesalvorada.com.br (Priority 5)
MX record found: mail3.transportesalvorada.com.br (Priority 5)
Connecting to mail2.transportesalvorada.com.br
Connected to mail2.transportesalvorada.com.br
Dialog with mail2.transportesalvorada.com.br ok
------------------------------------------------------------
220 mail3.transportesalvorada.com.br running OSTec Mail Server 3000
HELO verifyemailaddress.org
250 mail3.transportesalvorada.com.br
MAIL FROM: <noreply@verifyemailaddress.org>
250 2.1.0 Ok
RCPT TO: <teste.002@transportesalvorada.com.br>
250 2.1.5 Ok
QUIT
221 2.0.0 Bye
------------------------------------------------------------
Email address teste.002@transportesalvorada.com.br accepted

Assuntos relacionados:
Comandos SMTP:
http://www.samlogic.net/articles/smtp-commands-reference.htm
Páginas relacionadas de pessoas que tentaram fazer essa validação de existência de um e-mail com Java com algum sucesso:
https://stackoverflow.com/questions/13514005/how-to-check-mail-address-is-exists-or-not
http://www.rgagnon.com/javadetails/java-0452.html

A: Temo que o único jeito de resolver esse problema seja acessar periodicamente os e-mails do Gmail e procurar pela mensagem de retorno.
E-mail é um protocolo que foi mais ou menos estabilizado na década de 1970, e não é um protocolo de tempo real. Os MTA (Mail Transport Agent), como os do Gmail, têm a liberdade de segurar o e-mail por tempo indeterminado e fazer várias tentativas de entrega antes de desistirem. Eles podem até fazer uma entrega indireta, mandando para outro servidor de e-mail, e esse outro ser o encarregado de entregar para o destinatário final (embora eu duvide que algum sistema funcione dessa maneira nos dias de hoje). Se funcionava com o seu servidor de e-mail próprio, é porque ele fazia uma tentativa de entrega imediatamente, e já retornava o erro em caso de falha. O Gmail não é assim, e o aviso de falha deles é feito por e-mail.


text:
Q: Why does Django think my query string is empty? I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything.
My URL:
localhost/query_view/?foo=foo

My template:
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <p>{{ query_string }}</p>
    </body>
</html>

My view:
def query_view(request):
    query_string = request.META['QUERY_STRING']
    return render(request, 'query_view.html', {'query_string': query_string})

I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing.
Edit: Django version 1.9.4, Python version 3.4.3

A: I would put a debugger before the return to see what's actually in the request. But usually something like request.GET.get('foo') would get you what you want. Also, you can provide a default value if foo is actually empty. request.GET.get('foo', 'blah')

A: try
 def query_view(request):
     query_string = request.GET.get('foo',None)
     print(query_string)
     return render(request, 'query_view.html', {'query_string': query_string})

and check if query_string value is None or not .
Let me know, if it didn't work out!
Inaddition  mention your django and python version also.


text:
Q: Why does $\mathfrak{p} \supseteq \mathfrak{a}$ imply $\mathfrak{p}$ is the only prime containing $\mathfrak{a}^{ec}$?
Let $\mathcal{O}$ be a one-dimensional noetherian integral domain (or more specifically, an order in an algebraic number field).  Let $\mathfrak{a} \not= 0$ be an ideal of $\mathcal{O}$.  Why does $\mathfrak{p} \supseteq \mathfrak{a}$ imply that $\mathfrak{p}$ is the only prime containing $\mathcal{O} \cap \mathfrak{a}\mathcal{O}_{\mathfrak{p}}$?

Then $\mathfrak{p}^{e} \supseteq \mathfrak{a}^{e}$. If $\mathfrak{q}$ is another prime containing $\mathfrak{a}^{ec}$ ($e$/$c$ are extension/contraction to/from $\mathcal{O}_{\mathfrak{p}}$), then $\mathfrak{q}^{e} \supseteq \mathfrak{a}^{ece} = \mathfrak{a}^{e}$.  But I assume this latter fact comes from the fact that $\mathfrak{q} \not\subseteq \mathfrak{p}$, hence $\mathfrak{q}^{e} = \mathcal{O}_{\mathfrak{p}}$.
Note that this is from the proof of Proposition 12.3 in Chapter 1 of Neukirch's Algebraic Number Theory.

A: Let $\mathfrak a=\mathfrak q_1\cap\cdots\cap\mathfrak q_n$ be a reduced primary decomposition, and $\mathfrak p_i=\sqrt{\mathfrak q_i}$. Then $\mathfrak p_i$ are all maximal ideals, and one of them equals $\mathfrak p$, say $\mathfrak p_1$. Then $\mathfrak aR_{\mathfrak p}\cap R=\mathfrak q_1$, and we are done.


text:
Q: Setting targetSdk based on "Optimization Tips" I see Google has added a new section called "Optimization Tips" in the developer console.
In it it mentioned I should set a targetSdk.  I currently only have:
<uses-sdk android:minSdkVersion="7"/>

In  their documentation
they say:
"You can set the app's range of targeted Android versions in the manifest file, in the <uses-sdk> element. In most cases, you can target Android versions properly by setting the element's targetSdkVersion attribute to the highest API level available."
and
"targetSdkVersion is declared with value 11 or higher (14 or higher is recommended)"
My app works perfectly in all versions of android including tablets.  Based on what they are saying, even though my app supports version 7, and uses no features of higher versions - should I really be setting my target to the highest possible value (currently API 17).
At the moment I get a reasonable amount of downloads for my app so I'm not understanding the benefit properly - is it just an indicator to google I've tested it on higher devices (since its a full screen canvas app - colour scheme and menu style, changes are unlikely to have any effect for me)
(Btw, I do understand why someone might want to use a higher targetSdk, I'm just wondering if one should set it higher even if you don't need it)

A:
should I really be setting my target to the highest possible value (currently API 17)

Yes. It'll improve the user experience on newer devices in various ways.
An example of this is that devices with virtual soft keys, i.e. the last few generations of Nexus phones, will show the legacy options menu button if you're not targeting at least API level 11.
There are several other things to mention, but I'm a bit short on time at the moment. In short: You should always include a target API and a minimum API level.
I'd highly recommend you read this article: http://android-developers.blogspot.dk/2012/01/say-goodbye-to-menu-button.html

A: Setting a targetSdk version is like indicating that you develop with higher level APIs taken into consideration. As Michell points out, it would automatically take care of a few things.
On the flip side this would also 'imply' that you have taken care of handling any deprecated APIs/ behavioral changes of APIs in your code.

*

*For instance, AsyncTasks used to be executed in a ThreadPool(Parallel execution) prior to API 11. And in APIlevel >= 11 the default mode of execution of AsyncTasks is a Single Thread, the tasks being queued up. Now when you target SDK >=11 you implicitly accept that your AsyncTasks are fine to be run on a single thread (No parallel execution).

*Google Nexus Devices have a soft menu button(When you have implemented menus) on screen when you don't specify a targetSDK version. Now when you do specify a target>=11 you indicate that you are taking care of displaying the menu yourself.
There are a few things like these that you should be aware of. As suggested it would be better if you could go through the link http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
carefully and sufficiently test the app for any deviations after you specify the target.


text:
Q: Is it possible to control how object property names get converted to strings in JavaScript? I'm interested in creating an object that can handle keys of different types separately instead of casting them all to strings. I'm wondering if there's a way to do this with proxies or any other relatively new JavaScript features. If I do something like
const handler = {
    get: function(target, name) {
        return typeof(name);
    }
};
const proxy = new Proxy({}, handler);

and then try to access proxy[1] it returns string as the type. I understand why this is happening, but I'm curious if there's any way to hook into this type conversion and control it. I know that I could override Number.prototype.toString, but I would like to only modify this behavior when the property name is being processed. Ideally I would want something analogous to this.
const handler = {
    convertPropertyNameToString: function(target, name) {
        return `${typeof(name)}--${name}`;
    }
};
const proxy = new Proxy({}, handler);

I just want to control the conversion of the property names into strings for a specific object. If there's not a straightforward way to do it, then I'm also open to creative hacks.

A: With normal property access, e.g. foo.bar and foo[thing], the key is converted to a string before the object itself even knows there is an access coming. The get trap on a proxy only gets access to it after than point, so it is guaranteed that a string or Symbol.
If you're interested, you can see that in the spec for property access where on step (6) it is converted to a string. The logic to actually access the property does not happen until much later and has no knowledge about where the stringified key came from.
The best you could do is use your own function, e.g. proxy.readKey(name) where obviously name can be any value. As mentioned in the comments, this is similar to the interface used for ES6 Map instances.


text:
Q: Constant projective dimension of $R/I^i$ for all $i$. Let $R$ be a local Noetherian ring and $I$ an $R$-ideal. What can we say about the ideal $I$ if the projective dimension of $R/I^i$ for $i \ge 1$ is a finite number which is independent of $i$, i.e., $\operatorname{pd}_R R/I^i = c$ for all $i$?
Of course, in the obvious case when $R$ is regular and $I$ is primary to the maximal ideal, one cannot say much. What about the case where $R$ is not regular, so having a finite projective dimension is not automatic? I'm fine with assuming $R$ to be a complete intersection.


text:
Q: ¿Como pasar de spawn a spawnSync? Estoy haciendo una consola bash utilizando node.js. Tengo utilizar spawnSync en lugar de spawn. ¿Como hago para que cuando se produzca una salida estandar se emita un evento, lo capture y lo mande al cliente a traves de un socket?
El código con spawn sería algo así:
var spawn = require('child_process').spawn;
var shell = spawn('/bin/bash');

shell.stdout.on('data', function(data) {
   socket.emit('stdout', data);
});

socket.on('stdin', function(command) {
    shell.stdin.write(command+"\n") || socket.emit('disable');
});

Necesito saber como hacer algo equivalente con spawnSync. Si necesitais mas codigo o que aclare algo preguntad sin miedo.
Edit: por lo que ha explicado Gustavo no es viable hacerlo con spawnSync ¿Existe alguna manera de saber si un comando ha finalizado (correcta o incorrectamente)? El caso es que hay comandos como cd que no emiten salida y necesito un "algo" (sea un evento preferiblemente) que me indique que ha finalizado.

A: La funciónchild_process.spawnSync es síncrona, como su nombre lo indica. Al igual que fs.readFileSync por ejemplo, se bloqueará el EventLoop hasta que haya terminado su ejecución en el stack. En el caso de spawnSync, el EventLoop se bloqueará hasta que el proceso haya sido cerrado.
El modo de uso es simple:
const command = spawnSync('ifconfig', ['eth0']);
// el resto de código se ejecutará cuando se termine el proceso
const outtext = command.output[1];
console.log(outtext); // imprime información de la interface de red
socket.broadcast(outtext);


text:
Q: VHDL unexpected behaviour of XNOR for std_logic_vector I have a series of 25 64bit std_logic_vectors in my structural VHDL code. These should always be identical and I want to test if there are any faults which flip a bit. My code looks like this:
outX <= mt1_op XNOR mr2_op XNOR mt3_op XNOR .... XNOR mt25_op;

This gives me no errors and synthesises fine, but when I simulate it in ISim, the XNOR operation does not seem to be working. I expect all 1s or the occasional 0 if there is a fault, but the final output signal, outX, simply has the same value as all of the input signals. I won't bother stating the entire 64bit vector but as an unsigned int it resolves to 7776. All of the input vectors are the same - 7776 - and when I XNOR them all together, I get an answer of 7776.
I suspect that the problem might be caused by the XNOR operations being applied one at a time, i.e.
OutX <= (mt1_op XNOR mt2_op XNOR(mt3_op XNOR(mt4_op XNOR( ..... )))))))));

which will not give the desired behaviour.
Does anyone have an idea how I can get the behaviour that I want? i.e. if all 25 vectors are identical, give me all 1s or where there are differences, give me a 0. ??
Thanks
Tom

A: The XNOR expression is working just fine:
'0' XNOR '0' XNOR ... XNOR '0' = '0'  -- For 25 XNOR '0's
'1' XNOR '1' XNOR ... XNOR '1' = '1'  -- For 25 XNOR '1's

So the expression will return the argument vector if the same vector is given 25 times to XNOR.
To check if all vectors are identical you can do:
or_all <= mt1_op OR mt2_op OR ... OR mt25_op;
and_all <= mt1_op AND mt2_op AND ... AND mt25_op;
identical <= or_all = and_all;  -- Boolean as resulting type

And for resulting type as std_logic
identical_std_logic <= '1' when (and_all = or_all) else '0';


text:
Q: Which method will call if i delete application from device in iphone I am creating one iPhone server side application,in that when ever user will deletes the application i need to update the status of user.I am sending that request in application Terminate Method but it is not calling that method.Don't know where i need to send request inside application.If any one knows please help me as soon as possible.

A: The application cannot know when it was terminated, that is something that the operating system knows about. And there is no way for your app to do anything when the app is deleted - it's deleted and can't do anything.
So, the simple answer is that it can't be done, because you can't get the operating system to tell you when it deletes an application.


text:
Q: Como remover um alert depois de selecionar outro em um select Estou com o seguinte código:
HTML:
<select class="form-control btn-form" id="select-category">
      <option selected hidden>Selecione uma categoria:</option>
      <option value="anu1">Anunciante1</option>
      <option value="anu2">Anunciante/option>
      <option value="anu3">Anunciante3</option>
</select>

JS:
$('#select-category').change(function(){
  if($(this).val() == 'anu1'){
      document.getElementById('alert-anu-1').style.display='block';
  }

  if($(this).val() == 'anu2'){
    document.getElementById('alert-anu-2').style.display='block';
  }
  if($(this).val() == 'anu3'){
    document.getElementById('alert-anu-3').style.display='block';
  }
});

A ideia é ter uma lista e depois quando o usuário selecionar uma opção mostrar um "alert" em bootstrap. Ou seja, se o usuário selecionar o valor "anu1", mostra o alert "alert-anu-1", isso até então está funcionando. O que não estou conseguindo é limpar os valores.
Ex: se selecionar o valor anu1, mostra ele, mas se selecionar o valor anu2, tem que limpar o alert do anu1 e mostrar apenas o do anu2 e assim por diante....
Como poderia fazer isso?

A: Você não esta tirando o display, quando coloca com o display = "block" é preciso colocar display = "none", assim vai esconder a mensagem.
$('#select-category').change(function(){
    for(var x=1;x<=3;x+=1) //apaga as 3 mensagens
        document.getElementById('alert-anu-'+x).style.display='none';

    if($(this).val() == 'anu1'){
        document.getElementById('alert-anu-1').style.display='block';
    }
    /*...*/
});

A: Acho que basta algo como:
var alerts = $('[id^="alert-anu-"]');
$('#select-category').change(function() {
    alerts.hide();
    $('#alert-' + this.value).show();
});

Assim quando o select muda ele esconde todos os alertas e mostra só o que foi escolhido. Criei a variável alerts para ter esses elementos em cache e evitar ir ao DOM buscá-los muitas vezes.


text:
Q: Javascript API for Office error I am trying to read from an excel file to use the data in SharePoint.  I recently discovered the Javascript API for Office however I can't reference the library without an error.  I use the following html reference:
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js"/>
My browser responds with Uncaught TypeError: window.external.GetContext is not a function.
Thanks in advance for the help.

A: The script element can't be self-closed.
Try
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js"></script>


text:
Q: How to pass data from one ViewModel to another ViewModel I have a fragment in which I have two TextViews with hint texts. When a user clicks on the first one a bottom sheet dialog opens and shows a list of possible options. User selects an option, and the option info is displayed in the first TextView instead of hint text. When the user clicks on the second TextView the very same bottom sheet dialog opens, but shows a filtered list of options (the list is filtered based on the first choice). User selects an option and the option info is displayed in the second TextView instead of the hint text as well. I have achieved to have this by using only one ViewModel for the fragment itself, but it doesn't seem right because the ViewModel does too much. Therefore, I tried using two ViewModels: one for the fragment itself to update when the options are selected, and one for the bottom sheet dialog to load the data and show them in the list. But the issue is that I cannot share the selected option from the bottom sheet dialog ViewModel to the fragment ViewModel. Is there a way to achieve what I want to achieve by using two ViewModels?

A: For now, as far as I know, the Google recommended approach is to have a shared view model for such cases.
I am not sure how you implemented it in your case - but if it is something similar to what Google recommends - then it is ok.
Of course, you can create an elaborate architecture of multiple view models connected via interfaces and UI calls, but I don't know if it is worth it.
The general rule for implementing such cases is not to use the cleanest approach with a lot of abstractions and generifications but to use the most optimal one(in terms of time spent and simplicity/readability of the code) that still tries to follow OOD principles.
Hope it helps.

A: I had this problem and I solved with interface.I thing this is best practice.
Example: I show how send string from bottom sheet dialog to fragment.
First we create new interface
interface BottomSheetClickListener {
   fun onDialogClick(view: View, string: String)
}

Second we get in bottom sheet dialog fragment from class constructor. And we write how trigger this listener for example click textView.
class BottomSheetDialog(
 private val listener: BottomSheetClickListener
) : BottomSheetDialogFragment() {
   textView.setOnClickListener {
        listener.onDialogClick(it,"String")
   }
}

And finally we write fragment or activity code first inheritance from our listener and create bottomSheetDialog object.
  class HomeFragment : Fragment(), BottomSheetClickListener {

     private fun openBottomSheetDialog(){
        val dialog = BottomSheetDialog(this)
        dialog.show(childFragmentManager, "dialog")
     }

     override fun onDialogClick(string: String, id: Int) {
      //Get string from bottom sheet dialog string
     }
}

A: You can have multiple ViewModels in a Fragment, so there's no need to keep a huge shared ViewModel with all the logic of the 3 smaller ones.
You can create an extra shared ViewModel that only cares about the actual common data, and keep your 3 separate fragment specific ViewModels separate.
sharedModel = activity?.run {
        ViewModelProviders.of(this)[SharedViewModel::class.java]
    } ?: throw Exception("Invalid Activity")
localViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)


text:
Q: import of HttpSocket in Paypal in cakephp Well, here's what i got. I have a line of code here that imports HttpSocket in my CakePHP-paypal integration.
It is located in my /app/PaypalIpn/Model/DataSource/PaypalIpnSource.php. Here it is:
function __construct(){
    if (!class_exists('HttpSocket')) {
        if(App::uses('HttpSocket', 'Network/Http')){
            $this->log('http socket imported','paypal');
        }
    }
        else{
            $this->log('http socket not imported','paypal');
        }
    $this->Http = new HttpSocket();
  }

By the way, my HttpSocket.php is located here:
C:\xampp\htdocs\wifidrivescanportal\lib\Cake\Network\Http\HttpSocket.php

So everytime i try to access this function in my HttpSocket.php:
public function post($uri = null, $data = array(), $request = array()) {
     //$this->log('entered post in http socket','paypal');
     $request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
     return $this->request($request);
}

via this line of code inside my PaypalIpnSource.php:
function isValid($data){
    // .... other codes
    $response = $this->Http->post($server, $data);
    return $response;
}

nothing happens. It doesn't log anything despite that i indicated it to log something particularly in some portions in /app/PaypalIpn/Model/DataSource/PaypalIpnSource.php

A: Debug the raw response data in the HttpSocket class. In 1.3 I had a few cases in the past were I had the same issue with this class.
Try http://api13.cakephp.org/view_source/http-socket/#l-292 debug($this->request['raw']) after this line.
The raw data might contain something that the 1.3 class does not pick up.

A: Well here's what I did these line of codes
function isValid($data){
    // .... other codes
    $response = $this->Http->post($server, $data);
    return $response;
}

I made it this way:
function isValid($data){
    // .... other codes
    return $this->Http->post($server, $data);
}

Not so certain with the difference but it worked out this way. Once I finished my paypal integration in cakephp, i'll make sure i'll provide a tutorial for beginners like me. Hope I could help that way. My next goal is to do the encryption using ppcrypto.


text:
Q: Would the compiler optimize this expression into a temporary constant rather than resolve it every iteration? I have the following loop:
for (unique_ptr<Surface>& child : Children)
{
    child->Gather(hit);

    if (hit && HitTestMode == HitTestMode::Content && child->MouseOver && !mouseOver)
    {
        mouseOver = true;
    }
}

I wonder if the compiler (I use Visual Studio 2013, targeting x64 on Win7 upwards) would optimize the expression
hit && HitTestMode == HitTestMode::Content

into a temporary constant and use that rather than resolve the expression every iteration, similar to me doing something like this:
bool contentMode = hit && HitTestMode == HitTestMode::Content;

for (unique_ptr<Surface>& child : Children)
{
    child->Gather(hit);

    if (contentMode && child->MouseOver && !mouseOver)
    {
        mouseOver = true;
    }
}

Bonus question:
Is checking for !mouseOver worth it (in order to skip the conditional mouseOver = true; if it has already been set)? Or is it faster to simply set it again regardless?

A: The answer to whether that optimization could even take place would depend on what hit, HitTestMode and HitTestMode::Content are and whether it's possible that they could be changed by the call to child->Gather().
If those identifiers are constants or local variables that the compiler can prove aren't modified, then it's entirely possible that the sub-expression hit && HitTestMode == HitTestMode::Content will be hoisted.
For example, consider the following compilable version of your example:
#include <memory>
#include <vector>

using namespace std;

class Surface
{
public:
    void Gather(bool hit);
    bool MouseOver;
};

enum class HitTestMode
{
    Content = 1,
    Foo = 3,
    Bar = 4,
};

extern HitTestMode hittestmode;

bool anyMiceOver( vector<unique_ptr<Surface> > & Children, bool hit)
{
    bool mouseOver = false;

    for (unique_ptr<Surface>& child : Children)
    {
        child->Gather(hit);

        if (hit && hittestmode == HitTestMode::Content && child->MouseOver && !mouseOver)
        {
            mouseOver = true;
        }
    }

    return mouseOver;
}

When compiled using g++ 4.8.1 (mingw) with the -O3 optimization option, you get the following snippet of code for the loop (annotations added):
    mov rbx, QWORD PTR [rcx]      ; Children.begin()
    mov rsi, QWORD PTR 8[rcx]     ; Children.end()
    cmp rbx, rsi
    je  .L8                       ; early exit if Children is empty

    test    dl, dl                ; hit == 0?
    movzx   edi, dl
    je  .L5                       ; then goto loop L5

    xor ebp, ebp
    mov r12d, 1
    jmp .L7
    .p2align 4,,10
.L6:
    add rbx, 8
    cmp rsi, rbx                  ; check for end of Children
    je  .L2
.L7:
    mov rcx, QWORD PTR [rbx]
    mov edx, edi
    call    _ZN7Surface6GatherEb  ; call child->Gather(hit)
    cmp DWORD PTR hittestmode[rip], 1  ; check hittestmode
    jne .L6
    mov rax, QWORD PTR [rbx]      ; check child->MouseOver
    cmp BYTE PTR [rax], 0
    cmovne  ebp, r12d             ; set mouseOver appropriately
    jmp .L6
    .p2align 4,,10

.L5:                             ; loop L5 is run only when hit == 0
    mov rcx, QWORD PTR [rbx]     ; get net element in Children
    mov edx, edi
    add rbx, 8
    call    _ZN7Surface6GatherEb ; call child->Gather(hit)
    cmp rsi, rbx
    jne .L5

.L8:
    xor ebp, ebp
.L2:
    mov eax, ebp
    add rsp, 32
    pop rbx
    pop rsi
    pop rdi
    pop rbp
    pop r12
    ret

You'll note that the check for hit has been hoisted out of the loop - and if it's false then the a loop that does nothing but call child->Gather() is run.
If hitmodetest is changed to be a variable that's passed as a function argument so it's no longer subject to possibly being changed by the call to child-Gather(hit), then the compiler will also hoist the check for the value of hittestmode out of the loop and jump to the loop that does nothing but call child->Gather().
With a local hittestmode using -O2 will calculate hit && hittestmode == HitTestMode::Content prior to the loop and stash that result in a register, but it will still test the register in each loop iteration instead of optimizing to a separate loops that don't even bother with the test.
Since you specifically asked about the VS2013 compiler (using /Ox and /Ot options), it doesn't seem to hoist or optimize either of the checks (for hit or hittestmode) out of the loop - all it seems to do is keep the values for those variable in registers.


text:
Q: Power series ordinary differential equations I have the equation: $y'' - (\frac2x + x^2)y' + y = 0$
I need to use power series of the form $y = \sum_{n=0}^\infty a_n(x-5)^{n}$ and coefficients up to n=4
Derivatives of y: $y' = \sum_{n=1}^\infty a_nn(x-5)^{n-1}$ and $y'' = \sum_{n=2}^\infty a_nn(n-1)(x-5)^{n-2}$
If I sub them on my ODE I will get:
$\sum_{n=2}^\infty a_nn(n-1)(x-5)^{n-2} - (\frac2x + x^2)\sum_{n=1}^\infty a_nn(x-5)^{n-1} + \sum_{n=0}^\infty a_n(x-5)^{n}$ = 0
But, I have no idea what to do with $(\frac2x + x^2)$.


text:
Q: boost flyweight panics I am using Boost 1.39. I've implemented my class using boost::flyweight<no_locking, hashed_factory<> > (my application is single-threaded). Test program for my class passes fine, but when I use in in the application, I panic in
#9  0x08de7c3e in boost::flyweights::detail::refcounted_value<boost::flyweights::detail::default_value_policy<SharedFileAttr>::rep_type, SharedFileAttr>::release (this=0x0) at /usr/include/boost/flyweight/refcounted.hpp:89
#10 0x08de7517 in boost::flyweights::detail::refcounted_handle<boost::flyweights::detail::refcounted_value<boost::flyweights::detail::default_value_policy<SharedFileAttr>::rep_type, SharedFileAttr> const*, boost::flyweights::detail::flyweight_core_tracking_helper<boost::flyweights::detail::default_value_policy<SharedFileAttr>, mpl_::na, boost::flyweights::refcounted, boost::flyweights::hashed_factory<mpl_::na, mpl_::na, mpl_::na, 0>, boost::flyweights::no_locking, boost::flyweights::static_holder> >::~refcounted_handle (this=0xf32fe61c,
    __in_chrg=<value optimized out>) at /usr/include/boost/flyweight/refcounted.hpp:131
#11 0x08e2edfe in boost::flyweights::flyweight<SharedFileAttr, boost::flyweights::no_locking, boost::flyweights::hashed_factory<mpl_::na, mpl_::na, mpl_::na, 0>, boost::parameter::void_, boost::parameter::void_, boost::parameter::void_>::operator= (this=0xf32fe7e4, x=...)
    at /usr/include/boost/flyweight/flyweight.hpp:196

Notice that in frame #9 this is 0x0
I'm not sure how is it possible from my code that uses the boost::flyweight to cause reference counting issues. After all, my interface only includes methods to add flyweight objects, and destroy them.
I have no idea how to go about figuring out the problem. Any ideas?

A: Well, embarrassing, but the problem was trying to assign an uninitialized flyweight object to another. Must remember to initialize all class members ...


text:
Q: install grub after copy ubuntu i need to install grub on a new hard drive.
i have a 1tb hard drive with linux mint on it.
i also have a dual boot 40gb hard drive with windows xp and ubuntu 12.04lts with grub to chose an os.
i want to copy the ubuntu install from the 40 gb drive on to the bigger drive i have done this already (http://paste.ubuntu.com/7465749/)
i have copied the ubuntu install and put it on the new hard drive with linux mint already on it using gparted in linux mint.
so after i have done this how can i install grub on the 1tb drive to chose an os at boot ?

A: If you are planning to remove the old 40GB hdd, you should ensure that GRUB and /boot partition are installed onto the second drive. There is good instruction in How can I repair grub? (How to get Ubuntu back after installing Windows?)
Alternatively, you can use Boot Repair's Recommended repair. It will place GRUB on all drives.
However, Linux Mint uses GRUB too, and if you put the GRUB onto 1TB drive (/dev/sdb) when you did install it, you just need to boot into Mint and run sudo update-grub. It should print that it found Ubuntu.
Resume: check if Mint starts from the second hdd, and if it will, just run sudo update-grub in it. If not, use Boot Repair or install GRUB manually.


text:
Q: Battlelog How can i disable auto-join? When I am about to play battlefield 4, and I click "join", it will automaticly put me in the game as soon as its finished loading.
Is there any way I can disable that?
I can still remember that the old battlelog had a button to disable auto-join.

A: You can disable it by going to general settings and disabling "Focus game when loading is complete"


text:
Q: Refactoring a Zend_View_Helper_Action widget, utilizing Zend_Controller_Action_Helper_FlashMessenger, into a model I've tried to create a login widget that can be included at will in any action that is outside the content of the application that requires login. My thought here was that I wanted a DRY-approach for rendering the login box with any error messages from a previous login attempt. To enable this I utilized the FlashMessenger for saving the result of a failed login-attempt. The widget also uses the Post/Redirect/Get-pattern to avoid the problem of posting data multiple times when using the browser back-button.
Now, the problem is that I would rather not use the Zend_View_Helper_Action since that helper clones the request and creates another run of the dispatch-loop, which is pretty resource intensive. So, by looking at the code below, could you give me some advice on how to refactor the code such that:

*

*The widget can be included in an arbitrary view script

*Results from a previous login attempt is rendered

*The widget does not invoke a run in the dispatch-loop
Currently, the login widget is rendered by calling, in the view scripts:
echo $this->action('auth', 'login-widget');

AuthController.php:
class AuthController extends Zend_Controller_Action {
    // This method is invoked by Zend_View_Helper_Action to render the
    // login widget
    public function loginWidgetAction () {
        $flashMessenger = $this->_helper->flashMessenger->setNamespace('login');
        $this->view->messages = $flashMessenger->getMessages();
    }

    public function loginAction () {
        if($this->getRequest()->isPost()) {
            $result = Auth::doLogin($this->getRequest()->getPost());
            if($result->isValid()) {
                $this->_redirect('user');
            }
            else {
                $flashMessenger = $this->_helper->flashMessenger->
                                                  setNamespace('login');
                foreach($result->getMessages() as $message) {
                    $flashMessenger->addMessage($message);
                }
            }
        }
        // This will be changed to redirect either to the index page,
        // or the page the request originated from if available.
        $this->_redirect('');
    }
    [...]
}

/models/Auth.php:
/**
 * Model for encapsulating the actions that deals with authentication,
 * such as registering and activating users, as well as logging in and
 * logging out.
 * @todo: Refactor this to remove static methods
 */
class Auth {

    /**
     *
     * @return Zend_Auth_Result
     */
    public static function doLogin ($credentials) {
        $authAdapter = new Auth_Adapter_DbTable(
            Zend_Db_Table::getDefaultAdapter(),
            'Users',
            'username',
            'pwdHash',
            'SHA1(CONCAT(?, salt))'
        );
        $authAdapter->setIdentity($credentials['username']);
        $authAdapter->setCredential($credentials['password']);
        $auth = Zend_Auth::getInstance();
        return $auth->authenticate($authAdapter);
}
[...]
}

/models/Auth/Adapter/DbTable.php:
class Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable {

    /**
     * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method
     * is called to attempt an authenication.  Previous to this call, this
     * adapter would have already been configured with all necessary
     * information to successfully connect to a database table and attempt
     * to find a record matching the provided identity.
     *
     * @throws Zend_Auth_Adapter_Exception if answering the authentication
     * query is impossible
     * @see library/Zend/Auth/Adapter/Zend_Auth_Adapter_DbTable#authenticate()
     * @return MedU_Auth_Result
     */
    public function authenticate() {
        return parent::authenticate();
    }

    /**
     * _authenticateValidateResult() - This method attempts to validate that
     * the record in the result set is indeed a record that matched the
     * identity provided to this adapter.
     *
     * Additionally it checks that the user account is activated.
     *
     * @param array $resultIdentity
     * @return MedU_Auth_Result
     */
    protected function _authenticateValidateResult($resultIdentity)
    {
        $result = parent::_authenticateValidateResult($resultIdentity);
        if(!$result->isValid()) { return $result; }

        $this->_checkAccountIsActivated($resultIdentity);
        $this->_checkAccountIsSuspended($resultIdentity);

        // Overwrite the username supplied by the user and instead
        // use the name supplied upon registration, i.e if the
        // user signs in as uSERNAME and registered as Username,
        // the identity is Username
        $this->_authenticateResultInfo['identity'] =
            $resultIdentity[$this->_identityColumn];

        return $this->_authenticateCreateAuthResult();
    }

    protected function _checkAccountIsActivated ($resultIdentity) {
        if(!$resultIdentity['activated']) {
            $this->_authenticateResultInfo['code'] =
                MedU_Auth_Result::FAILURE_NOT_ACTIVATED;
            $this->_authenticateResultInfo['messages'] =
                array('The account has not yet been activated.
                       Please click on the link provided in the
                       activation email.');
        }
    }

    protected function _checkAccountIsSuspended ($resultIdentity) {
        if($resultIdentity['suspended']) {
            $this->_authenticateResultInfo['code'] =
                MedU_Auth_Result::FAILURE_SUSPENDED;
            $this->_authenticateResultInfo['messages'] =
                  array('The account has been suspended.
                         If you feel this is a mistake,
                         please contact our support: support@meduniverse.com');
        }
    }

    /**
     * _authenticateCreateAuthResult() - This method creates a
     * MedU_Auth_Result object from the information that has
     * been collected during the authenticate() attempt.
     *
     * @return MedU_Auth_Result
     */
    protected function _authenticateCreateAuthResult()
    {
        return new MedU_Auth_Result(
            $this->_authenticateResultInfo['code'],
            $this->_authenticateResultInfo['identity'],
            $this->_authenticateResultInfo['messages']
           );
    }
}

/views/scripts/auth/partials/login-widget.phtml
// The fetchForm-view helper returns a Zend_Form object.
// The form definition (xml) is attached below in the
// code box below this one.

Login

    <?php if($this->messages) : ?>

                <?php foreach($this->messages as $message) : ?>

<?php echo $message ?>

                <?php endforeach; ?>

    <?php endif; ?>

        <?php echo $this->fetchForm('user', 'login') ?>

/application/configs/forms.xml
// Configuration of the Login form. 'user' and 'login' are
// just keys for the view helper to return the correct form
<forms>
    <user>
        <login>
            <action value="/auth/login" />
            <method value="post" />
            <elements>
                <username>
                    <type value="text"></type>
                    <options>

                        <required value="true" />
                        <validators>
                            <alnum validator="alnum" />
                            <strlen validator="StringLength">
                                <options min="6" max="45" />
                            </strlen>
                        </validators>
                    </options>
                </username>

                <password>
                    <type value="password" />
                    <options>

                        <required value="true" />
                        <validators>
                            <strlen validator="StringLength">
                                <options min="6" max="20" />
                            </strlen>
                        </validators>
                    </options>
                </password>

                <submit>
                    <type value="submit" />
                    <options>

                    </options>
                </submit>
            </elements>
    </login>

A: As far as I understood your solution, your current call to the Zend_View_Helper_Action helper does nothing more than rendering the login form. Why don't you write your on view helper that retrieves the login-related messages from the flash-messenger and renders the login form?
EDIT:

*

*You can retrieve the flash-messenger from its static broker:
$flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
$flashMessenger->setNamespace('login');
$messages = $flashMessenger->getMessages();

*You don't need to instatiate a new flash-messenger in your view helper, you just can retrieve the current instance of it (see 1.). From a design point of view I'd say that it's absolutely feasible to retrieve application components within your view helpers (the Zend_View_Helper_Url for example retrieves the router from the static front-controller). To reduce coupling and to implement a setter-dependency-injection-pattern I'd suggest the following (Zend_View_Helper_Translate uses a similar pattern to retrieve the translator):
class My_View_Helper_Login extends Zend_View_Helper_Abstract
{
    // [...]
    /**
     * @var Zend_Controller_Action_Helper_FlashMessenger
     */
    protected $_flash;
    /**
     * @param Zend_Controller_Action_Helper_FlashMessenger $flash
     * @return My_View_Helper_Login Provides a fluent interface
     */
    public function setFlashMessenger(Zend_Controller_Action_Helper_FlashMessenger $flash)
    {
        $this->_flash = $flash;
        return $this;
    }
    /**
     * @return Zend_Controller_Action_Helper_FlashMessenger
     */
    public function getFlashMessenger()
    {
        if ($this->_flash === null) {
            $this->_flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        }
        return $this->_flash;
    }
    /**
     *
     */
    public function login()
    {
        $flashMessenger = $this->getFlashMessenger();
        $flashMessenger->setNamespace('login');
        $messages = $flashMessenger->getMessages();
        // [...]
     }
}

*Not when the flash-messenger provides the functionality you need. If you need to distinguish between error, informational and success messages for example a home-grown solution would perhaps be the better way.

A: Another addition is that you can use FlashMessenger to store ANY data. So you can do
$flash->addMessage(array('status'=>'error','message'=> 'oops'));

and then in foreach use
foreach($messages as $message){
echo '
' . $message['message'] . '
'
}

A: Maybe you should use ViewHelper to render form and ActionController for authentication?
This frees you from second dispatch-loop.
I can show you some little example, if you want.
P.S. You sure need validators for form? I don`t see any use in your example.


text:
Q: Why am I getting an error when viewing stackoverflow in IE7? I'm using Internet Explorer 7.0.5730.13 and I am getting the following error popping up:

---------------------------
Error
---------------------------
A Runtime Error has occurred.
Do you wish to Debug?

Line: 1
Error: Syntax error
---------------------------
Yes   No
---------------------------

This occurs when I visit any page including the main page.  I have JavaScript enabled.

A: TheTXI seems to have hit the nail on the head.  If that doesn't correct the issue though, it is certainly possible that you are not getting the Javascript files loaded onto your PC from Google.  The SO sites now use Google for hosting the jQuery files.

A: You may need to clear your cache and do a hard refresh (Ctrl + F5) of your browser. You may have cached some bad javascript.


text:
Q: C++ Understanding the exact semantics of templates, esp. with functional parameters I'm comfortable using templates when they simply parameterize over a type.  However, I'm now beginning to use them in more complex applications (specifically, parameterizing over a function, as in  C++ Template: typename and function to map to int ), and have been reduced essentially to trial and error (note in the above referenced question I can't get my code to compile).

*

*What are the exact semantics of the template keyword (or the typename keyword when used outside the definition of a template), especially when you want a function as a parameter?

*How do I define a template that takes a function as a parameter?

*Once defined, how do I instantiate and use that template?

I'll accept the first complete answer that includes both a compilable example as well as clear, full explanation, of what's going on behind the magic?

CLARIFICATION: I understand how to use typename.  My question is: What are the exact semantics of template definition, especially when applied to invocable parameters?  and How do you define and instantiate a class which takes a function (or functor or something invokable) as a template parameter?

A:
What are the exact semantics of the template and typename keywords, especially when you want a function as a parameter?

template introduces a template declaration (and also declarations of explicit instantiations and specialisations, but that's beyond the scope of this question). It's followed by the list of template parameters, in angle brackets <>.
Within that list, typename or class introduces a type parameter; one of three kinds of parameter, the others being non-type (value) parameters, and template parameters.

How do I define a template that takes a function as a parameter?

The simplest way is with a type parameter, which can be any type that can be called like a function; for example
template <typename F, typename... Args>
void call(F && f, Args &&... args) {f(std::forward<Args>(args)...);}

Once defined, how do I instantiate and use that template?

If it's a function template, simply call the function with appropriately typed arguments. The template parameters will be deduced from them:
void f1(int a, double b);   // function
struct fn {
    void operator()(std::string);
};

call(f1, 42, 1.5);
call(fn{}, "Hello");
call([](std::string s){std::cout << s}, "Lambda\n");

For class templates, you'd have to specify the function type, which can be a bit messy:
template <typename F>
struct thing {
    F f;
};

thing<void(*)(int,double)> thing1 {f1};
thing<fn> thing2 {fn{}};

// Lambdas are problematic since the type has no name
//thing<???> thing3 {[]{std::cout << "Lambda\n";}};

The messiness could be avoided by using a factory function template to deduce the function type and instantiate the class template:
template <typename F>
thing<F> make_thing(F && f) {
    return thing<F>(std::forward<F>(f));
}

auto thing1 = make_thing(f1);
auto thing2 = make_thing(fn{});
auto thing3 = make_thing([]{std::cout << "Lambda\n";});

A: Below some example (commented) code to show how functions can be used in a template. You can replace typename Parameter with typename... Parameter and p to p... if you want the first template to work for any number of fucntion arguments, which uses variadic templates.
#include <functional> // for std::function
#include <iostream>

// example functions
void func(int i)
{
  std::cout << "Integer: " << i << ".\n";
}
int gunc(int i)
{
  int result = i+1;
  std::cout << "+Integer:" << result << ".\n";
  return result;
}

// general non-restrictive template
template<typename Function, typename Parameter>
void call_twice(Function f, Parameter p)
{
  f(p);
  f(p);
}
// Restrict signature to void(int), but the return value can be anything: it will be ignored
void call_thrice(std::function<void(int)> f, int p)
{
  f(p);
  f(p);
  f(p);
}
// Restrict signature to int(int), to exclude func
void call_four_times(std::function<int(int)> f, int p)
{
  f(p);
  f(p);
  f(p);
  f(p);
}

int main()
{
  call_twice(func, 1); // instantiates void call_twice(void (*)(int), int)
  call_twice(gunc, 1); // instantiated void call_twice(int (*)(int), int)
                     // Note I do not write the explicit types of func and gunc in the above comments, they're not important!

  call_thrice(func, 10); // converts func to a std::function<void(int)>
  call_thrice(gunc, 10); // return value can be ignored, so int(int) is convertible to void(int)

  //call_four_times(func, 100); // will fail to compile: cannot convert a function of signature void(int) to one with signature int(int)
  call_four_times(gunc, 100); // converts gunc to std::function<int(int)>
}

Live demo here.

The basic form of a template declaration starts anything of the form
template<typename T>
template<class T> // same as above
template<int N> // explicitly typed template parameter, need not be an int
template<typename... variadic_template_args>

And of course the forms with combinations of the above, including nested template types and all. Just remember the variadic template parameter must come last.
Templates are what the name implies: a blueprint to create a class with certain functionality expressed within the template definition.
Instantiation occurs when you actually call a template function (from either another instantiated template function or a non-template function), or for class templates, when you declare an object of the type, e.g. for std::vector:
std::vector<double> v; // instantiate the class template std::vector for type double

This is no different to templates that take functions as arguments. Note that functions decay to function pointers when passed to another function.

For example, a class template with a function as template parameter:
#include <iostream>
#include <type_traits> // for std::result_of

template<typename Function, Function f>
struct A
{
  using function_type = Function;
  template<typename... ArgTypes>
  typename std::result_of<Function(ArgTypes...)>::type call(ArgTypes... args)
  {
    return f(args...);
  }
};

void func(int i) { std::cout << "Integer: " << i << ".\n"; }

int main()
{
  A<decltype(&func), func> a;
  a.call(42);
}

Live demo here. Note the extra & in the decltype, because a function only decays to a function pointer when it is passed to a function, not when it is used as a template parameter. Note the "extra" typename before the std::result_of: this is required because its type typedef is a dependent name. These and other times you need to use the template and typename keywords, those are covered in Where and why do I have to put the "template" and "typename" keywords?

A: It's easier to use lambdas
template <typename F>
void herp(F function)
{
    function("Hello from herp");
}

int main()
{
    const auto deDerp = [] (const std::string& msg)
    {
        std::cout << msg << "\n";
    };

    herp(deDerp);
}


text:
Q: Multiple awks from one line I am getting output from access logs to view hit counts, IP address, and user agent. The output isn't working because it's not capturing everything I need in the user agent string.
Example output:
Getting access logs from /var/log/apache2/my.access.log ...

Sorting unique IPs...

COUNT   IP Address | User Agent String

15165 xx.xxx.xxx.xx | "Mozilla/5.0 <--- Need everything between quotes
10704 xx.xxx.xxx.xx | "Mozilla/5.0      not just this portion
 9915 xx.xxx.xxx.xx | "Mozilla/5.0
 8240 xx.xxx.xxx.xx | "Mozilla/5.0
 7770 xx.xxx.xxx.xx | "Mozilla/5.0
 7266 xx.xxx.xxx.xx | "Mozilla/5.0

The line that gets this info is:
cat /var/log/apache2/my.access.log | awk '{print $11 " | " $24 " " $25 " " $26}' | sort -n | uniq -c | sort -nr | head -30

I understand that the portion with $24 " " $25 " " $26 can actually be cleaned up with
awk -F\" '{ print $6 }'

My question is how can I add both of them into a single line, if possible?
Example raw output of log file (with some text altered):
[2018-10-10 10:11:22 (Wed)] | <servername> | R:<servername> | www.<thewebsite>.com | xxx.xxx.xx.xxx |"GET /script/that/was/accessed HTTP/1.1" | 200 | 1430 | 8104 | "https://www.<thewebsite>.com" | "Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko"

I need that last section starting with "Mozilla/5.0 all the way to the other quotation mark, but in the same line as the other awk.


text:
Q: Test Case Outcome Column in TFS 2010 and/or Test Manager I am trying to figure out how to add the work item field Outcome to my queries in TFS 2010 and/or Test Manager 2010 so that I can see our test case results and use them for reporting purposes.
While I realize this column is available through the default reports provided by linking TFS to a SharePoint site, I am currently unable to set this up since our client hasn't configured their SharePoint to do it yet.
My current plan is to create my own reports within Excel, but to break my question down simply, is there anyway to query for this field from within TFS or Test Manager?

A: I found that there really isn't a way to access the Outcome field from TFS or Test Manager currently (up to TFS 2012 for sure).
The easiest way to do it for a project that doesn't have its reports setup (or for Visual Studio Online which doesn't have the test reports) is to do it manually from the results in Test Manager.
Thanks to everyone for viewing and for the help.


text:
Q: Converting an MP3 from a folder to library to burn on a regular CD? I have a CD with MP3 files and when I put it into my media player it cannot find the file. It shows in my folders, so how can I get the folders into my music library to burn to a CD?

A: Among other tools that can do this, iTunes will burn an audio CD for you from MP3 files.


text:
Q: Custom icon with fontello not working React Native Hi I'm trying to implement custom icons following similar tutorials from online but keep running into the same problem with different approaches. First I uploaded the svg to the fontello service. Then I put the .ttf file into my assets/fonts folder. Then I placed the config.json file in my src base folder. Finally, I linked them and even checked build phase settings to make sure its there in xcode. However, the icon doesn't show up with the following code and it shows up instead a question mark inside a white box.What should i be doing?

import { createIconSetFromFontello } from 'react-native-vector-icons';
import fontelloConfig from '../config.json';
const Icon = createIconSetFromFontello(fontelloConfig);
...
 render(){
    <Icon name="Icon_X" size={80} color="#000"/>
 }


text:
Q: Order change in Parent to its child tables using FK relations I have used Aasim Abdullah's stored procedure to dynamically generate code for deletion of child tables, based on parent with certain filter condition. But I am getting a output which is not proper (Query 1). I would like to have output mentioned in Query 2.
--[Patient] is the Parent table, [Case] is child table and [ChartInstanceCase] is grand child
--When I am deleting a grand child table, it should be linked to child table first followed by Parent
Query 1
DELETE Top(100000) FROM [dbo].[ChartInstanceCase]
FROM [dbo].[Patient]
INNER JOIN [dbo].[Case]              ON [Patient].[PatientID]        = [Case].[PatientID]
INNER JOIN [dbo].[ChartInstanceCase] ON [ChartInstanceCase].[CaseId] = [Case].[CaseID]
WHERE [Patient].PracticeID = '55';

Query 2
DELETE Top(100000) [dbo].[ChartInstanceCase]
FROM  [dbo].[ChartInstanceCase]
INNER JOIN [dbo].[Case]    ON [ChartInstanceCase].[CaseId] = [Case].[CaseID]
INNER JOIN [dbo].[Patient] ON [Patient].[PatientID]        = [Case].[PatientID]
WHERE [Patient].PracticeID = '55';

Please let me know how I should modify the SP dbo.uspCascadeDelete to get the output as Query 2?


text:
Q: Difference between assigning function to variable or not I have a worked on a couple different projects and I have seen two different ways of creating jQuery/JavaScript functions.
The first:
function testFunction(){

};

The second:
var testFunction = function (){

};

Is there a difference between these?

A: The main difference is the first one (a function declaration) is hoisted to the top of the scope in which it is declared, whereas the second one (a function expression) is not.
This is the reason you are able to call a function that has been declared after you call it:
testFunction();
function testFunction() {}

You can't do that with a function expression, since the assignment happens in-place:
testFunction();
var testFunction = function() {}; //TypeError

There is also a third form (a named function expression):
var testFunction = function myFunc() {};

In this case, the identifier myFunc is only in scope inside the function, whereas testFunction is available in whatever scope it is declared. BUT (and there's always a but when it comes to Internet Explorer) in IE below version 9 the myFunc identifier wrongly leaks out to the containing scope. Named function expressions are useful when you need to refer to the calling function (since arguments.callee is deprecated).

Also note that the same is true for variable declarations:
console.log(x); //undefined (not TypeError)
var x = 10;

You can imagine that the JavaScript engine interprets the code like this:
var x; //Declaration is hoisted to top of scope, value is `undefined`
console.log(x);
x = 10; //Assignment happens where you expect it to


text:
Q: M1 Max (macOS 12.1): Battery discharging whilst connected to power - should I be concerned about this? It's NEVER unplugged I have Asperger's, so this might just be me not understanding how the 'battery optimisation' feature is supposed to work (it's currently not turned on - according to Settings > Battery > Battery it's switched off until 06:00).
This is making me nervous; at the moment, the computer is never used on battery (my current situation means I can leave it connected 24/7) yet the battery still drains and I have to 'charge to full now' about 4 or 5 times a day. Is this expected behaviour? Why would the battery discharge when it's connected to mains power? I'm using the supplied 140W charger and MagSafe cable, and it's plugged directly into the wall socket, no adapters.
I had a similar issue with my iPads (2017 and 2020 Pros) but, in that case it was because there was a mismatch between the charger and the cable (ie the cable was drawing current faster than the charger could supply it which caused the batteries to drain. Once I bought a more powerful charger, the problem resolved itself).
Obviously, this shouldn't be the case here - should I be having a word with Apple about this? Looking at the battery indicator and seeing it on 72% when it's not been unplugged is somewhat unnerving (this laptop was an early Xmas present from my parents to replace my loathed 2016 Touch Bar).
Unfortunately, despite the nearest Apple Store being just over 3 miles away, ill-health prevents me from making a Genius Bar appointment (should it be warranted). I have AppleCare+ to the end of 2024.
Apologies for what is, probably, another stupid question.
Happy whatever it is you may celebrate (or not)
Sarah

A: Short answer: No, you shouldn't be worried about it as it is because of the Battery Optimization that knows how to handle your charging i.e. when to charge/discharge your mac.

I kept my new mac plugged-in at all times. For 10-12 days, it used to show full 100% charge but recently it started discharging while plugged in. I was also worried about this, but then I found that the charge didn't go below 80%, that means the machine was learning from my charging routine, how I am charging my mac. Once it has gained sufficient data, it knows that I always keep it plugged in, so it will not charge past 80% to prolong battery's life, you can find more information here

If you use optimized battery charging in macOS Big Sur or later, or use macOS Catalina or earlier, occasionally the battery might not show a full charge (100%) in macOS, even after the power adapter has been connected for an extended period of time. This behavior is normal and helps prolong the overall life of the battery.


text:
Q: How to convert this SetLike collection from Scala 2.12 to 2.13? I have this simple immutable Long-based bitset that contains the Card case class. Unfortunately, with the Scala 2.13 collections revamp, it does not compile anymore.
I have looked at the BitSet implementation in Scala 2.13, but it is very verbose. How would I go about converting this class while keeping the code clean and succint? Is there a demo example of such data structure that I could build upon?
import scala.collection.{GenSet, GenTraversableOnce, SetLike}

case class Card(ord: Int)

case class Deck(data: Long) extends Set[Card] with SetLike[Card, Deck] {
    def iterator = new Iterator[Card] {
        var cur = data

        def next = {
            val res = java.lang.Long.numberOfTrailingZeros(cur)
            cur &= ~(1L << res)
            Card(res)
        }

        def hasNext = cur != 0
    }

    override def empty: Deck = Deck.empty
    override def size: Int = java.lang.Long.bitCount(data)
    override def contains(card: Card): Boolean = (data & (1L << card.ord)) > 0
    override def +(card: Card): Deck = Deck(data | (1L << card.ord))
    override def -(card: Card): Deck = Deck(data & ~(1L << card.ord))

    private def toBits(deck: GenTraversableOnce[Card]): Long = deck match {
        case deck: Deck => deck.data
        case _ =>
            var data = 0L
            for (card <- deck) data |= 1L << card.ord
            data
    }

    override def ++(deck: GenTraversableOnce[Card]): Deck = Deck(data | toBits(deck))
    override def &(deck: GenSet[Card]): Deck = Deck(data & toBits(deck))
    override def diff(deck: GenSet[Card]): Deck = Deck(data & ~toBits(deck))
}

object Deck {
    val empty: Deck = Deck(0)
    def of(deck: Iterable[Card]): Deck = empty ++ deck
}

A: Should be something like this; I've commented the notable steps
// SetLike has been sorta superseded by SetOps. Notice the 3rd type parameter -
// that's the return constructor of e.g. deck.map(Some(_))
case class Deck(data: Long) extends Set[Card] with SetOps[Card, Set, Deck] {

  // Minimum definition of set is these two, instead of symbolic names
  override def incl(card: Card): Deck = Deck(data | (1L << card.ord))
  override def excl(card: Card): Deck = Deck(data & ~(1L << card.ord))

  def iterator = new Iterator[Card] {
    var cur = data

    def next() = {
      val res = java.lang.Long.numberOfTrailingZeros(cur)
      cur &= ~(1L << res)
      Card(res)
    }

    def hasNext = cur != 0
  }

  override def empty: Deck = Deck.empty
  override def size: Int = java.lang.Long.bitCount(data)
  override def contains(card: Card): Boolean = (data & (1L << card.ord)) > 0

  // These two are inherited from SetOps but neither their type nor the impl aligns with
  // what you want them to do. You have to re-override them to type as Deck instead of Set[Card]
  override protected def fromSpecific(coll: IterableOnce[Card]): Deck = Deck(toBits(coll))

  override protected def newSpecificBuilder: Builder[Card, Deck] =
    new Builder[Card, Deck] {
      var data = 0L
      def clear(): Unit = data = 0
      def result(): Deck = Deck(data)
      def addOne(elem: Card): this.type = {
        data |= (1L << elem.ord)
        this
      }
    }

  // I kept this as is but you can probably replace it with newSpecificBuilder
  // if you want to keep things more DRY - you could use
  // `newSpecificBuilder.addAll(deck).result()` in fromSpecific
  private def toBits(deck: IterableOnce[Card]): Long = deck match {
    case deck: Deck => deck.data
    case _ =>
      var data = 0L
      for (card <- deck.iterator) data |= 1L << card.ord
      data
  }

  // concat is the only non-final method - union and | just delegate to that.
  override def concat(deck: IterableOnce[Card]): Deck = Deck(data | toBits(deck))

  // this needs a set of unknown-mutability. It has kinda replaced GenSet
  override def diff(deck: scala.collection.Set[Card]): Deck = Deck(data & ~toBits(deck))
}


text:
Q: 3 activity timer produces null errors I have 3 activities:

*

*timer settings that you set the number that the countdown timer starts

*the timer itself

*activated upon pressing the back button

And my problem is that in the pause timer activity(third) when the resume button is pressed the app shows null errors but when the main menu button is pressed the app works fine.
First Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer_settings);
    final NumberPicker np = (NumberPicker)findViewById(R.id.numberPicker2);
    np.setMinValue(1);
    np.setMaxValue(999);
    np.setWrapSelectorWheel(false);

    final Button testbutton = (Button) findViewById(R.id.testbutton);
    testbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent testintent = new Intent(timer_settings.this, timer_2.class);
            Bundle timer2extras = new Bundle();
            timer2extras.putString("timer2string", np.getValue() + "");
            testintent.putExtras(timer2extras);
            startActivity(testintent);
        }
    });
}

Second Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer_2);
    //...
    Bundle timer2extras = getIntent().getExtras();
    String timer2string = timer2extras.getString("timer2string");
    starttime = Integer.parseInt(timer2string);
    starttimeup = starttime*60000;
    starttimedown = starttime*60000;
    int minutes_up_start = (int) (starttimeup / 1000) / 60;
    int seconds_up_start = (int) (starttimeup / 1000) % 60;
    String time_2_up_start_formatted =
    String.format(Locale.getDefault(),"%02d:%02d", minutes_up_start,
    seconds_up_start);
    timer_2_up.setText(time_2_up_start_formatted);

    int minutes_down_start = (int) (starttimedown / 1000) / 60;
    int seconds_down_start = (int) (starttimedown / 1000) % 60;
    String time_2_down_start_formatted =
    String.format(Locale.getDefault(),"%02d:%02d", minutes_down_start,
    seconds_down_start);
    timer_2_down.setText(time_2_down_start_formatted);
    //...

@Override
public void onBackPressed()
{
    startActivity(new Intent(timer_2.this, timer_2_pause.class));
}

Third Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer_2_pause);
    this.setFinishOnTouchOutside(false);
    Button main = (Button)findViewById(R.id.button8);
    Button resu = (Button)findViewById(R.id.button7);
    main.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent mainintent = new Intent(timer_2_pause.this, main_menu.class);
            startActivity(mainintent);
        }
    });
    resu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent resuintent = new Intent(timer_2_pause.this, timer_2.class);
            startActivity(resuintent);
        }
    });

}

A: Your activity two expects to get some data from the intent.
Bundle timer2extras = getIntent().getExtras();
String timer2string = timer2extras.getString("timer2string");

Your timer2extras are null, and when you try to get string from that, it results in null pointer exception.

A: Fixed it by changing onclick for resume :
 resu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });


text:
Q: When registering a table using the %pyspark interpreter in Zeppelin, I can't access the table in %sql I am using Zeppelin 0.5.5. I found this code/sample here for python as I couldn't get my own to work with %pyspark http://www.makedatauseful.com/python-spark-sql-zeppelin-tutorial/. I have a feeling his %pyspark example worked because if you using the original %spark zeppelin tutorial the "bank" table is already created.
This code is in a notebook.
%pyspark
from os import getcwd
# sqlContext = SQLContext(sc) # Removed with latest version I tested
zeppelinHome = getcwd()
bankText = sc.textFile(zeppelinHome+"/data/bank-full.csv")

bankSchema = StructType([StructField("age", IntegerType(),     False),StructField("job", StringType(), False),StructField("marital", StringType(), False),StructField("education", StringType(), False),StructField("balance", IntegerType(), False)])

bank = bankText.map(lambda s: s.split(";")).filter(lambda s: s[0] != "\"age\"").map(lambda s:(int(s[0]), str(s[1]).replace("\"", ""), str(s[2]).replace("\"", ""), str(s[3]).replace("\"", ""), int(s[5]) ))

bankdf = sqlContext.createDataFrame(bank,bankSchema)
bankdf.registerAsTable("bank")

This code is in the same notebook but different work pad.
%sql
SELECT count(1) FROM bank

org.apache.spark.sql.AnalysisException: no such table bank; line 1 pos 21
...

A: I found the problem to this issue. Prior to 0.6.0 the sqlContext variable is sqlc in %pyspark.
Defect can be found here: https://issues.apache.org/jira/browse/ZEPPELIN-134

In Pyspark, the SQLContext is currently available in the variable name sqlc. This is incosistent with the documentation and with the variable name in scala which is sqlContext.
sqlContext can be used as a variable for the SQLContext, in addition to sqlc (for backward compatibility)
Related code:
https://github.com/apache/incubator-zeppelin/blob/master/spark/src/main/resources/python/zeppelin_pyspark.py#L66

The suggested workaround is simply to do the following in your %pyspark script
sqlContext = sqlc
Found here:
https://mail-archives.apache.org/mod_mbox/incubator-zeppelin-users/201506.mbox/%3CCALf24sazkTxVd3EpLKTWo7yfE4NvW032j346N+6AuB7KKZS_AQ@mail.gmail.com%3E

A: Instead of sqlContext, use sqlc and replace registerAsTable by sqlc.registerDataFrameAsTable
%pyspark
from os import getcwd
zeppelinHome = getcwd()
bankText = sc.textFile(zeppelinHome+"/data/bank-full.csv")

bankSchema = StructType([StructField("age", IntegerType(), False),StructField("job", StringType(), False),StructField("marital", StringType(), False),StructField("education", StringType(), False),StructField("balance", IntegerType(), False)])

bank = bankText.map(lambda s: s.split(";")).filter(lambda s: s[0] != "\"age\"").map(lambda s:(int(s[0]), str(s[1]).replace("\"", ""), str(s[2]).replace("\"", ""), str(s[3]).replace("\"", ""), int(s[5]) ))

bankdf = sqlc.createDataFrame(bank,bankSchema)
sqlc.registerDataFrameAsTable(bankdf, "bank")

%sql
SELECT count(1) FROM bank


text:
Q: sorting a table column using react bootstrap not working I am looking into using the react-bootstrap-table library mostly because it seems to be easy to sort columns.
Do I need to stick to the structure used in this library?
My old project is using regular tables and it looks really confusing.
This library looks so easy, I was hoping I'd be able to use elements of the library and not all such as the sort table feature.
I've been looking on here but I'm not finding anything regarding using regular Tables
http://allenfang.github.io/react-bootstrap-table

I'm going to assume I need to use the correct library to get it to work.
such as this.
<BootstrapTable ref='table' data={ products }>
<TableHeaderColumn dataField='id' isKey={ true } dataSort={ true }>Product ID</TableHeaderColumn>
</BootstrapTable>

but i can't do this.

Product ID</TableHeaderColumn>

A: Well, you certainly can't use pieces like that solo end component tag. </TableHeaderColumn>	 is never going to work because there is no corresponding <TableHeaderColumn>.
So the thing is, <TableHeaderColumn> is a component, not a tag. What you are doing is using properties of this component and inserting them as attributes of the  tag. This won't work. I won't say never, because in some cases there are properties that directly translate to tag attributes, but in general - just don't.
If you're going to use component libraries, there are some cases where you can use pieces of components, such as subcomponents, if they are exported and incorporated correctly. I'm afraid this isn't the case with this library. It's meant to work as a whole. The components for the headers provide sorting instructions/data for the functionality of the table body components. That is, the table body components use data provided from the table headers to determine what order the data in your table should be sorted.
I hope this makes sense. In short, this table library works as a whole, not a part. I'm sure with enough time one could pick apart the library and make pieces of it work without the whole but it might be easier/faster just to use the entire library and rebuild your table.
Side notes:
Looking through the React-Bootstrap-Table documentation it first states it's deprecated (I'm mentioning this because your full code hasn't been shown and I'm not sure what version you've imported).
Here's the non-deprecated version: React-Bootstrap-Table2


text:
Q: creating a web image tiler I need to show a rather large image that represents something similar to a construction plan and allow users to place pins on it.
I'd like to do this similarly to how google maps works having the image tiled so the user can zoom in and get a better resolution if needed, as these images can be quite large its quite likely they would want to zoom in pretty far.
I'm considering the best way to do this, the images that would be used would not be a constant size although they would be roughly in the same ballpark say roughly around 3000-4000 x 3000-4000 pixels and they are not neccessarily a square shape.
I am trying to figure out the best way to tile this, I don't know if I can really set a tile size (say like 256px like google maps) and use that as its quite possible that some of the tiles wont fit 256px. I guess I could add tranparency/whitespace to make up the difference or I could alter the entire image before any tiling is completed and add transparency/whitespace to the whole image to make it a square.
I've also considered just defining a certain number of tiles to split the image into, eg. 3 tiles wide by 4 high or similar and just calculate on the fly the required size of the tile, at least this way I think there shouldn't be any transparency fill needed.
Can anyone suggest any pitfalls or other ways to go about this?
I would just use google maps but it doesnt quite suit what I am doing as these points would be located in something like a house where it would be too fine-grained to use gis points.


text:
Q: Python Arguments, Required 1 Argument I am working on a zip file password cracker, and I need a brute-force option. I have the basic code for it written out, but I am not sure of how to use an argument to make it work. How can I write an argument to make this work?
import optparse
import zipfile
import argparse
from threading import Thread

parser = argparse.ArgumentParser()
parser.add_argument("-b", "--brute")

def extract_zip(zFile, password):
    try:
        password_encoded = bytes(password.encode('utf-8'))
        zFile.setpassword(password_encoded)
        zFile.testzip()
        print ("[+] Password Found: " + password + '\n')
    except:
        pass

def Main():
        parser = optparse.OptionParser("useage &prog "+\
                        "-f <zipfile> -d <dictionary> / -b <brute force>")

        parser.add_option('-f', dest='zname', type='string',\
                        help='specify zip file')
        parser.add_option('-d', dest='dname', type='string',\
                        help='specify dictionary file')
        parser.add_option('-b', dest='bname', type='string',\
                        help='specify brute force')
        (options, arg) = parser.parse_args()
        if (options.zname == None) | (options.dname == None) | (options.bname == None):
                print (parser.usage)
                exit(0)
        else:
                zname = options.zname
                dname = options.dname
                bname = options.bname

        zFile = zipfile.ZipFile(zname)
        passFile = open(dname)
        brute = open(bname)

        for line in passFile.readlines():
            password = line.strip('\n')
            t = Thread(target=extract_zip, args=(zFile, password))
            t.start()

        if args.brute:
            characters = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
            for length in range(1, int(args.brute)):
                to_attempt = product(characters, repeat=length)
                t = Thread(target=extract_zip, args=(zFile, password))
                t.start()

if __name__ == '__main__':
    Main()


text:
Q: cvFindExtrinsicCameraParams2() error on iPhone 4 I'm getting an error in OpenCV (v1.1,2.0,2.2) when using the cvFindExtrinsicCameraParams2() method, it works with an iPhone3GS but falls over when tested on the iPhone4. The error is:
"incorrect checksum for freed object - object was probably modified after being freed"
I ended up converting a whole lot of cvMat types to floats as opposed to doubles which resolved the issue but introduced the result overflowing giving me some strange results.
Does the iPhone4 have a stack limit for doubles?
Anyway - just wondering if anyone has resolved this issue? (also - anyone know of an optimized version?)

A: I don't know why you had the error, but to answer your question, the stack has a limited size.
On most systems, the size of float is 4 bytes and double is 8. So when you use double to represent your data, you are actually using twice the space you would with float.
A simple workaround (if you can) is to allocate memory for cvMat on the HEAP instead of the stack. To do this, declare a pointer do cvMat and allocate space for it using the new operator.
The Thread Management doc states that stack size of the iOS main thread is 1 MB and 512K for secondary threads. You might need to do the core of your processing on the main thread.


text:
Q: CSS: -webkit-touch-callout alternatives for android Is there any alternative for -webkit-touch-callout, which works on Android based mobiles.
I'm trying to disable the long touch popup in mobile devices.
I've tried to bind jQuerys taphold event to return false; but no luck...
Any idea?
Thanks!

A: <!DOCTYPE html>
<html>
<head>
  <script>
    function absorbEvent_(event) {
      var e = event || window.event;
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }

    function preventLongPressMenu(node) {
      node.ontouchstart = absorbEvent_;
      node.ontouchmove = absorbEvent_;
      node.ontouchend = absorbEvent_;
      node.ontouchcancel = absorbEvent_;
    }

    function init() {
      preventLongPressMenu(document.getElementById('theimage'));
    }
  </script>
</head>
<body onload="init()">
  <img id="theimage" src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>

Source: Disabling the context menu on long taps on Android