text:
Q: Is is possible to split a generic type? API endpoints that I call deliver data in the following shapes:
interface ArrayResponse<T> {
   data: Partial<T>[]
}

interface ObjectResponse<T> {
   data: Partial<T>
}

I've written a function that calls endpoints and returns responses:
function fetchOne<T>(path: string): ObjectResponse<T> {
  // HTTP call
}

function fetchMany<T>(path: string): ArrayResponse<T> {
  // Exact same HTTP logic as above
}

Ideally I want to have a single response type:
interface Response<T> {
  data: Partial<T> | Partial<T>[]
}

But I what I really want is to be able to have the above type to determine Partial or Partial[] based on the value passed for T.
So Response<T> would result in data: Partial<T> and Response<T>[] results in data: Partial<T>[].
I'm also open to other creative ways of achieving the same effect.

A: You can do that using User-Defined Type Guards
so, if you have these interfaces:
interface ObjectResponse<T> {
  data: Partial<T>
}

interface ArrayResponse<T> {
  data: Partial<T>[]
}

type IResponse<T> = ObjectResponse<T> | ArrayResponse<T>;

You can write this guard function:
function isMultiResponse<T>(response: IResponse<T>): response is ArrayResponse<T> {
  return Array.isArray(response.data);
}

This function will get a type of IResponse<T>, and determines if it's an ArrayResponse<T>. This will allow you to check at runtime what kind of type it is.
This translates to regular javascript, but typescript knows that this function determines the type.
So, for your two functions, you can combine them if the logic is the same:
async function fetchData<T>(path: string): Promise<IResponse<T>> {
  // HTTP call
  return get(path);
}

And when you use the user defined guard function, typescript will know which type the response is:
async function doSomething<T>(): Promise<void> {
  const path = '';
  const res: IResponse<T> = await fetchData(path);

  if (isMultiResponse(res)) {
    // typescript will know the response is ArrayResponse<T>
    console.log(res.data[0]);
  } else {
    // typescript will know the response is ObjectResponse<T>
    console.log(res.data);
  }
}

VS Code in action

the first type is Partial<T>[] as expected

the second type is Partial<T> as expected

Compiled code
When compiled to JavaScript, the isMultiResponse function and if statement will obviously be there. But you probably want a check like that somewhere in your code anyway :-) Writing it using a Type Guard will do the necessary check at runtime, but will also make typescript aware of the two different scenarios and give you feedback accordingly.

A: It can be done. But regardless of how you set this up you would need to manually set the generic T when calling, like fetch<MyType>(path), in order to get a meaningful response type because the generic T cannot possibly be inferred from the path which is a string.
Try this:
function fetchEither<T>(path: string): T extends (infer U)[] ? ArrayResponse<U> : ObjectResponse<T> {
}

With this setup, you would pass in MyType as T to get a single response or MyType[] as T for a multiple response. (note: this assumes that MyType itself would not be an array)
const array = fetchEither<MyType[]>(""); // has type ArrayResponse<MyType>
const object = fetchEither<MyType>(""); // has type ObjectResponse<MyType>

Typescript Playground Link
Given that T cannot be inferred, it might make more sense to just return a union type and determine the value at runtime as proposed by @Thatkookooguy.

A: Maybe someone else can think outside the box better than I, but what you're asking for doesn't seem possible. Posting this answer for the sake of discussion. Let's try a simpler example. What you have right now:
function returnString(): string {
  // returns string
}

function returnNumber(): number {
  // returns number
}

let string: string = returnString();
let number: number = returnNumber();

Now let's say you try to add a union type. Notice that regardless of what happens inside your function at runtime, the compiler can't infer the appropriate type:
type StringOrNumber = string | number;

function returnString(): StringOrNumber {
  // returns string
}

function returnNumber(): StringOrNumber {
  // returns number
}

let string: string = returnString();
// Type 'StringOrNumber' is not assignable to type 'string'.
//  Type 'number' is not assignable to type 'string'.

let number: number = returnNumber();
// Type 'StringOrNumber' is not assignable to type 'number'.
//  Type 'string' is not assignable to type 'number'.


text:
Q: I have problems sending email with javamail + glassfish 4 I have this same code in glassfish 2.1 and running, but to deploy it in glassfish 4 throws me following error:
Grave: javax.mail.MessagingException: 501 5.5.4 Invalid Address.
the error is thrown right over the code:  t.connect(mailhost, user, password);
  public void sendmailto(String amsg, String mailaddress, String asubject) {
    String to = mailaddress;     // to address
    String from = "soporte@EMNI.MOA.MINEM.CU"; // from address
    String subject = asubject;   // the subject line
    String message = amsg;                  // the body of the message
    String mailhost = "atlas"; // SMTP server
    String user = "soporte";                 // user ID
    String password = "soportepass";              // password
    boolean auth = true;
    boolean ssl = false;
    Properties props = System.getProperties();

    if (mailhost != null) {
        props.put("mail.smtp.host", mailhost);
    }
    if (auth) {
        props.put("mail.smtp.auth", "true");
    }
    javax.mail.Session session = javax.mail.Session.getInstance(props, null);

    javax.mail.Message msg = new MimeMessage(session);

    try {
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setText(message);
        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        try {
            if (auth) {
                t.connect(mailhost, user, password);
            } else {
                t.connect();
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            t.close();

        }

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

    }
}

Stacktrace
Grave:   javax.mail.MessagingException: 501 5.5.4 Invalid Address
    at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:2076)
    at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:1469)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:660)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at util.MailSender.sendmailto(MailSender.java:80)
    at tools.MailManager.enviarMail(MailManager.java:119)
    at tools.MailManager.sendmailto(MailManager.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at sun.reflect.GeneratedMethodAccessor179.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.GeneratedMethodAccessor134.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy337.sendmailto(Unknown Source)
    at tools.ErpTools.guardarRegisto(ErpTools.java:151)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at sun.reflect.GeneratedMethodAccessor179.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.GeneratedMethodAccessor134.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy343.guardarRegisto(Unknown Source)
    at usuarios.manejadorSessionBean.login(manejadorSessionBean.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy342.login(Unknown Source)
    at ManagedBean.LoginMB.login(LoginMB.java:88)
    at ManagedBean.LoginMB$Proxy$_$$_WeldClientProxy.login(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAc
Grave:   cessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:275)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)

A: See the JavaMail FAQ for debugging tips.
It looks like it's complaining about your From address or To address.
Note that your code is broken if you choose to use SSL.  If you choose the "smtps" transport, the "mail.smtp.*" properties will be ignored.  Instead of choosing a different transport, set the "mail.smtp.ssl.enable" property.

A: http://www.oracle.com/technetwork/java/javamail/faq/index.html#debug
here I found the solution path...
Step 1) set session debug true
javax.mail.Session session = javax.mail.Session.getInstance(props, null);
session.setDebug(true);

After step 1 I see light over the problem, that is what log show:
DEBUG: setDebug: JavaMail version 1.5.0
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "atlas", port 25, isSSL false
220 atlas.emni.moa.minbas.cu Microsoft ESMTP MAIL Service, Version: 6.0.3790.3959 ready at  Fri, 21 Feb 2014 14:10:50 -0500
DEBUG SMTP: connected to host "atlas", port: 25
EHLO info0.emni.moa.minbas.cu.
501 5.5.4 Invalid Address
HELO info0.emni.moa.minbas.cu.
501 5.5.4 Invalid Address
step 2) set the "mail.smtp.localhost" property ... (my computer name 'info0')
props.put("mail.smtp.localhost", "info0");

ORACLE JAVAMAIL'DOC SAY:
The SMTP provider uses the results of InetAddress.getLocalHost().getHostName() in the SMTP HELO command. If that call fails to return any data, no name is sent in the HELO command. Check your JDK and name server configuration to ensure that that call returns the correct data. You may also set the "mail.smtp.localhost" property to the name you want to use for the HELO command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux C: Do System V message queues have a file descriptor on which `poll` can be called? The question is basically already in the title.
Do System V message queues have a file descriptor on which poll can be called such that the calling program knows as soon as possible in case a new message arrives?
Edit: Is it possible to link the file pathname returned by
key_t ftok (const char *pathname, int proj_id);

with the System V msg queue in case it uses the key ftok returns, like this?
int msgget (key_t key, int msg_flags);


text:
Q: Can I have multi schema DB on a single AWS Aurora PostgreSQL instance? We're working on a multi-tenant SaaS solution that has 4 different subscription Plans, so we want to have their data isolated in a single cluster DB (everybody sharing a single logical instance) but with a different schema per tenant (plan), which seems to be better for us from a cost point of view. How should we create it?
Any clue will be welcome!


text:
Q: Did Section 31 appear in Star Trek: The Next Generation? Can anyone confirm whether Section 31 ever appeared in a Star Trek: The Next Generation episode?

A: They did not. The organisation was invented for the DS9 episode Inquisition, broadcast 4 years after the last episode of TNG.

Q. Was there any debate about whether or not to establish that [Section 31,
in "Inquisition"] has been around for so long?
A. We had extended conversations about the backstory to Section 31 and yes,  there was a lot of debate about how long and under what
circumstances this  branch had existed.
Ronald D. Moore - Webchat AOL

That being said, Section 31 comes into conflict with the crew of the TNG Enterprise a few years after Nemesis in the EU novel Star Trek: Section 31: Control.

Data felt great pride at the progress his daughter had made in so
short a time. When he was her age, he had still been struggling to
master basic interactions with organic sentient beings. By contrast,
Lal meshed easily with organic beings, and in spite of what Data had
originally considered her fragile emotional state, she was
demonstrating tremendous calm and poise in the face of a serious and
perhaps even existential threat from Section 31.

A: As @Valorum already stated, 'Section 31' as a department was  thought up during DS9's run, but in-universe the organisation, or specifically the article in the Starfleet charter that lends its name to the covert-ops branch, has existed since the very beginning. Here's a quote from the Star trek: Enterprise episode Divergence, where Phlox is ... involuntarily re-assigned.

ARCHER: Phlox was kidnapped. Starfleet would never authorise that.
HARRIS [on monitor]: Reread the Charter, Article 14, Section 31. There are a few lines that make allowances for bending the rules during times of extraordinary threat.

http://www.chakoteya.net/Enterprise/92.htm


text:
Q: Uploading a photo using XMLHtttpRequest to a Flask webserver I'm creating a WinJS app and using XMLHttpRequest to send a photo as a blob to a Flask webserver.
openPicker.pickSingleFileAsync().then(function (file) {
        file.openAsync(Windows.Storage.FileAccessMode.read).done(function (stream) {
            var blob = MSApp.createBlobFromRandomAccessStream("application/octet-stream", stream);
            var fdata = new FormData();
            fdata.append("file", blob, "photo.jpg");

            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("POST", "http://127.0.0.1:5000/api/addPhoto", true);
            xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
            xmlhttp.send(fdata);
        });
    });

This results in the following HTTP request:
POST http://127.0.0.1:5000/api/addPhoto HTTP/1.1
Accept: */*
Content-Type: application/octet-stream, multipart/form-data; boundary=---------------------------7dd2a320aa0ec0
Accept-Language: en-US,en;q=0.7,ja;q=0.3
UA-CPU: AMD64
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; MSAppHost/1.0)
Host: 127.0.0.1:5000
Content-Length: 9471100
Connection: Keep-Alive
Pragma: no-cache

-----------------------------7dd2a320aa0ec0
Content-Disposition: form-data; name="file"; filename="photo.jpg"
Content-Type: application/octet-stream

Handling the request on the Flask web server
UPLOAD_FOLDER = '/images'
@app.route('/api/addPhoto', methods=['POST'])
def addPhoto():
        if request.method == 'POST':
            f = request.files['file']
            if f and allowed_file(f.filename):
                    return "error" #add error response here
        else:
                    filename = secure_filename(f.filename)
                    f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    f.close
                    return "ok" #add success response here

I'm getting the following error:
TypeError: 'ImmutableMultiDict' object is not callable

I have a few questions that I can't find answers for:

*

*Am I sending the data in the right format? Am I appending data to my form correctly?

*Are my HTTP content types correct?

*Am I trying to pull the file from the HTTP request incorrectly?

Thank you!

A: try to replace this:
f = request.files('file')

with:
f = request.files['file']


text:
Q: Activity indicator is not being removed from googlemap view I have developed a google map in which i am displaying atm's nearby user location. I have added an activity indicator to animate when my application is getting the information and it should stop when it has got.
I have written the following code to do so. My activity indicator is being displayed but it is not removed. Please help me to do so.
   #import "ViewController.h"
#import <GoogleMaps/GoogleMaps.h>

@interface ViewController ()<GMSMapViewDelegate>
{
    NSUserDefaults *latitudess;
    NSUserDefaults *longitudess;
    GMSMapView *mapView_;
    UIView *viewForSlider;
    UILabel *labelToShowCurrentRadiusValue;
    NSMutableData *urldata;
    NSInteger *j;
    UIActivityIndicatorView *spinner;

}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    mapView_ = [[GMSMapView alloc] init];

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:22.595769
                                                            longitude:88.263639
                                                                 zoom:12];

    mapView_ = [GMSMapView mapWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height) camera:camera];
    mapView_.delegate=self;
    mapView_.settings.myLocationButton = YES;
    mapView_.myLocationEnabled = YES;
    [self.view addSubview:mapView_];

    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(22.595769, 88.263639);
    marker.title = @"Howrah";
    marker.snippet = @"Kolkata";
    marker.map = mapView_;

    viewForSlider = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 62.0 , self.view.frame.size.width, 62.0)];
    viewForSlider.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.9];

    [self.view addSubview:viewForSlider];

    labelToShowCurrentRadiusValue =[[UILabel alloc]initWithFrame:CGRectMake(0, 8.0, viewForSlider.frame.size.width, 20.0)];
    labelToShowCurrentRadiusValue.backgroundColor=[UIColor clearColor];
    [labelToShowCurrentRadiusValue setFont:[UIFont systemFontOfSize:15.0]];
    labelToShowCurrentRadiusValue.textAlignment=NSTextAlignmentCenter;
    labelToShowCurrentRadiusValue.textColor=[UIColor colorWithRed:84.0/255.0 green:84.0/255.0 blue:84.0/255.0 alpha:1.0];
    [viewForSlider addSubview:labelToShowCurrentRadiusValue];

    [self startUserTracking];
   [self displayAtm];

spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
    spinner.color = [UIColor blueColor];
    [spinner startAnimating];
        [self.view addSubview:spinner];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

-(void)startUserTracking
{

    if (mapView_.observationInfo == nil)
    {
        [mapView_ addObserver:self
                   forKeyPath:@"myLocation"
                      options:NSKeyValueObservingOptionNew
                      context:NULL];

        dispatch_async(dispatch_get_main_queue(), ^{
            mapView_.myLocationEnabled = YES;
        });
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{

    CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];

    mapView_.camera = [GMSCameraPosition cameraWithTarget:location.coordinate
                                                     zoom:15];

    labelToShowCurrentRadiusValue.text = [NSString stringWithFormat:@"%f , %f", location.coordinate.latitude, location.coordinate.longitude];
    latitudess=[NSUserDefaults standardUserDefaults];
    longitudess=[NSUserDefaults standardUserDefaults];
    [latitudess setFloat:location.coordinate.latitude forKey:@"LATITUDE"];
    [latitudess setFloat:location.coordinate.longitude forKey:@"LONGITUDE"];
    [latitudess synchronize];

    @try {
        [mapView_ removeObserver:self forKeyPath:@"myLocation"];
    } @catch(id exception){

    }

}

-(void)displayAtm
{

    latitudess=[NSUserDefaults standardUserDefaults];

    float retrievedlat=[latitudess floatForKey:@"LATITUDE"];
    float retrievedlong=[latitudess floatForKey:@"LONGITUDE"];
    NSLog(@"detail=%f",retrievedlat);

    NSString *urlforrequest=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=atm&name=atm&key=*******",retrievedlat,retrievedlong];
    NSURL *finalurl=[NSURL URLWithString:urlforrequest];

    urldata=[[NSMutableData alloc]initWithContentsOfURL:finalurl];
    NSError *error;
    id jsonresults=[NSJSONSerialization JSONObjectWithData:urldata options:kNilOptions error:&error];

    NSArray *datarray= [jsonresults objectForKey:@"results"];
    for (int i=0; i<datarray.count; i++)
    {
        GMSMarker *marker=[[GMSMarker alloc]init];
        NSDictionary *geometryretrieved=[[datarray valueForKey:@"geometry"]objectAtIndex:i];
        NSDictionary *coordinatesretrieved=[geometryretrieved valueForKey:@"location"];
        marker.position=CLLocationCoordinate2DMake([[coordinatesretrieved objectForKey:@"lat"] doubleValue], [[coordinatesretrieved objectForKey:@"lng"]doubleValue]);
        marker.title=[[datarray valueForKey:@"name"]objectAtIndex:i];
        marker.map=mapView_;

        [spinner removeFromSuperview];

    }

}

Thanks in advance.

A: change in view didload call this method last after display spinner in [self displayAtm];
- (void)viewDidLoad
{
    [self startUserTracking];
   //  [self displayAtm];

spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
    spinner.color = [UIColor blueColor];
    [spinner startAnimating];
        [self.view addSubview:spinner];

[self displayAtm];

}


text:
Q: Encoding problem with bibliography in tufte class I try to make a bibliography using tufte book style. As you see, the bibliography reference on the margins is all messed up.

I hope you understand, these weird margin symbols are not Russian, but the text is. I feel the problem is with an encoding (that is why the example is language oriented), but I don't understand why.
How to fix margin text into normal language, uploaded by babel-package? How to translate the word "and" automatically inserted by tufte-class for several citations? (boxed on the picture)
MWE:
\documentclass{tufte-book}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\usepackage[OT1]{fontenc}
\usepackage{lipsum}

\begin{document}

Этот вопрос волнует обучающих\cite{Poya} и
обучающихся\cite{Gabovich, GPY} с момента возникновения самих задач.

\backmatter
\bibliography{Bibliography}
\bibliographystyle{plainnat}

\end{document}

Output - see above.
The bibliography looks fine:

No problems with compilation. Bibliography.bib is a modification of sample-handout.bib provided by Tufte.
@BOOK{Sharygin,
    author = {И. Ф. Шарыгин},
    title = {Геометрия 10--11. Учебник для общеобразоватлеьных учебных заведений},
    year = {1999},
    publisher = {Дрофа},
    address = {Москва}
}

@BOOK{Sharygin500,
    author = {И. Ф. Шарыгин},
    title = {500 задач геометрического стандарта},
    publisher = {Просвещение},
    year = {2007},
    address = {Москва}
}

@BOOK{Sharygin10,
    author = {И. Ф. Шарыгин},
    title = {Факультативный курс по математике. Решение задач. Учебное пособие для 10 класса средней школы},
    publisher = {Просвещение},
    year = {1989},
    address = {Москва}
}

@BOOK{Sharygin11,
    author = {И. Ф. Шарыгин, В. И. Голубев},
    title = {Факультативный курс по
    математике. Решение задач. Учебное пособие для 11 класса средней школы},
    publisher = {Просвещение},
    year = {1991},
    address = {Москва}
}

@BOOK{Gabovich,
    author = {И. Г. Габович},
    title = {Алгоритмический подход к решению геометрических задач},
    publisher = {Просвещение},
    year = {1996},
    address = {Москва}
}

@BOOK{GPY,
    author = {В. Б. Полонский, Е. М. Рабинович, М. С. Якир},
    title = {Учимся решать задачи по геометрии},
    publisher = {Магiстр-S},
    year = {1996},
    address = {Киев}
}

@BOOK{Poya,
    author = {Г. Пойя},
    title = {Как решать задачу?},
    publisher = {Квантор},
    year = {1992},
    address = {Львов}
}

@BOOK{Zel,
    author = {О. П. Зеленяк},
    title = {Решение задач по планиметрии.Технология алгоритмического подхода на основе задач--теорем},
    publisher = {ДМК, Диасофт},
    year = {2008},
    address = {Киев}
}

@BOOK{GGK,
    author = {И. М. Гельфанд, Е. Г. Глаголева, А. А. Кириллов},
    title = {Метод координат},
    publisher = {Наука},
    year = {1973},
    address = {Москва}
}

@BOOK{Kushnir,
    author = {И. А. Кушнир},
    title = {Векторные методы решения задач},
    publisher = {Обериг},
    year = {1994},
    address = {Киев}
}

@BOOK{KushnirGB,
    author = {И. А. Кушнир},
    title = {Геометрия на баррикидах},
    publisher = {Факт},
    year = {2009},
    address = {Киев}
}

@BOOK{Kiselev,
    author = {А. П. Киселёв},
    title = {Геометрия. Планиметрия.
    Стереометрия. Учебник},
    publisher = {Физматлит},
    year = {2004},
    address = {Москва}
}

@BOOK{Prasolov,
    author = {В. В. Прасолов},
    title = {Задачи по стереометрии},
    publisher = {МЦНМО},
    year = {2010},
    address = {Москва}
}


text:
Q: Force download of a txt via js in php page I'm trying to get a txt file (created on-the-fly) automatically downloaded.
The following code is not working, because the user gets redirected to a page showing the txt instead of downloading it.
What I want, instead, is that clicking on the form (top part of the code) causes the page to refresh (which happens) and then the file downloaded. If a change the file format to rtf, e.g., I can download it, but not a txt.
=================NOT WORKING CODE==================
      echo "
      <form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
      // more not related stuff
      <input type=\"image\" src=\"".JURI::root().
      "components/com_comp/images/download_icon.png\" .
      "\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
      // more not related stuff";

      if($_POST['downloadaddresses_x']!=0) {

            $myfilename = "tmp/results.txt";
            $fh = fopen($myfilename, 'w');

            $recipients = $_POST['recipients'];
            $semicolon_separated = implode(";", $recipients);
            fwrite($fh, $semicolon_separated);
            fclose($fh);

            echo "
            This download should start automatically!";
            echo "";
        }

A: need to specify the content type in the header of your PHP file
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="your_filename_here.txt"');
echo file_get_contents('path_to_file.txt');

A: Headers, you got this.
header("Content-type: text/plain")


text:
Q: How to create a varying variable name in python How can I create varying variable name?
like i am iterating in a loop say from 0 to 100.
I need to create  different variable in each iteration and assign some values to it. an example
for i in range(0,100):
   'var'+i=i

Doesnot seems valid. I want to create variables in each iteration like var0,var1 etc and should be able to access it with that names. Can some one suggest me a solution

A: To solve this, you can try something like this:
for x in range(0, 9):
    globals()['var%s' % x] = x

print var5

The globals() function produces a list-like series of values, which can be indexed using the typical l[i] syntax.
"var%s" % x uses the %s syntax to create a template that allows you to populate the var string with various values.

A: Unless there is a strong reason to create multiple variables on the fly, it is normally in these situations to put things in a list of some sort,
or a dictionary:
mydict = {'var{}'.format(i):i for i in range(1,101)}

Now access values with:
mydict["var1"] # returns 1
mydict.get("var1") # returns 1
mydict.get("var101") # returns None

A: I don't like your Idea but yeah you can do it in python:
for i in range(0,100):
    exec('var{i} = {i}'.format(i=i))

A: I wouldn't recommend doing this using varying variable names. Instead, you could put everything into a list and you would still be able to access each value independently. For example, you could do:
var = []
for i in range(100):
    var.append(i)

Then you can access any element from that list like so:
var[33]

This would return the number 33.
If you really did want each to be its own variable, you could use exec as others have noted.

A: You should better use dictionary for this:
var_dict = {
    'var'+str(i): i
        for i in range(10)
}
var_dict['var0']


text:
Q: Can the internal IP addresses of azure worker role instances be swapped? Like if one is on 192.168.1.1 and the other on 192.168.1.2, can you configure the machine's to each other's static IP addresses and thereby have them start receiving information for each other's InstanceInputEndpoints (since now the Azure gateway should route the InstanceInputEndpoint to the new owner of the IP address)?

A: No, you can't do that!
And, as of today (Dec. 2013) you are highly advised to never set static IP Address of your Virtual Machine inside Windows Azure! You should always use default DHCP configuration. If you wand IP Address predictability check out this blog post. You can still use Azure Virtual Network with Web and Worker Roles and have IP Address predictability.

A: If you use VM you should create several VM and a Networks, define address space you will use. When you create a VM, make sure your VM is using the networks that you create. If you forget to include the vm into the network, you need to recreate the VM.
Example how to change the internal IP using 3 VM:
Server A is connected to the network and get ip 192.168.0.1
Server B 192.168.0.2
Server C 192.168.0.3
shutdown all your server from azure portal so that the status is deallocated then turn it on with this sequence:
Server B
Server C
Server A
The Result will be:
Server A 192.168.0.3
Server B 192.168.0.1
Server C 192.168.0.2
If you turn off the VM from inside the VM, it won't be change the internal IP.

A: If you remote onto one of your VMs, you will see an XML file at
C:\config

The filename looks something like
[deployment id]_[role name]_[instance number].[version number]

Inside the file you will find all the instances in the deployment with their IP addresses. If you edit the IP address in this file for a particular role instance on a particular VM, that VM will think that the IP address for the instance is the one in the file and will start routing traffic to it.
Warning: I've never tried to do this programmatically. Also, the changes will get wiped out if there is any update to the deployment (either initiated by you or by Azure). And there might be some other horrible side effect.


text:
Q: Attach an agent remotely using Bytebuddy I am trying to attach an agent for a process using bytebuddy .I found that we can use ByteBuddyAgent.attach(file,"18467"); for this. But when i am trying to do this following errors occurring.
This is agent i used
File file = (new File("Agent.jar"));
Error
java.lang.IllegalStateException: Error during attachment using: net.bytebuddy.agent.ByteBuddyAgent$AttachmentProvider$Compound@e26db604
    at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:378)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:227)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:202)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:189)
    at common.netty.echo.EchoHttpServer.main(EchoHttpServer.java:95)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bytebuddy.agent.Attacher.install(Attacher.java:77)
    at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:373)
    ... 4 more
Caused by: com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded
    at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:106)
    at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
    at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)
    ... 10 more

Any idea for this ? and When i try to use this attachment from another agent as follows
public class Agent {

    public static void premain(String args, Instrumentation instrumentation) {

        System.out.println("Premain");
        File file ;
        try {

                file = (new File("Agent.jar"));
                ByteBuddyAgent.attach(file,"18467");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

    }

I am getting this error
Error
java.lang.IllegalStateException: Error during attachment using: net.bytebuddy.agent.ByteBuddyAgent$AttachmentProvider$Compound@423f0955
    at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:378)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:227)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:202)
    at net.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:189)
    at common.netty.echo.Agent.premain(Agent.java:111)
    at common.netty.echo.EchoHttpServer.<clinit>(EchoHttpServer.java:56)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bytebuddy.agent.Attacher.install(Attacher.java:77)
    at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:373)
    ... 5 more
Caused by: java.lang.UnsatisfiedLinkError: Native Library /usr/lib/jvm/java-8-oracle/jre/lib/amd64/libattach.so already loaded in another classloader
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1907)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1845)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:342)
    at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
    at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)
    ... 11 more

Any suggestion on this!!

A: As for the first error message: does the target VM run the attachment listener? You can try to force starting the thread by setting -XX:+StartAttachListener which should be set by default. What JVM version are you running?
The other error message indicates that the attachment library was already loaded by another class loader. See this answer for further details: java.lang.UnsatisfiedLinkError: Native Library XXX.so already loaded in another classloader


text:
Q: Talking about a specific place to people who doesn't know this place Let's say I want to describe something that occurred at a specific place (althought the place where it occurred isn't important at all - I'm just mentioning it) but the people I'm talking to doesn't know anything about this place. So if I say something like…

I was spending some time at the bar last night when an idea popped
  into my head.

Does this phrase make any sense? Would people ask themselves "what bar is this guy talking about?" Should I be more specific and say something like:

I was spending some time at a bar near my house last night when an
  idea popped into my head.

or

I was spending some time at the new bar around the corner last night
  when an idea popped into my head.

A: Is the person you are talking to likely to ask 'Which bar?'. Generally, we tell people as much as they need to know to understand what we are saying. If your idea could have popped into your head at any bar, then it is not important to say exactly which bar you were at (but you can). If your idea is somehow related to exactly which bar you are in, then it's more important to say so: I was spending some time at a bar near my house last night when an idea popped into my head. I could dig a tunnel from here to my house.

A: Your example phrase does make sense, and wouldn't necessarily make me think "what bar is this guy talking about?" - in colloqial British English at least, it is very common to say "I was down the pub the other week" and for it to be understood "the" pub is probably the speaker's local/habitual pub, and/or whatever pub they happened to be in, it doesn't matter.
In a strictly grammatical sense, however, it does imply a specific bar, and in different contexts with different speakers it is possible a listener may find themselves which place you mean.  To make it more clear the particular bar/place does not matter, you could simply say "I was spending some time at a bar last night..."  Using the indefinite article with no qualification ("around the corner") is an implicit  statement that the specific X is irrelevant.
Adding further description / qualification of the particular bar could add useful context or simply colour to the anecdote, or it could be seen as extraneous information, distracting from the point.  It's up to you, no right or wrong.


text:
Q: How to write an Async Sub in VB.NET? Public Class LoginManager
    Implements ILoginManager
    Private ReadOnly _iLoginRepository As ILoginRepository
    Public Sub New()
        _iLoginRepository = New LoginRepository()
    End Sub

    Public Async Sub InsertFailedLoginAttempt(failedLoginAttempt As FailedLogin) Implements ILoginManager.InsertFailedLoginAttempt
        'Example of the S in Solid (Single Repsonsibilty)
        'Need to call these method async. But await errors
            _iLoginRepository.InsertFailedLoginAttemptAsync(failedLoginAttempt)
            _iLoginRepository.InsertFailedLoginAttemptIntoLoginMasterAsync(failedLoginAttempt)
        End Sub
    End Class

Repsoitory Interface:
Public Interface ILoginRepository
    Function IsUserAuthenticatedAsync(ByVal cID As String, ByVal password As String, ByVal IsExternalUser As Boolean) As Task(Of Boolean)
    Sub InsertFailedLoginAttemptAsync(ByVal failedLoginAttempt As FailedLogin)
    Sub InsertFailedLoginAttemptIntoLoginMasterAsync(ByVal failedLoginAttempt As FailedLogin)

End Interface

Repository Implementation:
Public Class LoginRepository
    Implements ILoginRepository
    Public ReadOnly _applicationDBContext As New ApplicationDBContext()

    Public Async Sub InsertFailedLoginAttemptAsync(failedLoginAttempt As FailedLogin) Implements ILoginRepository.InsertFailedLoginAttemptAsync
        Using _applicationDBContext
            _applicationDBContext.RepFailedLogins.Add(failedLoginAttempt)
            Await _applicationDBContext.SaveChangesAsync()
        End Using
    End Sub

    Public Async Sub InsertFailedLoginAttemptIntoLoginMasterAsync(failedLoginAttempt As FailedLogin) Implements ILoginRepository.InsertFailedLoginAttemptIntoLoginMasterAsync
        Using _applicationDBContext
            _applicationDBContext.RepFailedLoginMasters.Add(failedLoginAttempt)
            Await _applicationDBContext.SaveChangesAsync()
        End Using
    End Sub

    ''' <summary>
    ''' Determine whether a user is authenticated, be it an internal or external user
    ''' I have condensed two methods into one
    ''' </summary>
    ''' <param name="cID"></param>
    ''' <param name="password"></param>
    ''' <param name="IsExternalUser"></param>
    ''' <returns></returns>
    Public Async Function IsUserAuthenticatedAsync(cID As String, password As String, IsExternalUser As Boolean) As Task(Of Boolean) Implements ILoginRepository.IsUserAuthenticatedAsync
        If (IsExternalUser And String.IsNullOrEmpty(password)) Then
            Throw New ArgumentNullException("External user requires password")
        End If

        Dim user As Chaser
        Dim toRet As Boolean

        Using _applicationDBContext
            'Two ways to use LINQ
            'First is LINQ Lambda sybntax(little harder to read)
            user = Await _applicationDBContext.Chasers.Where(Function(x) x.CID = cID).FirstOrDefaultAsync()

            'Second is LINQ Query syntax(looks more like SQL just more verbose
            'user = From x In _applicationDBContext.Chasers
            '       Where x.CID = cID
            '       Select x
        End Using

        If IsNothing(user) Then
            toRet = False
        ElseIf Not IsExternalUser And Not IsNothing(user) Then
            toRet = True
        ElseIf IsExternalUser And user.Hash_Password = password Then
            toRet = True
        End If

        Return toRet
    End Function
End Class

I'm trying to call the InsertFailedLoginAttemptAsync repository method in my manager. It is an async method but I am unable to await the method. How can I make this method awaitable?
I believe it has something to do with the interface and not making it an async method like in C# but I'm unable to do this.

A: Subs should not be async. Event handlers are the only exception to that rule. You await Task which can only be returned from a Function. If the intention is to make that interface async then all the members need to be functions that return a Task or its derivative.
Async is something that bubbles all the way through when used. That said the ILoginManager along with the ILoginRepository should be refactored (if possible) to follow the proper syntax.
Reference: Async/Await - Best Practices in Asynchronous Programming

A: Fixed via Nkosi's reply:
Interface:
Public Interface ILoginRepository
    Function IsUserAuthenticatedAsync(ByVal cID As String, ByVal password As String, ByVal IsExternalUser As Boolean) As Task(Of Boolean)
    Function InsertFailedLoginAttemptAsync(ByVal failedLoginAttempt As FailedLogin) As Task
    Function InsertFailedLoginAttemptIntoLoginMasterAsync(ByVal failedLoginAttempt As FailedLogin) As Task

End Interface

Manager method:
 Public Async Function InsertFailedLoginAttempt(failedLoginAttempt As FailedLogin) As Task Implements ILoginManager.InsertFailedLoginAttempt
        'Example of the S in Solid (Single Repsonsibilty)
        Await _iLoginRepository.InsertFailedLoginAttemptAsync(failedLoginAttempt)
        Await _iLoginRepository.InsertFailedLoginAttemptIntoLoginMasterAsync(failedLoginAttempt)
    End Function


text:
Q: xslt - how to specify a single node value? <Tags>
  <Tag TagName="#CC" TagDataType="Text" TagValue="" />
  <Tag TagName="#BCC" TagDataType="Text" TagValue="" />
  <Tag TagName="#To" TagDataType="Text" TagValue="" />
  <Tag TagName="#DocID" TagDataType="Text" TagValue="00000001" />
  <Tag TagName="#Date" TagDataType="DateTime" TagValue="20000917213300" />
  <Tag TagName="#Subject" TagDataType="Text" TagValue="" />
</Tags>

 <xsl:for-each select="Tags/Tag"> <!-- works, give me all tags -->

   <xsl:value-of select="@TagValue" />

 </xsl:for-each>

<xsl:value-of select="Tags/Tag/@TagValue[1]" /> <!-- doesn't give me anything -

When I use the for-each, I get all the TagValues in the order listed.  I now need to display these values in a different order.  So, I abandoned the for-each and tried using the a single statement to get a single value, without success.  How can I specify a specific TagValue to be displayed?  I'm using XSLT 1.0.

A:
I now need to display these values in a different order. So, I
  abandoned the for-each

That makes no sense. If you want "to display these values in a different order", you need to sort them. Try the following stylesheet:
XSLT 1.0
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <output>
        <xsl:for-each select="Tags/Tag[string(@TagValue)]">
            <xsl:sort select="string-length(substring-before('#DocID#Date#To#CC#BCC#Subject', @TagName))" data-type="number" order="ascending"/>
            <value name="{@TagName}"><xsl:value-of select="@TagValue" /></value>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

This takes all non-empty TagValue values and sorts them by the following custom order: #DocID, #Date, #To, #CC, #BCC, #Subject. When applied to the following test input:
<Tags>
    <Tag TagName="#CC" TagDataType="Text" TagValue="" />
    <Tag TagName="#BCC" TagDataType="Text" TagValue="bcc recipient" />
    <Tag TagName="#To" TagDataType="Text" TagValue="" />
    <Tag TagName="#DocID" TagDataType="Text" TagValue="00000001" />
    <Tag TagName="#Date" TagDataType="DateTime" TagValue="20000917213300" />
    <Tag TagName="#Subject" TagDataType="Text" TagValue="my subject" />
</Tags>

the result will be:
<?xml version="1.0" encoding="UTF-8"?>
<output>
   <value name="#DocID">00000001</value>
   <value name="#Date">20000917213300</value>
   <value name="#BCC">bcc recipient</value>
   <value name="#Subject">my subject</value>
</output>


text:
Q: Unable to upgrade from SQL Server 2012 evaluation to Standard I was using SQL Sever 2012 Evaluation edition. As it was about to expire, we purchased a Standard edition license.
I was told that I don't need the lisence key as it was embedded in the ISO installation file. However, when trying to run the installation file, I get the message - There are no SQL Server instances or shared features that can be updated on this computer.
The reason for this is that the edition that I was trying to install was 2012 SP1, which is the version that I was already on.
When trying to do the upgrade using the Configuration manager and then choosing maintainance -> Upgrade, I get asked for the product key, which I don't have.
The advice from the Microsoft account manager was to let my product expire and then try the upgrade again. However after the product expired I still have exactly the same issue.
Any advice besides uninstalling SQL and reinstalling?
Thanks,
Niel

A: You should be able to run an 'Edition Upgrade' of an existing SQL Server instance, even on an expired evaluation, you can do it via the SQL Server setup from the Installation media, and SQL Server Installation Center, by clicking on 'Maintenance', then 'Edition Upgrade' and follow the rest of the installation from there.
The error message is generally caused by applying incorrect versions (patched up, language incorrect etc.) on an instance that is different.  The 'Select features' page has a description message on the top right side of the page explaining what is ocurring.  I'd suggest taking a look there first of all.
Please check this post, although it relates to 2008 R2, the error fix is the same in 2012 :-
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/c82da968-bbfb-4803-a9b2-876776f033d6/there-are-no-sql-server-instances-or-shared-features-that-can-be-updated-on-this-computer?forum=sqlsetupandupgrade
This should have the answers that you need.
Regards,
Dave


text:
Q: C# Cannot call constructor for class B which has an attribute of class A. ERR: Non-invocable member cannot be used like a method So I'm really going crazy with this:
public class foo
{
    int attributeA;

    public foo(int a)
    {
        attributeA = a;
    }
}

public class goo
{
    foo attributeA;

    public goo(int a)
    {
        ERROR HERE-> attributeA = foo(a);
    }
}

I get an error when trying to call the constructor for the foo class foo in order to make an object of the class goo.
The error I get is: Non-invocable member cannot be used like a method
I really don't get it, why is it non invocable? How can I fix it? I just want to create a simple class which uses another class as one of its attributes and It's already taken me like 5 hours. Thank you.

A: You forgot to use new, which is needed for calling constructors.
attributeA = foo(a);
should be
attributeA = new foo(a);


text:
Q: Opencv ip camera bad memory access exception using rtsp protocoll in Mat.inl.hpp header I'm trying to connect to a ip camera by rtsp protocoll to solve a object detection task, my issue is the access to the camera. I use the rtsp protocoll, and when I launch the system in release mode, after few minutes it gives me a bad memory access exception:

I access the camera using the following code:
VideoCapture cap;
Mat src;
cap.open("rtsp://<xxx>:<xxx>@ip_adress:554");

while(true){

    cap.copyTo(src);
    resize(src, src, Size(640, 480));
    imshow("source", src);
    char k = (char)cv::waitKey(25);

    if (k == 27)
        break;
}

I process the frame to apply a neural network, and I don't figure why the system give me this exception, after 4/5 minutes.
Thank's.


text:
Q: Diamond and UV light In the paper

Characteristics of 2-photon ultraviolet laser etching of diamond. RP Mildren et al. Opt. Mater. Express 1, 576 (2011),

I found out that UV light cause the atom ejection from the surface of diamond. According to the article, the process is caused by the presence of UV light and there's no threshold meaning that the loss of mass will happen even under sunlight. My question is: if there's no threshold, does that mean that the process will happen even under visible light in standard irradiance or there's definitely necessary to have UV rays? Thank you.

A: By analogy with the photoelectric effect, you can have "no threshold" of intensity, yet have a threshold of wavelength. If an individual photon does not have sufficient energy to kick an atom off the surface, then the effect will not occur.
If they say "you need UV", then you need UV. Of course there is a small component of UV in sunlight (some of it is filtered by air, so it's a function of altitude).


text:
Q: Why does the server respond iteratively with each new piece of input data I send it from the console? I am just trying to learn some client-server basics and I'm almost there with what I'm trying to do. I am just sending the server some input and having it respond back to the client with the data it received. However, it works fine once I send the first piece of data but once I send another input the server responds with two instances of that same piece of data, and so on. How do I get around this?
Server:
var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var server = net.createServer();
server.on('connection', function(sock) {
  console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

  sock.on('data', function(data) {
    console.log('DATA ' + sock.remoteAddress +':' + data);
    // write back data received to the client
    sock.write('You said "' + data + '"');
  });
});

server.listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

Client:
var net = require('net');
var readline = require('readline');

var HOST = '127.0.0.1';
var PORT = 6969;

const r1 = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var client = new net.Socket();
client.connect(PORT, HOST, function() {
  console.log('CONNECTED TO: ' + HOST + ':' + PORT);

  // continue talkback
  function waitForUserInput() {
    r1.question("Enter some data you wish to send: ", function(data) {
      if(data == "exit") {
        r1.close();
      } else {
        // write input data to the server
        client.write(data);
        // receive what data server sends back to client
        client.on('data', function(server_data) {
          console.log('DATA: ' + server_data);
        });
        setInterval(waitForUserInput, 1000);
      }
    });
  }

  waitForUserInput();

});

A: You keep adding more and more client.on('data', ...) handlers.  Each time you call waitForUserInput(), you end up adding another duplicate handler for the data message.  So, after calling waitForUserInput() twice, you have two identical handlers for the data message so when a new piece of data arrives, each of the two handlers gets called and the output in your console appears twice.  One one piece of data arrives, but you have duplicate handlers that are listening for it.
You can either use .once() instead of .one() or you can move the handler listening for the incoming data outside of the function so it's just installed once and only once.
Incidentally, using setInterval() here is also a problem for several reasons.  You're creating a new interval timer every time you call waitForUserInput() and there's no coordination between that and when the question is actually answered.


text:
Q: Expected return value of a recursive probabilistic function In this question asked on Stackoverflow, the asker gives a Java function similar to this:
public int f(){
    if(Math.random() >= 0.5){
        return 1;
    }
    else{
        return 1 + Math.max(f(), f());
    }
}

In math-speak, that would be written something like this:
$$f = \left\{
    \begin{array}{ll}
        50\%\ chance : & 1 \\
        50\%\ chance : & 1 + max(f, f)
    \end{array}
\right.$$
So basically, $f()$ is a probabilistic function that calls itself twice with 50% probability, and returns the maximum depth of its calls.

If you draw the call-tree and label the first case "tails" and the second case "heads," you can see that the question "What is the probability that this function eventually returns" is the same as the question "What is the probability of eventually getting more heads than tails.".  Thus, this function terminates with probability 1. This also allows you to calculate the expected number of total times that $f()$ is called.

However, the one question I haven't been able to answer is, what is the expected return value of $f()$?
My first thought was that the expected value $E_f$ should be
$$E_f = 0.5 * 1 + 0.5 * (1 + max(E_f, E_f))$$
However, that is clearly wrong; that would mean that, no matter how many calls $f()$ makes to itself in the second case, $E_f = 2$ !
So, does anyone know how to calculate the expected return value of $f()$?

A: The result of the procedure is a random positive integer $X$ such that
$$
X=1+B\cdot\max(X_1,X_2),
$$
where $X_1$ and $X_2$ are two independent copies of $X$ and $B$ is a Bernoulli random variable with $P[B=1]=P[B=0]=\frac12$.
To describe the distribution of $X$, let $R_n=P[X\geqslant n]$ for every positive integer $n$. The stochastic identity above translates into
$$
P[X\geqslant n+1]=P[B=1]\cdot P[X_1\geqslant n\ \text{or}\ X_2\geqslant n],
$$
that is,
$$
R_{n+1}=R_n-\tfrac12R_n^2.
$$
Since $R_1=1$, this recursion characterizes the distribution of $X$.
Unfortunately, iterating quadratic functions is notoriously difficult. Fortunately, estimating $R_n$ is rather straightforward, leading to $R_n\sim\frac2n$. Thus, the "expected return value" $E[X]=\sum\limits_{n\geqslant1}R_n$ is infinite while the return value $X$ is almost surely finite.


text:
Q: Stop PyCharm If Error In PyCharm debugging mode, is there way to let it stop right after it hits an error but not exit and highlight the offending line? The analogous feature I have in mind is "dbstop if error" of Matlab.

A: Yes, there is. Under Run, if you hit View Breakpoints (Ctrl + Shift + F8 on Windows) there's a checkbox where you can create an exception breakpoint for any exception.

A: The given answer was confusing to me. To do this you do not need to go to preferences, what you need to go is to break points menu bar (which is not in preferences for some reason). So:

*

*Go to break point by pressing Command + shift + fn + F8 (Ctrl + Shift + F8 on Windows) or go to the breakpoints you have at the bottom (see picture 1). This opens the break point menu (see picture 2).

*Then click enabled (for me suspend was already on so I only needed to click enabled). That's it.
Pic 1:

Pic 2:

Note: the reason this feature is useful is because after running an execution it halts with exactly the program state it caused it to err. For me I have stochastic code due to machine learning and reproducing the error exactly is annoying. I'd rather just see what cased the error, inspect the program state, stack etc and just fix it. There is even a little window at the bottom right to run code so I can test it right there while I am fixing it. I can even do control+shift+E to test pieces of code from my actual code (as I right new code).


text:
Q: Slow WIFI on iPhone 3GS after update to iOS6 After updating my iPhone 3GS to iOS6, when I'm on WIFI the network connection appears terribly slow. Loading a webpage in Safari takes ages and opening the update tab in the App store seems to keep loading forever. When I turn off WIFI and try the same on a 3G network, it all is responding a lot faster.
I've checked the WIFI connection itself, and from my laptop that appears all fine. Before the update to iOS6, my iPhone was working fine on that same WIFI connection. What can I do?

A: Reset your network settings, to clear all remembered WIFI networks. This will force it to create a new ones. You will have manually connect to the WIFI network again, and if required enter its password again afterwards.
You can reset the network settings by selecting:
Settings -> General -> Reset -> Reset Network Settings
Also what can help is trying to clear the history of your Safari browser, you can do that by going to the Bookmarks -> History and then press the Clear button on the lower left hand corner of the screen.


text: Q: Airflow : I want to make a scheduler of my own. How to proceed? Airflow : I want to make a scheduler of my own, basically instead of using airflow/3rd party schedulers, i want to understand how to make my own scheduler similar to airflow on large scale. What things should i learn? any learning recommedation?


text:
Q: Removing text inside the bracket from specific rows in dataframe So this is my sample dataframe
dput(aa)
structure(list(V4 = structure(1:22, .Label = c("Peak228404",
"Peak228411", "Peak228413", "Peak228423", "Peak228424", "Peak228439",
"Peak228461", "Peak228476", "Peak228479", "Peak228495", "Peak228528",
"Peak228553", "Peak228603", "Peak228612", "Peak228629", "Peak228630",
"Peak228642", "Peak228651", "Peak228691", "Peak228740", "Peak4983",
"Peak5261"), class = "factor"), annotation = structure(c(1L,
4L, 5L, 1L, 1L, 1L, 6L, 8L, 1L, 1L, 1L, 1L, 1L, 1L, 8L, 8L, 8L,
8L, 7L, 8L, 2L, 3L), .Label = c("Distal Intergenic", "Downstream (1-2kb)",
"Downstream (2-3kb)", "Exon (ENST00000370460.6/2334, exon 16 of 21)",
"Exon (ENST00000370460.6/2334, exon 21 of 21)", "Exon (ENST00000616857.4/84548, exon 3 of 3)",
"Exon (ENST00000620118.4/ENST00000620118.4, exon 3 of 4)", "Promoter"
), class = "factor"), Output_required = structure(c(1L, 5L, 5L,
1L, 1L, 1L, 5L, 6L, 1L, 1L, 1L, 1L, 1L, 1L, 6L, 6L, 6L, 6L, 4L,
6L, 2L, 3L), .Label = c("Distal Intergenic", "Downstream (1-2kb)",
"Downstream (2-3kb)", "Exon", "Exon ", "Promoter"), class = "factor")), class = "data.frame", row.names = c(NA,
-22L))

This
 V4                                              annotation    Output_required
1  Peak228404                                       Distal Intergenic  Distal Intergenic
2  Peak228411            Exon (ENST00000370460.6/2334, exon 16 of 21)              Exon
3  Peak228413            Exon (ENST00000370460.6/2334, exon 21 of 21)              Exon
4  Peak228423                                       Distal Intergenic  Distal Intergenic
5  Peak228424                                       Distal Intergenic  Distal Intergenic
6  Peak228439                                       Distal Intergenic  Distal Intergenic
7  Peak228461             Exon (ENST00000616857.4/84548, exon 3 of 3)              Exon
8  Peak228476                                                Promoter           Promoter
9  Peak228479                                       Distal Intergenic  Distal Intergenic
10 Peak228495                                       Distal Intergenic  Distal Intergenic
11 Peak228528                                       Distal Intergenic  Distal Intergenic
12 Peak228553                                       Distal Intergenic  Distal Intergenic
13 Peak228603                                       Distal Intergenic  Distal Intergenic
14 Peak228612                                       Distal Intergenic  Distal Intergenic
15 Peak228629                                                Promoter           Promoter
16 Peak228630                                                Promoter           Promoter
17 Peak228642                                                Promoter           Promoter
18 Peak228651                                                Promoter           Promoter
19 Peak228691 Exon (ENST00000620118.4/ENST00000620118.4, exon 3 of 4)               Exon
20 Peak228740                                                Promoter           Promoter
21   Peak4983                                      Downstream (1-2kb) Downstream (1-2kb)
22   Peak5261                                      Downstream (2-3kb) Downstream (2-3kb)

So in this data-frame the column called annotation there are row which contains the string Exon so each there is text inside the bracket which i don't want as i want to keep it consistent which is Exononly. I have added another column  Output_requiredwhich is my desired final output.
Any suggestion or help would be really appreciated.

A: Remove everything after 'Exon' can be written with the help of lookbehind regex.
sub('(?<=Exon).*', '', aa$annotation, perl = TRUE)

# [1] "Distal Intergenic"  "Exon"               "Exon"               "Distal Intergenic"
# [5] "Distal Intergenic"  "Distal Intergenic"  "Exon"               "Promoter"
# [9] "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"
#[13] "Distal Intergenic"  "Distal Intergenic"  "Promoter"           "Promoter"
#[17] "Promoter"           "Promoter"           "Exon"               "Promoter"
#[21] "Downstream (1-2kb)" "Downstream (2-3kb)"

Similarly, stringr::str_remove can be used as well.
stringr::str_remove(aa$annotation, '(?<=Exon).*')

A: Another way to achieve your goal is by using backreference:
sub("(Exon)(.*)", "\\1", aa$annotation)

Here we partition the strings into two capturing groups:

*

*(Exon): this group literally captures Exon

*(.*): this group captures everything else

*\\1: ths backreference, used in the replacement argument to sub, "recollects" the first capture group - but not the second, thereby effectively removing it!

A: We may use trimws from base R
trimws(aa$annotation, whitespace = "(?<=Exon).*")
[1] "Distal Intergenic"  "Exon"               "Exon"               "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"  "Exon"
 [8] "Promoter"           "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"  "Distal Intergenic"
[15] "Promoter"           "Promoter"           "Promoter"           "Promoter"           "Exon"               "Promoter"           "Downstream (1-2kb)"
[22] "Downstream (2-3kb)"


text:
Q: Php update database column using radio button id Trying to make a simple database and form to collect data. I am trying to increment the value in the tables column but dont know how to tell the sql to update the column based off of the id value from the radio buttons. Any help would be great.
id | male | female
1  |   5  |    3
form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<fieldset>
<legend>Gender</legend>

<input type="radio" name="gender" id="male" value="1" />Male

<input type="radio" name="gender" id="female" value="1" />Female

</fieldset>
<fieldset>

Submit the form
<input type="submit" name="submit" id="submit" value="Send your Input" />

</form>

Php database update:
$query = "UPDATE table SET x = x + 1 WHERE id = '1'";
$q = mysql_query($query);

From looking around ive been trying to use something like this but cant seem to get the checked radio value to be pulled in. Think I am missing something from the form to tell what radio button has been checked and to post that on submit.
$selected_radio = $_GET['id'];
$query = "UPDATE table SET $selected_radio = $selected_radio + 1 WHERE id = '1'";
$q = mysql_query($query);

A: You will have to get $selected_radio by $_POST and not $_GET... BTW inside $_POST['gender'], after submit, your PHP script should receive the value defined in "value" attribute from input radio so.. change the values:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<fieldset>
<legend>Gender</legend>

<input type="radio" name="gender" id="male" value="5" />Male

<input type="radio" name="gender" id="female" value="3" />Female

</fieldset>
<fieldset>

Submit the form
<input type="submit" name="submit" id="submit" value="Send your Input" />

</form>

/*Then, you could increment your x column where the row id = 5 (male) or 3 (female)*/

$selected_radio = $_POST['gender'];
$query = "UPDATE table SET x = x + 1 WHERE id = '" .  $selected_radio . "'";
$q = mysql_query($query);

A: you should make your radio button like this:
<input type="radio" name="gender" id="gender" value="female" />
<input type="radio" name="gender" id="gender" value="male" />

$selected_radio = isset($_POST['gender']);
$query = "UPDATE table SET $selected_radio = $selected_radio + 1 WHERE id = '1'";
$q = mysql_query($query);


text:
Q: Intermitent error in API Gateway import time we are trying to create an API Gateway from the import button in the AWS console.
The user policy is as follows:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "apigateway:GET"
            ],
            "Resource": [
                "arn:aws:apigateway:*::/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "apigateway:PUT"
            ],
            "Resource": [
                "arn:aws:apigateway:*::/restapis/`our-api-id`/*"
            ]
        }
    ]
}

As we import the swagger file from the console, it prompts the following error randomly:
User: arn:aws:iam::`account-id`:user/`user-id` is not authorized to perform: apigateway:PUT on resource: arn:aws:apigateway:eu-west-1::/restapis/`our-api-id`

We don't know why sometimes the same actions works and sometimes does not.
Any idea?

A: Permissions errors should not be intermittent. However the resource for the PUT action (specifically for put-rest-api operation) should be
        {
            "Effect": "Allow",
            "Action": [
                "apigateway:PUT"
            ],
            "Resource": [
                "arn:aws:apigateway:*::/restapis/`our-api-id`"
            ]
        }


text:
Q: Is it possible for moderators to earn the Reviewer badge? I hit the 1000 reviews mark several days ago and still don't have the Reviewer badge.
(I saw that two of the new mods already have the badge, but they earned it before being elected.)

A: Yes, Moderators can earn the Reviewer badge.
I have it over on Web Apps where I have been a moderator since Feb 2011.
A post becomes "reviewed" if you click "review post" or the hyperlink from the /review page. You can act on it anywhere after that.


text:
Q: ListToArray for submitted form I have a web form with multiple elements with the same name for example:
<textarea name="instructions"><cfoutput>#struct.instructions# </cfoutput> </textarea>

Form is built in html/coldfusion/js and the database to store the data is MS Access.
In the script that I am using to process form submission I am using ListToArray method to get all fields with a given name.
<cfset arrayInstr = ListToArray(Form.instructions)>

Ok and here is the problem. If the submitted text contains comas ListToArray will interpret it as multiple elements.
For example if I try to submit a string "Bla bla bla bla" everything will be fine, but if string will be "bla, bla, bla" only "bla" will be submitted to database.
Is there other way to process multiple fields with the same name?
I would like to avoid giving unique names.
thank you,
Janusz

A: If you give the form field names like instructions1, instructions2, instructions3, it is easy to perform whatever logic you need in a loop.
for( var i = 1; i <=3; i++ ){
    var theValue = form["instructions" & i];

    //do whatever you need to do with theValue//
}

I think that is much easier to deal with than using JavaScript to add delimters to the form fields.

A: Q: Is there other way to process multiple fields with the same name?
A: Not directly
Javascript sees the items as a array. What you would need to do is have Javascript loop through all the values and create a string with a different delimiter and put that into a hidden field. The distinction between different <textarea>'s and commas would be maintained.

A: You can create an array of the individual form fields by using the getHTTPRequestData function.
<cfset Variables.RequestData = getHTTPRequestData()>
<cfset Variables.RequestContent = Variables.RequestData.Content>

<cfset Variables.FormScope = []>
<cfloop index="Variables.CurrentItem" list="#Variables.RequestContent#" delimiters="&">
    <cfset ArrayAppend(Variables.FormScope, URLDecode(ListLast(Variables.CurrentItem, "=")))>
</cfloop>


text:
Q: Is it possible to mount a RAID 1 software/mdadm member raw? I am wondering if a software member can be mounted directly. Is the software raid this transparent? I think this would be a nice thing to know just in case the RAID management fails for some reason?
If this is the case, does this apply to hardware RAID 1 systems?

A: For mdadm RAID 1, it's possible. However, doing so (bypassing the RAID layer in any way) would put the drives out of sync, which in turn will cause corruption. So it's best to mount read-only.
Determine the data offset:
# mdadm --examine /dev/sda2
[...]
     Raid Level : raid1
[...]
    Data Offset : 2048 sectors
[...]

In this case it's 2048 sectors.
Create a (preferably read-only) loop device with that offset:
# losetup --find --show --offset=$((2048*512)) /dev/sda2
/dev/loop3

Mount it:
# mount -o ro /dev/loop3 /mnt/somewhere

The loop device creation and mount can also be expressed in one command:
# mount -o ro,loop,offset=$((2048*512)) /dev/sda2 /mnt/somewhere

One of the downsides of read-only mounting is that the mount might fail if the filesystem is in an unclean state, and can't be repaired due to read-onlyness. In this case it's possible to put a copy-on-write overlay on top of the loop device.
Please note, if you don't do this strictly read-only, and bypass the RAID layer, the RAID is no longer in sync and corruption issues will follow if you don't force the RAID to resync/repair itself afterwards.

For hardware and other types of RAID, it depends on the format. A lot of RAID have metadata at the end, so you can do the same steps with offset 0. Otherwise you have to determine the data offset somehow.
If there is no filesystem on the RAID (cryptsetup, LVM, ...) you have to open those layers before the mount step. If the RAID device is partitioned, loop devices support partitions (losetup --partscan then e.g. /dev/loop3p1).


text:
Q: Height of the Inner Content doesn't get changed when changing the container height I want the 3rd element to take the place of the element second when clicked on the button, I know I can use .remove() to remove that specific block of code, but it will not gonna transition, so I want the third element to take place of the second with transition instead of direct getting there. How can I do that? I try to do the example but changing the height of the 2nd container, but the inner Content didn't change and it also didn't transition even though I have set the transition on the height

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    const all = document.querySelectorAll('.cont');
  all[1].classList.add('changeheight');
})
.changeheight {
  height: 0px;
  transition: height 250ms ease;
}

Hello 1

Hello 2

Hello 3

Hello 4

<button id="btn">
  Click
</button>

A:

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
  const all = document.querySelectorAll('.cont');
  all[1].classList.add('changeheight');
})
* {
  margin: 0;
  padding: 0;
}

.cont {
  height: 50px;
}

.changeheight {
  height: 0px;
  transition: height 350ms ease;
}

Hello 1

Hello 2

Hello 3

Hello 4

<button id="btn">
        Click
    </button>

A: Add overflow: hidden to changeHeight class and take some idea from @CyrusKabir answer

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    const all = document.querySelectorAll('.cont');
  all[1].classList.add('changeheight');
})
* {
  margin: 0;
  padding: 0;
}

.cont {
  height: 50px;
}

.changeheight {
  height: 0px;
  transition: height 550ms ease;
  overflow: hidden;
}

Hello 1

Hello 2

Hello 3

Hello 4

<button id="btn">
        Click
    </button>


text:
Q: How does ls [[:punct:]]* work? I am learning bash. Currently, I have a file called _something.txt and when I use:
ls [[:punct:]]*

I get the following error:
ls: invalid option -- 'V'

What am I doing wrong?

A: Since you have a name in your current directory that starts with a dash (-), this name is mistaken for an option to ls.
Use -- to delimit the actual options from the operands when you call ls to avoid this:
ls -- [[:punct:]]*

The double dash (--) ends the options list.

A: You have a file whose name starts with a dash (-).
Try ls -d ./-* to see it


text:
Q: Induction on summation inequality stuck on Induction step working on a fairly simple induction problem, but stuck when decomposing the m+1^st summation and bringing in the I.H to show it holds.
I am bad with formatting so bare with me.
$$\sum_{k=1}^n \frac1{k^2} \leq 2 - \frac1n$$
Base Case:
Set $n = 1$ and show that the inequality holds
IH:
Assume for all $n = m$, $\sum_{k=1}^m \frac1{k^2} \leq 2 - \frac1m$  holds
I.S:
$$\sum_{k=1}^{m+1} \frac1{k^2} \leq 2 - \frac1{m+1}$$
since we can decompose m+1 to m we get
$$\sum_{k=1}^m \frac1{k^2} + \frac1{m^2} \le 2 - \frac1m$$
then we can use I.H since we have $\sum_{k=1}^m \frac1{k^2} \le 2 - \frac1{m+1}$
so I am trying to show $2 - 1/(m+1) + 1/(m^2)$, but I am stuck here since I cannot manipulate the equation to come to the m+1st equation on the RHS

A: For the inductive step you have:
$$\sum_{n=1}^{m+1} \frac{1}{k^2} = \sum_{n=1}^{m} \frac{1}{k^2} + \frac{1}{(m+1)^2} \le 2 - \frac{1}{m} + \frac{1}{(m+1)^2}  \le 2 - \frac{1}{m+1}$$
The last inequality is true as:
$$\frac{1}{m} - \frac{1}{(m+1)^2} \ge \frac{1}{m+1} \iff (m+1)^2 - m \ge m(m+1) \iff m^2 + m + 1 \ge m^2 + m$$

A: i think it must be
$$\sum_{k=1}^m\frac{1}{k^2}+\frac{1}{(m+1)^2}\le 2-\frac{1}{m+1}$$ and it must be
$$\le 2-\frac{1}{m}+ \frac{1}{(m+1)^2}\le 2-\frac{1}{m+1}$$


text:
Q: Images go away after minerals = 0 In my program you can place pictures on the applet if you have the required minerals
you start with 400 and each one is 100 minerals so you place 3 and then on the 4th it will delete all the others
public int Minerals

    //Pylons
    int xCoord[];
    int yCoord[];
    int numSquare;
    boolean firstPaint;

public void init()
    {

        Minerals = 400;

        pylon = getImage(getDocumentBase(),"image/pylon.png");
    //pylons
        xCoord = new int[100];
        yCoord = new int[100];
        numSquare = 0;
        firstPaint = true;
}

public void paint(Grapics g)
{

            pylons(g);
}

    public void pylons(Graphics g)
    {
        //Building the pylons
        if(Minerals >= 100)
        {

            for (int k = 0; k < numSquare; k++)
            {
                    g.drawImage(pylon,xCoord[k],yCoord[k],85,85,this);
                    //Makes cursor normal.
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            }

        }

        //Checks if buildPylon is 1 if so it will draw the infoScreen and then set the cursor to pylon
        if(buildPylon == 1)
        {
            g.drawImage(pylon,510,820,100,100,this);
            //Use the custom cursor
            setCursor(cursor);
        }
    }

    private void handlePylonPlacement()
    {
        //This takes away 100 minerals and will add 9 population and make buildPylon 0 again
        if(decrementMinerals(100))
            addPopMax(9);
            buildPylon = 0;

    }

    private boolean decrementMinerals(int amount)
    {
        //This Is where it takes away the minerals
        if(Minerals - amount >= 0) // prevent situation where you go into negative minerals
        {
             Minerals -= amount;
             return true;
        }
        else
             return false;
    }

    private void addPopMax(int amount)
    {
        //Add the population (9)
        if(popMax + amount <= 72) // restrict addition to pop-max to a sane upper bound
             popMax += amount;
    }

public boolean mouseDown(Event e, int x, int y) {
        //Makes the ints xCoord2 to equal x and same for the other
        xCoord2 = x;
        yCoord2 = y;
        repaint();

        if (numClicks == 10) {//Title screen
            numClicks++;
            repaint();
        }

    //Checks to see if buildPylon == 1 then builds the pylon if its in the correct place.

    if(buildPylon == 1)
    {
        if(x > 1 && x < 1275 && y > 711 && y < 948) // Checks to see if the person clicked in this area
        {}
        else if(x > 378 && x < 876 && y < 568 && y < 705) // Checks to see if the person clicked in this area
            {}else if (Minerals >= 100)
            {
            xCoord[numSquare] = x;
            yCoord[numSquare] = y;
            numSquare++;
            handlePylonPlacement(); // call your new handler
            repaint();
             }
        }

        return true;
    }

Instead of it deleting them i want the pylons to stay painted on the screen... any help?

A: In handlePylonPlacement(), did you mean
    private void handlePylonPlacement()
    {
        //This takes away 100 minerals and will add 9 population and make buildPylon 0 again
        if (decrementMinerals(100)) {
            addPopMax(9);
            buildPylon = 0;
        }
    }

?


text:
Q: why does my jQuery auto-refresh stop working if I add in a if statement? window.onload = setupRefresh;
function setupRefresh() {
    setInterval("refreshBlock();", 1000);
}

function refreshBlock() {

    $('#activeItems').load("current_auctions.php");

}

the above code automatically refreshes the content of a div tag on my page every 1 second.
window.onload = setupRefresh;
function setupRefresh() {
    setInterval("refreshBlock();", 1000);
}

function refreshBlock() {
    if ($('#myAccount').html() == 'My Accout') {
        $('#activeItems').load("current_auctions.php");
    };
}

The above code, which only has the addition of an if statement, loads up the page once in the beginning, and then ceases to refresh. How can I fix this code?

A: Probably because that conditional is returning false.
if ($('#myAccount').html() == 'My Accout') {

Quite likely because of the typo in 'Accout', as @nnnnn says.
You can debug this quite easily in Chrome or Firefox by using a script terminal. In Firefox you could install Firebug or in Chrome just press Crtl+Shift+J. Either way get to a JavaScript command-line interface and enter:
$('#myAccount').html() == 'My Accout'

In  your page. You'll see it return either true or false. If it's false you can then easily tweak that condition until it's true where you're expecting.


text:
Q: Can't resolve all parameters for MyComponent I was developing in Angular and I've found a weird issue:

Uncaught Error: Can't resolve all parameters for MyComponent: ([object
  Object], ?, ?, [object Object], [object Object], [object Object]).

Worth to say that the dependencies which appear as "?" are only the services made by me, the others are Angular objects or third-parties, and it happens in my entire all project only happening in my own dependencies.
I've already read almost everything that I've found in google, I already reviewed the known issues about circular dependencies and barrel imports.
Other things you should know are:

*

*The dependencies which don't works are hosted in their own project and published in my local/own/private npm repository.

*I'd publish those dependencies through gulp using npc.

*I'm not using aot.

*@angular/cli: "1.7.4"

*@angular: "^5.2.6"
I really suspect about metadata, but I don't find anything inside node_modules/myDependency/ which gives me a clue about corrupted or missing metadata.

A:
Uncaught Error: Can't resolve all parameters for MyComponent: ([object Object], ?, ?, [object Object], [object Object], [object Object]).

The services defined by the ? must be added to the providers section of the NgModule that provide those services.


text:
Q: For loop and lapply First, I used a for loop for a vector of numbers, it worked well.
When I used lapply fucntion, the results was not I want. I only want one element within a list.
This is my example
# With for loop, the outcome is one vector of numbers
x <- c(0.2,0.5,0.03,0.006,0.08)
p.value <- NULL
for (i in 1:length(x)){
if(x[i] > 0.5 p.value[i] <- (1-x[i])*2
else p.value[i] <- x[i]*2

# with lapply
lapply(x, function(x) {if(x > 0.5) p.value <- (1-x)*2 else p.value <- x*2

The outcome from lapply is the combination of same results. I kinda realizing the problem, but I dont know how to change my code. Any suggestions for this?

A: This can be solved in a vectorized way so you don't need a for loop or lapply.
p.value <- ifelse(x > 0.5, (1 - x), x) * 2

The lapply code does give me the expected output as for loop but you can change few things.

*

*Use sapply since the output is a vector

*assign p.value outside sapply and not inside the function.

*Since you already have a vector named x, change the variable in anonymous function to another name.

p.value <- sapply(x, function(y) if(y > 0.5) (1-y)*2 else y*2)

A: You may use replace which is faster than ifelse.
replace(x, x > .5, 1 - x)*2
# [1] 0.400 1.000 0.060 0.012 0.160

Benchmark
x <- sample(x, 1e6, replace=T)
microbenchmark::microbenchmark(ifelse=ifelse(x > 0.5, (1 - x), x) * 2,
                               replace=replace(x, x > .5, 1 - x)*2)
# Unit: milliseconds
#    expr       min       lq     mean   median       uq      max neval cld
#  ifelse 25.049546 31.29303 39.53500 36.23981 42.06574 124.9903   100   b
# replace  8.074329 11.06676 18.68296 14.02976 16.99336 100.2051   100  a

A: try sapply instead of lapply. that simplify list solution


text:
Q: Custom styling an input slider using styled-components I am trying to style a slider that I am creating using styled components. It should be a different color and should have an image for the thumb piece, but it is still the default blue, and the default thumb piece. I'm using bootstrap, so this slider styling must be the default for bootstrap.
Other solutions which I've implemented in the code below aren't working. All I'm trying to do is to change the colour to something like yellow, and place an image overtop of the thumb piece.

import React from 'react';

import styled from 'styled-components';
import colors from 'styles/json/colors.json';

const image = './myImage.png';
const thumb = {
    width: 54,
    height: 26
}

const StyledSlider = styled.input`

    height: 5px;
    background-color: ${colors.colorScheme.secondary};
    outline: none;
    transition: opacity .2s;

    &::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: ${thumb.width}px;
        height: ${thumb.height}px;
        border: 0;
        background: url(${image});
        cursor: pointer;
        border-radius: 2px;
        background-size: 100%;
        background-position: center center;
        background-repeat: no-repeat;
        outline: none;
    }

    &::-moz-range-thumb {
        width: ${thumb.width}px;
        height: ${thumb.height}px;
        border: 0;
        background: url(${image});
        cursor: pointer;
        outline: none;
        border-radius: 2px;
        background-size: 100%;
        background-position: center center;
        background-repeat: no-repeat;
    }

`

export default (props) => (
    <StyledSlider type="range" {...props} />
)

Update
Here's a code sandbox of a tempermental solution. In my actual code the shadow doesn't line up perfectly with the line if I start messing with the margin. Also I can't figure out how to get this rounded.

A: This might help you

the code was written by @rblakejohnson but I did some changes

import React from 'react';

import styled from 'styled-components';
import colors from 'styles/json/colors.json';

const image = './myImage.png';
const thumb = {
    width: 54,
    height: 26
}

const height = "36px";
const thumbHeight = 36;
const trackHeight = "16px";

// colours
const upperColor = "red";
const lowerColor = "yellow";
const thumbColor = "orange";
const thumbHoverColor = "#ccc";
const upperBackground = `linear-gradient(to bottom, ${upperColor}, ${upperColor}) 100% 50% / 100% ${trackHeight} no-repeat transparent`;
const lowerBackground = `linear-gradient(to bottom, ${lowerColor}, ${lowerColor}) 100% 50% / 100% ${trackHeight} no-repeat transparent`;

// Webkit cannot style progress so we fake it with a long shadow on the thumb element
const makeLongShadow = (color, size) => {
  let i = 18;
  let shadow = `${i}px 0 0 ${size} ${color}`;

  for (; i < 706; i++) {
    shadow = `${shadow}, ${i}px 0 0 ${size} ${color}`;
  }

  return shadow;
};

const StyledSlider = styled.input`
  overflow: hidden;
  display: block;
  appearance: none;
  max-width: 700px;
  width: 100%;
  margin: 0;
  height: ${height};
  cursor: pointer;

  &:focus {
    outline: none;
  }

  &::-webkit-slider-runnable-track {
    width: 100%;
    height: ${height};
    background: ${lowerBackground};
  }

  &::-webkit-slider-thumb {
    position: relative;
    appearance: none;
    height: ${thumbHeight}px;
    width: ${thumbHeight}px;
    background: url(${image});
    background-size: cover;
    border-radius: 100%;
    border: 0;
    top: 50%;
    transform: translateY(-50%);
    box-shadow: ${makeLongShadow(upperColor, "-10px")};
    transition: background-color 150ms;
  }

  &::-moz-range-track,
  &::-moz-range-progress {
    width: 100%;
    height: ${height};
    background: ${upperBackground};
  }

  &::-moz-range-progress {
    background: ${lowerBackground};
  }

  &::-moz-range-thumb {
    appearance: none;
    margin: 0;
    height: ${thumbHeight};
    width: ${thumbHeight};
    background: ${thumbColor};
    border-radius: 100%;
    border: 0;
    transition: background-color 150ms;
  }

  &::-ms-track {
    width: 100%;
    height: ${height};
    border: 0;
    /* color needed to hide track marks */
    color: transparent;
    background: transparent;
  }

  &::-ms-fill-lower {
    background: ${lowerBackground};
  }

  &::-ms-fill-upper {
    background: ${upperBackground};
  }

  &::-ms-thumb {
    appearance: none;
    height: ${thumbHeight};
    width: ${thumbHeight};
    background: ${thumbColor};
    border-radius: 100%;
    border: 0;
    transition: background-color 150ms;
    /* IE Edge thinks it can support -webkit prefixes */
    top: 0;
    margin: 0;
    box-shadow: none;
  }

  &:hover,
  &:focus {
    &::-webkit-slider-thumb {
      background-color: ${thumbHoverColor};
    }
    &::-moz-range-thumb {
      background-color: ${thumbHoverColor};
    }
    &::-ms-thumb {
      background-color: ${thumbHoverColor};
    }
  }
`;

export default (props) => (
    <StyledSlider type="range" {...props} />
)


text:
Q: Scheme for Posts and Comments I need to allow Comments to different entities such as Posts, Products, etc:

*

*One Post / Product / ... can have many comments;

*One Comment can only be associated to a Post / Comment / ...

I though of different schemes and I came up with the following schemes and tables:
1. Each entity has its own Comment table:
    Posts (PostId), PostsComments (CommentId, PostId, CommentText)
    Products (ProductId), ProductComents (CommentId, ProductId, CommentText)

It has the disadvantage of needing more tables if more entities need comments.
2. One comment table for all entities (Many to Many):
    Posts (PostId), PostsComments (CommentId, PostId)
    Products (ProductId), ProductComents (CommentId, ProductId)
    Comments (CommentId, CommentText)

It has the disadvantage of needing more tables if more entities need comments. Besides the Many to Many relationship ...
3. One Forum table that aggregates comments:
   Posts (PostId, ForumId)
   Products (ProductId, ForumId)
   Forums (ForumId)
   Comments (CommentId, ForumId, CommentText)

In the future if I need another entity with comments I just add a ForumId FK to it.
What do you think about each approach? Do you have a better one?

A: how about this one:
comments table will have info about post or product and may be both.
Comments (CommentId, PostId, ProductId, CommentText)