text:
Q: Spring Integration - @InboundChannelAdapter polling I am new to Spring Integration. We are creating our application using Spring Integration Annotations.
I have configured an @InboundChannelAdapter with poller fixed delay of 5 seconds. But the problem is as soon as I start my application on weblogic, the adapter starts polling and hits endpoint with practically no message.
We need to call a rest service and then trigger this adapter.
Is there a way to implement the same?
TIA!

A: Set the autoStartup property to false and use a control bus to start/stop it.
@SpringBootApplication
@IntegrationComponentScan
public class So59469573Application {

    public static void main(String[] args) {
        SpringApplication.run(So59469573Application.class, args);
    }

}

@Component
class Integration {

    @Autowired
    private ApplicationContext context;

    @InboundChannelAdapter(channel = "channel", autoStartup = "false",
            poller = @Poller(fixedDelay = "5000"))
    public String foo() {
        return "foo";
    }

    @ServiceActivator(inputChannel = "channel")
    public void handle(String in) {
        System.out.println(in);
    }

    @ServiceActivator(inputChannel = "controlChannel")
    @Bean
    public ExpressionControlBusFactoryBean controlBus() {
        return new ExpressionControlBusFactoryBean();
    }

}

@MessagingGateway(defaultRequestChannel = "controlChannel")
interface Control {

    void send(String control);
}

@RestController
class Rest {

    @Autowired
    Control control;

    @PostMapping("/foo/{command}")
    public void trigger(@PathVariable String command) {
        if ("start".equals(command)) {
            control.send("@'integration.foo.inboundChannelAdapter'.start()");
        }
    }

}


text:
Q: Can't get the public IP of a connected client on my server I have a very basic server written in Python as follows:
import socket
from time import sleep
import requests

c = None #Client socket1
addr = None #Client address1

server_socket1 = socket.socket() #by default it is SOCK_STREAM (TCP) and has porotocal AF_INET (IPv4)

server_socket1.bind(('127.0.0.1',9999)) #server machine's ip and port on which it will send and recieve connections from

server_socket1.listen(2) #We will only accept two connections as of now , one for each client
print("Server started successfully!!!")
print("Waiting for connections...\n\n")

while (((c is None)and(addr is None))):
    if((c is None) and (addr is None)):
        c,addr = server_socket1.accept()
        print("Intrusion detected at address 127.0.0.1:9999 ")
        print("Client connected with ip address "+str(addr))
        client_ip=str(addr)

while True:
    msg = c.recv(4096)
    if(msg!=None):
        #print(msg)
        headers, sep, body = msg.partition(b'\r\n\r\n')
        headers = headers.decode('utf-8')
        print(headers)

        html_body = "
You are not authorized to acces this Page!

3 more attemps and your ip will be jailed!
"
        response_headers = {
        'Content-Type': 'text/html; encoding=utf8',
        'Content-Length': len(html_body),
        'Connection': 'close',
        }

        response_headers_raw = ''.join('%s: %s\r\n' % (k, v) for k, v in response_headers.items())
        response_proto = 'HTTP/1.1'
        response_status = '200'
        response_status_text = 'OK' # this can be random

        # sending all this stuff
        r = '%s %s %s\r\n' % (response_proto, response_status, response_status_text)
        c.sendall(r.encode())
        c.sendall(response_headers_raw.encode())
        c.sendall(b'\r\n') # to separate headers from body
        c.send(html_body.encode(encoding="utf-8"))

I have then used ngrok to forward my port 9999 on the web. Then I execute the server.
Now, when I connect to the ngrok's provided link via my mobile phone, I get the response from my server, that is a single lined HTML content, as seen in the code itself.
But, the c,addr = socket.accept() should return the IP of the connected client. In my case, I have used my phone to connect to ngrok, which should use my phone's public IP to connect to it, still on my server side, it shows something like this:

Can someone please tell me what am I doing wrong here?

A: What you are seeing makes perfect sense, as the phone is not directly connected to your server (it can't be, since your server is listening on 127.0.0.1 aka localhost, so it can only accept connections that originate from the same machine).
The phone is connected to ngrok, and then ngrok is connected to your server. So you are seeing the IP that ngrok is connecting to your server from.  There is simply no way for your server to get the IP of the phone, unless ngrok includes the phone's IP in the HTTP request it sends to your server, such as in an X-Forwarded-For, X-Original-Forwarded-For, X-Real-IP, etc kind of request header, which are common for proxies to send (but which I don't see in your screenshot, but it is incomplete).
---------     ---------     ----------
| phone | <-> | ngrok | <-> | server |
---------     ---------     ----------
           ^             ^
           |             |
desired IP is here   but you are getting IP from here

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the equivalent data objects in Bash in comparison to R? R was the first programming language I learned. It is always a pleasure to learn a new language associated with the first language.
Here comes my question. What are the equivalent data objects in Bash for the following data objects in R
I have also given a short description of each data-objects
Vector -> single dimension | can take both characters, integer and other standard datatypes (logical, double, complex) | but only one data-type at a  time
Dataframe --> two-dimension | collection of vectors of equal length | can take both characters, integer and other standard datatypes | but only one data type in a vector
List --> collection of different data types which can even contain functions !!! | a list can contain many lists | list can contain mix up of datatypes.
Matrix --> data arranged in two-dimensional rectangular layout | main in elements of same types
Array --> multi-dimension storage | standard datatypes


text:
Q: Proof of the Euclidean Algorithm How is the euclidean algorithm infallible? An intuitive approach or sketch of the proof would be much appreciated

A: The proof shows that

*

*every step of the algorithm preserves the $\gcd$ of the two numbers.

*every step but the last reduces the numbers.
The proof concludes by observing that as the numbers cannot be reduced anymore, you have found the $\gcd$, and this occurs after a finite number of steps.

Technically:

*

*$\gcd(a,b)=\gcd(b,a\bmod b)$ because $a\bmod b$ and $a$ differ by a multiple of $b$.

*$b<a\implies a\bmod b<a$.
If $a=b$, then $\gcd(a,b)=a$.

Addendum:
It can be shown that the largest number of steps occurs when the input numbers are two successive Fibonacci numbers, so that the number of steps is bounded by $\log_\phi a$.


text:
Q: Resolving async function after a loop end I expect when I call an async function to resolve promise at the end, not before.
const urls = await uploadImages({ imageChanges, questions });
// ...next step
// I will use urls

But after calling await uploadImages() it continues to run until const data = await fetch(image.src);
And then ...next step starts. How can I make it wait for imageChanges.forEach loop finish ? Should I create another nested function inside ?
const uploadImages = async ({ imageChanges, questions }) => {
    if (!imageChanges.length) return null;

    const storage = firebase.storage();
    let urls;

    try {
        //** convert each new image's src from blob to downloadUrl. */
        imageChanges.forEach(async image => {
            const questionId = questions.findIndex(q => q.id === image.questionId);
            const imagePath = `${questionId}.jpg`;
            const storageRef = storage.ref(imagePath);

            // **
            const data = await fetch(image.src);
            const blob = await data.blob();

            const uploadTaskSnapshot = await storageRef.put(blob);
            const downloadURL = await uploadTaskSnapshot.ref.getDownloadURL();
            urls.push(downloadURL)
        });

        return urls;
    } catch (error) {
        console.log(error.message);
    }
};

A: forEach with async doesn't work as expected. Read this answer for more info.
Try like this
const uploadImages = async ({ imageChanges, questions }) => {
  if (!imageChanges.length) return null;

  const storage = firebase.storage();

  try {
    const imageChangesUrlPromise = imageChanges.map(async () => {
      const questionId = questions.findIndex(q => q.id === image.questionId);
      const imagePath = `${questionId}.jpg`;
      const storageRef = storage.ref(imagePath);
      const data = await fetch(image.src);
      const blob = await data.blob();
      const uploadTaskSnapshot = await storageRef.put(blob);
      const downloadURL = await uploadTaskSnapshot.ref.getDownloadURL();
      return downloadURL;
    })

    return await Promise.all(imageChangesUrlPromise);
  } catch (error) {
    console.log(error.message);
  }
};

and then
const urls = await uploadImages({ imageChanges, questions });
...

A: JavaScript does this because forEach is not promise-aware. It cannot support async and await. You cannot use await in forEach.
If you use await in a map, map will always return an array of promises. This is because asynchronous functions always return promises.
By littile modification to your code, this should work,
const uploadImages = async ({ imageChanges, questions }) => {
if (!imageChanges.length) return null;

const storage = firebase.storage();
let urls;

try {
    //** convert each new image's src from blob to downloadUrl. */
    await Promise.all(imageChanges.map(async image => {
        const questionId = questions.findIndex(q => q.id === image.questionId);
        const imagePath = `${questionId}.jpg`;
        const storageRef = storage.ref(imagePath);

        // **
        const data = await fetch(image.src);
        const blob = await data.blob();

        const uploadTaskSnapshot = await storageRef.put(blob);
        const downloadURL = await uploadTaskSnapshot.ref.getDownloadURL();
        urls.push(downloadURL)
    }));

    return urls;
 } catch (error) {
    console.log(error.message);
 }
};

const urls = await uploadImages({ imageChanges, questions });


text:
Q: How come my JSF code is getting a "java.lang.OutOfMemoryError: Java heap space"? I am getting a java.lang.OutOfMemoryError: Java heap space and I am not sure how to avoid it.   I am writing out to what I thought was basically a socket buffer.  I think it is javax.servlet.jsp.JspWriter.
However, when I attempt to write very large HTML file, ~700,000 lines, I get a java.lang.OutOfMemoryError: Java heap space.  I confused why the framework doesn't just flush to socket.  (Marsha, Marsha, Marsha)  Kidding aside, can I make it flush to socket rather just growing the buffer.
I am using JSF 1.1.
Note, I did try adding this web.xml:
<context-param>
    <param-name>facelets.BUFFER_SIZE</param-name>
    <param-value>500000</param-value>
</context-param>

It did not seem to change anything.
Here is my code sample:
<html>
    <f:view>
        <head>
            <title>Test</title>
        </head>
        <body id="page_body"
            <h:form id="form">
                <%
                    String s;
                    for (int i = 0; i < rowCount; i++) {
                        s = data.get(i);
                        out.println(s);
                        //flush after on every thousandths row.
                        //if(i%1000==1)
                        //         out.flush();
                    }  // for loop
                %>
            </h:form>
        </body>
    </f:view>
</html>

Here is the exception I get:
org.apache.jasper.JasperException: org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.OutOfMemoryError: Java heap space
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
    com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
    test.CustomLocaleRemapViewHandler.renderView(CustomLocaleRemapViewHandler.java:94)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
    com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
    test.CustomFilter.doFilter(CustomFilter.java:46)
    test.CustomFilter2.doFilter(CustomFilter2.java:81)
    org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)

root cause

org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.OutOfMemoryError: Java heap space
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:746)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:716)
    org.apache.jsp.test2_jsp._jspService(test2_jsp.java:122)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
    com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
    test.CustomLocaleRemapViewHandler.renderView(CustomLocaleRemapViewHandler.java:94)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
    com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
    test.CustomFilter.doFilter(CustomFilter.java:46)
    test.CustomFilter2.doFilter(CustomFilter2.java:81)
    org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)

root cause

javax.servlet.ServletException: java.lang.OutOfMemoryError: Java heap space
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:912)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:841)
    org.apache.jsp.test_jsp._jspService(test_jsp.java:745)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:746)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:716)
    org.apache.jsp.test2_jsp._jspService(test2_jsp.java:122)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:322)
    com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:130)
    test.CustomLocaleRemapViewHandler.renderView(CustomLocaleRemapViewHandler.java:94)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
    com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
    test.CustomFilter.doFilter(CustomFilter.java:46)
    test.CustomFilter2.doFilter(CustomFilter2.java:81)
    org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)

root cause

java.lang.OutOfMemoryError: Java heap space
    java.util.Arrays.copyOf(Unknown Source)
    java.io.ByteArrayOutputStream.grow(Unknown Source)
    java.io.ByteArrayOutputStream.ensureCapacity(Unknown Source)
    java.io.ByteArrayOutputStream.write(Unknown Source)
    sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
    sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
    sun.nio.cs.StreamEncoder.write(Unknown Source)
    java.io.OutputStreamWriter.write(Unknown Source)
    java.io.PrintWriter.write(Unknown Source)
    java.io.PrintWriter.write(Unknown Source)
    test.CustomWrapper$CustomPrintWriter.write(CustomWrapper.java:82)
    org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:119)
    org.apache.jasper.runtime.JspWriterImpl.write(JspWriterImpl.java:336)
    java.io.Writer.write(Unknown Source)
    com.sun.faces.renderkit.html_basic.HtmlResponseWriter.write(HtmlResponseWriter.java:519)
    com.sun.faces.taglib.jsf_core.ViewTag.doAfterBody(ViewTag.java:196)
    org.apache.jsp.test_jsp._jspService(test_jsp.java:725)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

BTW, BalusC, if your out there please help. No pressure, lol. You answer about half the JSF questions.
Grae

A: You can try using -Xmx to increase heap size.
For apache tomcat use i.e. export CATALINA_OPTS="-Xmx1024M"


text:
Q: Как защитить фотографии от скачивания? В моем проекте важно что бы фото были защищены и в идеале нельзя было их скачать. Какие способы защиты можно использовать?

A: Защитить изображения полностью не получится. Можете почитать про DRM, но даже это не защитит вас от копирования изображений.
Например, вы настроили DRM, сделали доступ к контенту возможным только с мобильных устройств. Скриншоты и скринкасты делать нельзя, и, казалось бы, все довольны. Однако найдётся пользователь, который запустит приложение на виртуальном устройстве и снимет данные с него, или рутует свой гаджет.
Про десктопные платформы или веб-платформы и говорить не стоит - тут у приложения куда меньше привилегий и способов ограничить возможности пользователя.
P.S. Кстати, недавно на Хабре была опубликована достаточно интересная статья. Можете почитать на досуге :)

A: Все довольно просто. Если ваше фото своровал неизвестно кто и смотрит на него у себя в бункере, заперев дверь, то и фиг с ним, аудитории у него нет, а значит, особо больших убытков от этого тоже нет.
Если же фото утянули журналисты и использовали в публикации, вы об этом узнаете, выполняя, например, поиск по вашим фото в Гугле, Тинае и Яндексе.
Теперь в дело вступают вотермарки, только не те вотермарки, которые огромная серая надпись поперек фотки, а настоящие, неразрушаемые обработкой цифровые вотермарки с ЭЦП и суды - юристы. Либо какой-то другой способ доказать приоритет, например, оригинальные RAW файлы.

A: Любую защиту можно обойти. Главное - сделать защиту довольно сложной, чтоб стоимость обхода была выше стоимости картинок.

*

*Весь код клиента должен быть обфусцированный, понятное дело.

*Клиент с сервером поднимает WebSocket соединение, обменивается с ним ключами по протоколу Диффи-Хеллмана

*Сервер отдает клиенту зашифрованые куски нарезаной картинки. Картинка нарезена на кучу кусочков, как описано в статье на хабре.

*Картинки рендерятся не в тег img, а на несколько Canvasов. У всех абсолютное позиционирование, так же запутанная DOM-структура, которая раз в пару секунд меняется (может это лишнее).

*Можно прикрутить сюда captcha - чтоб было труднее парсить.

*Можно сделать сложный алгоритм дешифровки, чтоб на расшифровку нужно было несколько секунд.

*Добавить защиту от дебага - если открыт DevTools - скрипт прекращает работу и очищает картинки.

Но все равно любую защиту можно обойти, например, сделав скриншот. От скриншота защитит максимум ватермарка, и то не полностью.

Так же рекомендую немного уменьшить картинку, понизить JPEG-качество, чтоб не было выгодно брать вашку картинку.


text:
Q: What Qt widgets should be used for sprite animation viewer I'm looking to make a sprite animation editor. I have the loading of my custom animation file done but now need to get the actual ui started. I'm really just stuck on what widgets I would use to actually play my animation. I need to be able to go to certain frame, play, pause, loop, etc. Once I'm done with the viewing portion I plan on adding in the editing.
I've seen AnimatedSprite in qt docs but that seems to only allow playback of sprites in the same file. In my situation sprites can be from multiple image files and sometimes doesn't follow a grid like sprite cutter.

A: First of all, you should decide whether you want to use QML or Widgets. AnimatedSprite is QML related class. All widget-related classes starts with "Q" letter.
If you decide to use Qt Widgets, I would recommend to take a look at Qt Animation Framework in combination with Qt Graphics View Framework. Most likely it will not let you do everything you want out of box, but it should provide you with a rich set of useful tools.
If you need here are some examples.
Hope it helps.

A: Have a look at QMovie. This class may provide all the methods you need, as long as you only want to use it for viewing. The QMovie can be passed to a QLabel to show the animation.
QMovie however supports only gif out of the box (and there is a third party plugin for apng files). You would probably have to create your own image handle plugin to support your format.
If thats not applicable or to complicated, you will most likely have to create your own custom widget. Have a look at the painter example. Playing an animation is not that hard if you have all the frames. A simple  QTimer to change the image to be drawn in a constant rate should work.


text:
Q: How to Switch Between two Jquery Based Layouts (when using desktop and mobile) I want to create a responsive website.
If the browser is mobile sized, the content should be displayed with an iPhone Style List View
If the browser is desktop sized, the content should be displayed with tabs:

What is the best way of doing this?
I don't want to use separate files for Mobile/Desktop. I want it to be responsive.

Here is some of the research I have done.
Attempt 1: Pure CSS solution.
A pure CSS solution would be the best, as CSS offers media queries which makes it easy to switch between layouts. CSS offers methods for creating tabs. But it doesn't seem to offer a method for an iPhone style list. (You can almost fake it with an accordion list but this doesn't take the user to a separate page like on a true iPhone app).
Attempt 2: Jquery Solution (see Fiddle)

*

*Jquery Mobile offers an easy way to create iPhone style list
views

*Jquery UI offers an easy way to create tabs.

*Enquire.js offers a Javascript equivalent for media queries.

In this fiddle, I have tried to combine Jquery Mobile and Jquery Ui. Enquire.Js is used to call the necessary library depending on screen.
When a library is called, it will alter the dom structure. So the unneeded library has to be removed, otherwise if the user re-sizes the browser (i.e. switches between mobile desktop), the unused library will break cause conflicts for the called library.
In my fiddle, I have tried to do this, but it doesn't seem to work:
$(document).ready(function() {

        enquire.register("screen and (max-width: 600px)", function() {
    $('script[src~="jquery-ui.js"]').remove();
    $('link[rel=stylesheet][href~="jquery-ui.css"]').remove();
     $('head').append('<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />');
     $('head').append('<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"><\/script>');
        $("#tabs").tabs("destroy");
    }).listen();

       enquire.register("screen and (min-width: 601px)", function() {
    $('script[src~="jquery.mobile-1.0a3.min.js"]').remove();
    $('link[rel=stylesheet][href~="jquery.mobile-1.0a3.min.css"]').remove();
    $('head').append('<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />');
     $('head').append('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"><\/script>');
    $("#tabs").tabs();

    }).listen();

});

Even though the unused library is removed, it causes conflicts for the new library.
Also, you have to re-size the browser before any of the layouts are called. If the user doesn't re-size the browser, the content will be unstyled.
Attempt 3: Dom Cloning (see Fiddle)
This attempt is similar to attempt 2, except on page load it stores the DOM in a variable. Then when the user re-sizes the browser, the existing DOM is replaced with the stored DOM. I have followed the method outline here, but it doesn't seem to work. The dom is just removed instead of being replaced.
I would appreciate any helpful with this, as I have been tearing my hair out to find a solution! (I know I have asked a question similar to this, but I felt this new question was different enough to warrant a new post.)
Attempt 4: Dynamically Assigning Data Attributes
Jquery mobile uses data attributes in the mark up to make the scripts work. I have tried applying these dynamically, so they are only written to the document when the browser is at mobile size. However, when the browser is re-sized, the desktop tabs are still broken.

A: I dont think there is a need for reinventing the wheel here. Responsive Design has been around for quite a while and is already taken the web development by storm. That said, I would suggest you can use any of the no. of Responsive frame works works out there you like. My personal favorite and I would suggest to use is the Twitter Bootstrap frame work. It is incredibly smart light weight and easy to use, when you get the hang around the things as to how they work. You don't need to worry just about iPhone and Desktop. Twitter Bootstrap caters to the other devices as well like tables et-al.
Now coming directly to your question as you wanted to show the same tabbed content both on Mobile as well as Desktop, without having two separate html files. Following is what I have put up for you as a sample demo.
I have a simple html file with all the content, It used twitter bootstrap as a responsive frame work.
HTML
Please see fiddle, It is too huge(content) to be pasted here :)
CSS
Except from Loading bootstrap.css and bootstrap-responsive.css, I need my custom CSS to suit the layout of my page.
The most important part of CSS that actually does the rick here is the media query. I specify the device width and ask the CSS to display in this manner, when this device width has reached.  Media Query Syntax is like:
@media  (max-width:480px) {
   // Custom for device that has width 480px;

}

Now iPhone has a width of 480px for layout and when the device on which my page is being viewed, I want to style my elements to suit the 480px screen.
Here is the custom CSS for the page:
.container {
    margin-top: 10px;
}
.ora, .ban, .man{display:none;}
.fruit-content{width:100%;}
li{display:inline-block;width:24%;text-align:center;border-bottom:1px solid #fff;background: #C0C;}
ul.upperul{margin:0 0 0 0px;width:103%;}
.custom-row{border:1px solid green;}
.selected{background: #c0c0c0;}
@media  (max-width:480px) {
    li{display: block;width: 100%;text-align: left;}
    .custom-row{border:1px solid #000000;}
    ul.upperul{margin-left: 0px;width:100%;}

}

JS
Now comes the functionality part about switching the tabbed content. I used jQuery with just a few lines of code to set the content in a tabbed Manner:
$(function() {
    $("li").live("click" , function() {
     $(this).css("background","#c0c0c0").siblings().css("background","#C0C");
     $(".des").hide().eq($(this).index()).show();
    })
    .eq(0).addClass('selected');
});

Finally The whole building block of these pieces is here in a fiddle:
DEMO
The Full screen Result is Here, resize your browser and see how the content behaves and responsiveness is achieved.

A: I would definitely go for Attemp 1 and try to simulate a "seperate page". It's much more lightweight and flexible in this case.
Attemp 2 and 3 have too much overhead in my opinion.
Some thougths on UX
From the perspective of UX I would say it's not good to change the concept of navigation in the way you show above. The users might get confused when resizing their browser window.


text:
Q: Correct name of place showing live concert videos What is the correct name of a place that shows live concert videos in a hall?

*

*Cine live hall

*Live cine hall

*Cine live in the hall

The noun takes two adjectives but I can't see which one would come first. I also wonder whether there's a type of event or performance called "cine live."

A: As far as I'm aware, English doesn't have a word or phrase for such a place, probably since it's unlikely that there would be a building or facility dedicated to showing live videos/streams of concerts.
One place that might show a live video of a concert would be a cinema (British English) or a movie theater (American English) (from Oxford Dictionaries):

cinema
  NOUN
British
1 A theatre where films are shown for public entertainment:
"I was weaned on a diet of Hollywood fantasy at my local cinema"
"I never go to the cinema"

movie theatre (also movie house)
  NOUN
North American
  A cinema.

In which case, you might use the verb to show to say that the cinema is offering customers the opportunity to see live video of the concert:

show
  VERB
1 Be, allow, or cause to be visible:
[no object] "wrinkles were starting to show on her face"
"the glow of a city skyline showed up ahead"
[no object, with complement] "the muscles of her jaws showed white through
  the skin"
[with object] "a white blouse will show the blood"
"a rising moon showed up the wild seascape"

1.3 [with object] Present (a film or television programme) on a screen
    for viewing:
"ITV showed The Enforcer on Saturday night"
1.4 [with object] (of a film) be presented for viewing:
"a movie showing at the Venice Film Festival"

Or you might say that the cinema was "putting on a showing of (the concert)":

showing
  NOUN
1 [mass noun] The action of showing something, or the fact of being
  shown:
"Alsation dog, championship quality, excellent results in showing"

1.1 [count noun] A presentation of a cinema film or television
    programme:
"another showing of the three-part series"

Note that to show and showing are appropriate for other venues. For example, some community/leisure centres put on showings of films, or a pub might show a sports match. It's also appropriate to use the passive voice (e.g. "that film is being shown at the pub").
Unfortunately, cine is not the correct word (unless you're Indian), as cine in English is for describing things related to the process of film-making rather than films in general:

cine
  ADJECTIVE
British
1 Cinematographic:
"a cine camera"

1.1 Indian Relating to cinema:
"a cine actor"

cinematography
  NOUN
[mass noun] The art of photography and camerawork in film-making:
"home movie footage with superb cinematography"


text:
Q: Playframework 2 - Storing your credentials Where do you store you credentials like secret key , mail passwords, db passwords?
I made a post on https://security.stackexchange.com/questions/19785/security-concerns-about-my-webapp/19786#19786
And it seems the best way to store the credentials is on an external server.
But play2 uses the application.conf to do this.

*

*So how and where do you store your credentials in play2?

Update 1:
Okay I am using heroku.
I set my enviroment variable like this:
heroku config:add test=ITWORKS

in application.conf I added
sometest=${test}

I trying to access it like this:
Logger.info(Play.application().configuration().getString("sometest"));

But I get the following error:
UnresolvedSubstitution: conf\application.conf: 54: Could not resolve substitution to a value: ${test}

So I guess play2 doesn't find the variable test because it is on heroku. But then I also added it in my local windows environment -> still the same error.
Any idea what is wrong?
Update2:
Okay it works, I just have to reboot after I added an env variable.
Last question:
It's kinda annoying to add the system variable everytime on my local machine. Is there a dev mode?

A: application.conf supports environment variables, e.g. db.default.user=${DB_USER}. You can pass it as a console parameter (which is not safe since it appears in ps), or more safely set it as an environment variable.
On Heroku, set the environment variable via heroku config, e.g. heroku config:add DB_USER=MyDBAdmin.
Locally you can set them via export DB_USER=MyDBAdmin, or add them to your ~/.bash_profile (if you use bash).

A: ad. 3: In Play application.conf is not accesible via any route or other kind of path so it can not be considered as 'placed in webroot'. Terry's advice is proper in PHP, but doesn't fit to Play (he warned, that he don't know the framework of course). He gives a sample of PHP script, but believe me, the diffrence between access to http://somdomain.tld/config.php and Play's conf/application.conf is huge. They can't be compared directly.
Storing credentials in application.conf is the safest (and fastest) way for now, I can't imagine a way to decompile the file in browser even if parser would die (which isn't possible as it's not PHP). If you'll decide to store credentials in some distant location, you'll gain the  new risk, as you will need to additionally check if client has permissions to get the config, time required for application's start will rise etc, etc.
Update 1:
Using environment variables is not a secure way - as Marius pointed, it will appear in the process list, so you will show your credentials to each admin and I'm pretty sure that you don't want do that with ie. your email.
In Heroku of course it's a way for passing their DB connection URL, but other credentials should be stored in config file. Finally remember that Procfile command length is limited to 255 chars, so placing all credential in it will cause, that your app won't start some day.
Resolution in this case is using alernative configuration files, scenario is quite simple

*

*in your application.conf keep an URL to your production database If it's Heroku most probably db.default.user and db.default.password should be commented as common heroku URL contains credentials in it.

*For your local version create a file ie: conf/local_postgres.conf include application.conf at the beginning and override/add all required configuration keys like credentials to your local Postgres DB. Additionally you can set there other things, change logging levels, enable smtp.mock, etc.

*Run your app locally with this conf. (note, I had some problem with -Dconfig.resource so I had to use -Dconfig.file syntax instead, you have to find which method will be working good in your system) ie.
play -Dconfig.resource=local_postgres.conf "~run 9123"

Tip: Using non default port is the easiest way to "demonstrate" that you're working with local config. If you'll forget that you have alternative config and will start your app with common play ~run command, your app in location http://localhost:9123 will be just unavailable.

*Create a bash script run-local (or run-local.bat file in Windows) and place there command from previous point. Ignore it in .gitignore file.
From now you'll be running the application for local development with the script from point 4.  While pushing to Heroku it will deploy your app with values from application.conf as you don't set alternative config in the Procfile. What's more with some other combinations you can run locally your application with Heroku's SQL to perform evolutions without pushing it to deployment, or check newest fix-pack. Of course you have to always make sure that you're developing on the local version of database, otherwise there's a risk that you accidentally change/destroy your life data.
Update 2:
Finally using *.conf files is better than storing it in separate classes in case when you have to change configuration for different locations (as mentioned yet, team working on the same code, dev/prod environments etc.)
Of course can be shortened to:
import play.Configuration;
import play.Play;

// ...
Configuration cfg = Play.application().configuration();

cfg.getString("smtp.password");
cfg.getBoolean("smtp.mock");
cfg.getInt("smtp.port");


text:
Q: java code and unix daemon I'having a problem when trying to run my java code wit nohup :
[root@ /]# nohup opt/jdk1.6.0_22/bin/java -cp "lib/hibernate/*:lib/tuscany-sca-1.6/lib/*:lib/tuscany-sca-1.6/modules/*:./*" com.lab.launch.Launcher &

[1] 23148

Content of nohup.out :
22 dec. 2010 18:20:21 org.apache.tuscany.sca.node.impl.NodeImpl <init>
INFO: Creating node: SOAPExchange.composite
22 dec. 2010 18:20:22 org.apache.tuscany.sca.node.impl.NodeImpl configureNode
INFO: Loading contribution: file:/xf_exchange.jar
22 dec. 2010 18:20:23 org.apache.tuscany.sca.node.impl.NodeImpl start
INFO: Starting node: SOAPExchange.composite
22 dec. 2010 18:20:32 org.apache.tuscany.sca.http.jetty.JettyServer addServletMapping
INFO: Added Servlet mapping: http://ns200534.ovh.net:8094/SOAPExchange
Exception in thread "main" java.io.IOException: Bad file descriptor
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:199)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
    at com.xavier.launch.Launcher.main(Launcher.java:24)
Exception in thread "Thread-1" java.lang.IllegalStateException: Shutdown in progress
    at java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:55)
    at java.lang.Runtime.removeShutdownHook(Runtime.java:220)
    at org.apache.tuscany.sca.binding.ws.axis2.TuscanyListenerManager.stop(TuscanyListenerManager.java:87)
    at org.apache.tuscany.sca.binding.ws.axis2.TuscanyListenerManager$ListenerManagerShutdownThread.run(TuscanyListenerManager.java:100)
java.lang.IllegalStateException: Shutdown in progress
    at java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:55)
    at java.lang.Runtime.removeShutdownHook(Runtime.java:220)
    at org.apache.tuscany.sca.binding.ws.axis2.TuscanyListenerManager.stop(TuscanyListenerManager.java:87)
    at org.apache.axis2.context.ConfigurationContext.terminate(ConfigurationContext.java:744)
    at org.apache.axis2.transport.http.AxisServlet.destroy(AxisServlet.java:465)
    at org.apache.tuscany.sca.binding.ws.axis2.Axis2ServiceServlet.destroy(Axis2ServiceServlet.java:295)
    at org.mortbay.jetty.servlet.ServletHolder.destroyInstance(ServletHolder.java:315)
    at org.mortbay.jetty.servlet.ServletHolder.doStop(ServletHolder.java:286)
    at org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:65)
    at org.mortbay.jetty.servlet.ServletHandler.doStop(ServletHandler.java:170)
    at org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:65)
    at org.mortbay.jetty.handler.HandlerWrapper.doStop(HandlerWrapper.java:129)
    at org.mortbay.jetty.servlet.SessionHandler.doStop(SessionHandler.java:124)
    at org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:65)
    at org.mortbay.jetty.handler.HandlerWrapper.doStop(HandlerWrapper.java:129)
    at org.mortbay.jetty.handler.ContextHandler.doStop(ContextHandler.java:566)
    at org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:65)
    at org.mortbay.jetty.handler.HandlerWrapper.doStop(HandlerWrapper.java:129)
    at org.mortbay.jetty.Server.doStop(Server.java:281)
    at org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:65)
    at org.mortbay.jetty.Server$ShutdownHookThread.run(Server.java:559)

thanks for your help

A: Exception in thread "main" java.io.IOException: Bad file descriptor
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:199)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
    at com.xavier.launch.Launcher.main(Launcher.java:24)

It looks like there is a bug in your application (or in its parameters) and I'm not sure it is not related to nohup. What is the file it tries to read?


text:
Q: How double quotes are added in LC_COLLATE? On Centos 6.5, running locale produces:
LANG=en_US.UTF-8
LC_CTYPE=en_US.UTF-8
LC_NUMERIC=zh_CN.UTF-8
LC_TIME=zh_CN.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=zh_CN.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=zh_CN.UTF-8
LC_NAME=zh_CN.UTF-8
LC_ADDRESS=zh_CN.UTF-8
LC_TELEPHONE=zh_CN.UTF-8
LC_MEASUREMENT=zh_CN.UTF-8
LC_IDENTIFICATION=zh_CN.UTF-8
LC_ALL=

After running export LC_COLLATE="en_US.UTF-8", running locale produces:

LANG=en_US.UTF-8
LC_CTYPE=en_US.UTF-8
LC_NUMERIC=zh_CN.UTF-8
LC_TIME=zh_CN.UTF-8
LC_COLLATE=en_US.UTF-8
LC_MONETARY=zh_CN.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=zh_CN.UTF-8
LC_NAME=zh_CN.UTF-8
LC_ADDRESS=zh_CN.UTF-8
LC_TELEPHONE=zh_CN.UTF-8
LC_MEASUREMENT=zh_CN.UTF-8
LC_IDENTIFICATION=zh_CN.UTF-8
LC_ALL=

LC_COLLATE="en_US.UTF-8" becomes LC_COLLATE=en_US.UTF-8. Double quotes are lost. How LC_COLLATE is set to "en_US.UTF-8"? If I run export LC_COLLATE='"en_US.UTF-8"', there is the following error:
-bash: warning: setlocale: LC_COLLATE: cannot change locale ("en_US.UTF-8"): No such file or directory
-bash: warning: setlocale: LC_COLLATE: cannot change locale ("en_US.UTF-8")

How I can set LC_COLLATE to "en_US.UTF-8" using some commands?


text:
Q: Remove jquery datepicker from a html control I have a datepicker on a textbox txtDate. I need to remove the datepicker, if a particular checkbox chkBox is checked. And to reapply the datepicker if the checkbox is not checked.
I tried making the textbox readonly, but datepicker is still working. How to do this.
EDIT: On the same checkbox event, I also want to make a select (dropdown) control as non selectable. No one should be able to change what in the select control.

A: In your change handler for the checkbox you can call enable or disable on the datepicker, for example:
$("#chkBox").change(function() {
  $("#txtDate").attr("readonly", this.checked)
               .datepicker(this.checked ? "disable" : "enable");
  //for your edit:
  $("#someSelect").attr("disabled", this.checked);
});

You can try it out in a demo here.


text:
Q: Need to direct the user to a file in the root of the website This should be pretty simple but I am having an issue.
I have a sidebar that is included into every page we have in our website. Now those pages can sometimes be found in different folders, so that poses an issue. When you are on index.php and fill out the form on the page, it directs you to the correct path.. But if you are in, (fictional folder title for clarity,) password/index.html that sidebar cannot link to the proper file to send the user upon form completion.
Here is my code:
 form name="sms_signup" method="post" action="text_alerts_thank_you.html" onSubmit="return ValidateForm();" target="_self" style="padding-bottom:25px;" class="form-horizontal">

What I need to know is, how do I tell HTML o go to the root of the directory and then access the file?
Thanks!

A: Start the action with a "/":
<form name="sms_signup" method="post" action="/text_alerts_thank_you.html" onSubmit="return ValidateForm();" target="_self" style="padding-bottom:25px;" class="form-horizontal">

A: You may have to look at displaying the path correctly within the "action" input.
See this question for more information on paths. HTML - pick images of Root Folder from Sub-Folder


text:
Q: Structure a stylesheet to manage skins or themes How can I structure a CSS or LESS file to manage skins or themes?
ex: using LESS vars to stock colors, or link to img patterns, and if I change this file the look of the site changes... but I don't know really how to proceed, I mean the better way?
Colors vars (dark/middle_dark/basic/middle_light/light) and do the same for all basic colors
/*neuter*/
@g_d_neuter: #3c3c3c; /*etc...*/

/*blue*/
@g_d_blue: #2D4B55; /*etc...*/

But for CSS classes I don't know how to structure the thing. Could I do like below:
.g_plans {
    padding: 10px;
    background-color: @g_l_neuter;
    border: solid 1px @g_ml_neuter;
 }
.g_titles {}
.g_texts {margin-bottom: 10px;}
.g_items {background-color: @g_l_neuter;}
.g_labels {}

etc...

A: A first idea would be to use different CSS files, and then write the <link> that references them using some JavaScript or PHP variable:
<link href = "<?php echo $_request['theme_name'] ?>" rel = "stylesheet" />

A variation on this theme should cover it.

A: Ordinarily, you would not create a CSS file that contained elements from different themes.
Keeping themes in separate CSS files makes the themes isolated and simplifies maintenance and retesting.
That is unless it is typical that the document will regularly switch themes whilst it is being viewed.  Even if this is the scenario, there's no reason why different themes cannot be implemented with different CSS files.
(Regardless whether or not the CSS files were produced statically, or dynamically using a preprocessor like LESS)

A: I Think You Need to Abstract A Bit More
File #1: All Possible Color, Img, Etc. Definitions
In this file you define all your possible colors, images to be used, etc.
/*neuter*/
@g_d_neuter: #3c3c3c; /*etc...*/

/*blue*/
@g_d_blue: #2D4B55; /*etc...*/

File #2: Theme Definitions File (here for your "neutral" theme perhaps)
You include the color definitions (File #1) into this file so it can define more "generic" variable names using the colors, images, etc. from File #1.
@backgroundColor: @g_d_neuter; /*etc...*/
@borderColor: @someColorValueForNeutralThemeBordersDefinedInFirstFile;

File #3: CSS Build File
To build the theme, import that theme file (File #2) into this file (or before this file) and then use those "generic" variables to define your actual classes, mixins, etc. This way, every theme is defining the same set of necessary variables for the output CSS.
.g_plans {
    padding: 10px;
    background-color: @backgroundColor;
    border: solid 1px @borderColor;
 }
.g_titles {}
.g_texts {margin-bottom: 10px;}
.g_items {background-color: @backgroundColor;}
.g_labels {}

Summary
Essentially, File #1 is your styling, File #3 is your sight structure and application of styles, and File #2 is the interface that changes the specific color variables from File #1 into generic references that allows File #3 to not have to change its variable definitions from theme to theme.


text:
Q: Can I ssh to my board directly? I have a robot that uses nano-pi board(something like raspberry). my robot is somewhere that there is no LAN network. So, can I use the LAN cable directly from the board(robot) to my laptop(Ubuntu 16.04 is the OS of both laptop/robot)?

A: Absolutely. Two options:

*

*In NetworkManager on the laptop create a new Ethernet connection and choose "Shared to other computers" as the method on both the IPv4 and IPv6 Settings tabs. The board will then use the laptop as a DHCP server.

*In NetworkManager on both systems create a new Ethernet connection and choose "Link-local Only" on both tabs. This will give the network adapters automatically-generated IPv4 and IPv6 addresses.
In both cases you should have Avahi running on the board so that you can connect to it using its Zeroconf address.
Note that doing this should be considered insecure on both systems (although not catastrophically so), and the rest of the network, firewall, and service settings should reflect this.


text:
Q: Sqlinjection attack in C language I know sql-injection is a web based attack. but I want to know is it possible ? to write sql injection attack complete code in C language or I can take the code in C  (from any open source web site). I would introduce some invariants in that code and then check my invariants work fine or not in that particular program.

A:
I know sql-injection is a web based attack.

It is not. SQL injections can be done whenever user input gets included in SQL statements - this can be web based, but can also happen if you use the same input in an equally vulnerable desktop application communicating with a database. So yes, you could do that in C, or basically any programming language that can interact with a vulnerable software.


text:
Q: How can I use Mongoid and ActiveRecord in parallel  in Rails 3? I'm using rails 3, and began my application with ActiveRecord.  Now, I have many models, and the relations are starting to get complicated, and some could be more simply expressed with a Document-Oriented structure, so I'd like to try migrating to MongoDB and use Mongoid.
I've always heard that you didn't have to eitheer use all MongoDB or nothing, but that you could use the two in parallel while migrating.  I don't see how to go about this from the docs though.
For example, I have:
class User < ActiveRecord::Base
   has_many :items
   has_many :products, :through => :items
end

class Product < ActiveRecord::Base
   has_many :items
end

class Item < ActiveRecord::Base
   belongs_to :user
   belongs_to :product

   # alot of data that fits a hierarchical document-oriented structure
end

I'd like to ideally begin by replacing my Item activerecord model with a Mongoid document, so my items are stored in MongoDB, and my Users and Products can stay in my SQL DB
Thing is, I don't see how to do this.  Am I going about this the right way?
Perhaps another alternative is to keep a base AR Item
class Item < ActiveRecord::Base
   has_one :mongodb_item  ?? # I know this is wrong
end

class MongodbItem
   include Mongoid::Document
   belongs_to AR_Item ???    # I know this is also wrong
end

Thanks!

A: What I did was just mock the relationship with methods in each the AR model and the Mongoid model like so.
# visit_session.rb
class VisitSession
  include Mongoid::Document
  include Mongoid::Timestamps

  field :user_id, type: Integer
  index({user_id: 1},{name: :user_id_index})

  # Mock a belongs_to relationship with User model
  def user
    User.find(self.user_id)
  end
end

# user.rb
class User < ActiveRecord::Base

  # Mock a has_many relationship with VisitSession Mongoid model
  def visit_sessions
    VisitSession.where(user_id: self.id)
  end
end

Of course you won't have all the AR methods on VisitSession Mongoid model but you'll at least be able to mock the relationship between the two fairly well.
Hope this helps.

A: I don't see any reason why you couldn't have both ActiveRecord and Mongoid models in the same application. That being said, I'm almost certain that you'll run into issues if you try to create relationships between your ActiveRecord and Mongoid models.
If your ActiveRecord models are heavily inter-related, but better suited to a document structure, then I would suggest just biting the bullet and converting them all to Mongoid documents. I had to do this recently on a (large-ish) project, and it's significantly less stressful than you would think.
If you have good unit tests for your models, then it should be a total snap. If you don't - write your unit tests first, make sure they pass with ActiveRecord and then start migrating things over to Mongoid.

A: i created a module for spoofing the relation in active record models.
module MongoRelations
  def belongs_to_mongo(name, options = {})
    id_name = "mongo_#{name}_id".to_sym
    mongo_model = options[:through] || "Mongo::#{name.to_s.camelize}".constantize

    define_method(name) do
      id = send(id_name)
      mongo_model.find(id) if id.present?
    end

    define_method("#{name}=") do |value|
      send("#{id_name}=".to_sym, value.try(:id).to_s)
    end
  end
end

In my SQL table, I name my mongo relations using the convention mongo_XXX_id, instead of XXX_id
I also namespace all my mongo models under Mongo::
in my active record model
class Foo < ActiveRecord::Base
    belongs_to_mongo :XXX
end

which allows
Foo.new.XXX = Mongo.find('123')
Foo.XXX

or
Foo.new.XXX_id = '123'
Foo.XXX

A: ... just for tracking purpose,
I'd like to add something I just found out on this field:
DRY up your SQL+NoSQL Rails projects


text:
Q: Can we use NetSuite suitescript to read data from a SFTP folder? I have a requirement to export payment files from NetSuite to a secure ftp folder and read the status of the payments back into NetSuite from the secure ftp folder.
I do not want to maintain any code in an external system. Does anyone know, How do I achieve this using Suite Script in Netsuite ?
Thanks a lot !

A: I made a tool and a video tutorial on how to use the new SFTP module of 2016.2 Suitescript API. It has everything you need to kickstart your script project like getting a passwordGUID and a hostkey of the sftp server.

Check the code here

A: I know this response is a little late however NetSuite just replaced SFTP.
If you have access to NetSuite SuiteAnswers, check out the link below.
https://netsuite.custhelp.com/app/answers/detail/a_id/51361
/**
*@NApiVersion 2.x
*/
require(['N/sftp', 'N/file'],
function(sftp, file) {
    var myPwdGuid = "B34672495064525E5D65032D63B52301";
    var myHostKey = "AAA1234567890Q=";

    var connection = sftp.createConnection({
        username: 'myuser',
        passwordGuid: myPwdGuid,
        url: 'host.somewhere.com',
        directory: 'myuser/wheres/my/file',
        hostKey: myHostKey
    });

    var myFileToUpload = file.create({
        name: 'originalname.js',
        fileType: file.fileType.PLAINTEXT,
        contents: 'I am a test file. Hear me roar.'
    });

    connection.upload({
        directory: 'relative/path/to/remote/dir',
        filename: 'newFileNameOnServer.js',
        file: myFileToUpload,
        replaceExisting: true
    });

    var downloadedFile = connection.download({
        directory: 'relative/path/to/file',
        filename: 'downloadMe.js'
    });
});

A: Using SuiteScript alone is impossible. You need to create an external app that will read the file from NetSuite via web service/suitetalk and upload it to the FTP or vice versa.


text:
Q: The sum of $\binom{n}{0}\binom{3n}{2n}-\binom{n}{1}\binom{3n-3}{2n-3}+\binom{n}{2}\binom{3n-6}{2n-6}+\cdots \cdots $
The sum of $$\binom{n}{0}\binom{3n}{2n}-\binom{n}{1}\binom{3n-3}{2n-3}+\binom{n}{2}\binom{3n-6}{2n-6}-\cdots \cdots \cdots $$

$\bf{My\; Try::}$ We can write above sum  as $$\sum^{n}_{k=0}(-1)^k\binom{n}{k}\binom{3n-3k}{2n-3k} = \sum^{n}_{k=0}(-1)^k\binom{n}{k}\binom{3n-3k}{n}$$
So sum $$ = \sum^{n}_{k=0}(-1)^k\cdot \frac{n!}{k!\cdot (n-k)!}\times \frac{(3n-2k)!}{n!\cdot (2n-3k)!} = \sum^{n}_{k=0}(-1)^k \cdot \frac{(3n-2k)!}{k!\cdot (n-k)!\cdot (2n-3k)!}$$
Now i did not understand how can i solve it after that , help Required, Thanks

A: Let's try to see this combinatorially in the form of picking marbles.
Suppose you have a $3\times n$ grid of marbles, and you want to choose $2n$
marbles out of them. The number of ways to do so is
$$\binom{3n}{2n}=\binom{n}{0}\binom{3n}{2n}.$$
The number of ways to do so with the additional requirement that we choose at least $k$ full rows can be computed as first choosing $k$ rows out of $n$, and then choosing $2n-3k$ marbles out of the remaining $3n-3k$ freely, so this number equals
$$\binom{n}{k}\binom{3n-3k}{2n-3k}.$$
We're taking an alternating sum over these terms, which suggests the inclusion-exclusion principle; the alternating sum counts the number of ways to pick $2n$ marbles without picking any full row. The only way to do so is by picking exactly $2$ marbles from each row, and there are $3$ ways to do so for each row. This shows that the alternating sum equals $3^n$.

A: This  also has  a  very simple  algebraic  proof. Suppose  we seek  to
evaluate
$$S_n = \sum_{k=0}^n {n\choose k} (-1)^k {3n-3k\choose n}.$$
Introduce
$${3n-3k\choose n} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2n-3k+1}} \frac{1}{(1-z)^{n+1}} \; dz.$$
We get for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2n+1}} \frac{1}{(1-z)^{n+1}}
\sum_{k=0}^n {n\choose k} (-1)^k z^{3k}
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2n+1}} \frac{1}{(1-z)^{n+1}}
(1-z^3)^n
\; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{2n+1}} \frac{1}{1-z}
(1+z+z^2)^n
\; dz.$$
Now residues sum  to zero so we  have from the poles at  zero, one and
infinity
$$S_n - 3^n +
\mathrm{Res}_{z=\infty} \frac{1}{z^{2n+1}} \frac{1}{1-z}
(1+z+z^2)^n = 0.$$
Note that the residue at infinity is
$$-\mathrm{Res}_{z=0} \frac{1}{z^2} z^{2n+1}
\frac{1}{1-1/z} (1+1/z+1/z^2)^n
\\= -\mathrm{Res}_{z=0}  z^{2n}
\frac{1}{z-1} (1+1/z+1/z^2)^n
\\ = -\mathrm{Res}_{z=0}
\frac{1}{z-1} (z^2+z+1)^n = 0.$$
This leaves
$$\bbox[5px,border:2px solid #00A000]{S_n = 3^n.}$$

A: \begin{align*}
&\binom{n}{0}\binom{3n}{2n}-\binom{n}{1}\binom{3n-3}{2n-3}+\binom{n}{2}\binom{3n-6}{2n-6}-\cdots \\
&=\binom{n}{0}\binom{3n}{n}-\binom{n}{1}\binom{3n-3}{n}+\binom{n}{2}\binom{3n-6}{n}-\cdots
\end{align*}
The right hand side is the coefficient of $x^n$ in
\begin{align*}
&\binom{n}{0}(1+x)^{3n} - \binom{n}{1}(1+x)^{3n-3} + \cdots \\
&= (1+x)^{3n}\left(1- \frac{1}{(1+x)^3}\right)^n \\
&= (1+x)^{3n-3}(3x+3x^2+x^3)^n \\
&= x^n(1+x)^{3n-3}(3+3x+x^2)^n
\end{align*}
and hence equals $3^n$.


text:
Q: How to pass function parameter to url_for in script I am trying to pass parameter to url_for in script.
On my html code.

    click

And for my script code.
function view_article(id){
    var w=700, h=1200, l=(screen.availWidth - w) / 2, t=(screen.availHeight - h) / 2;
    window.open("{{ url_for('articles.article_detail', articleId="+id+") }}","_blank","width= "+ w + ",height=" + h + ",left=" + l + ",top=" + t + ", scrollbars = yes, location = no, toolbar = no, menubar = no, status = no");
    };

And on my python code.
@articles.route("/article/detail/<articleId>", methods=['GET', 'POST'])
def article_detail(articleId):
    return articleId

I expect to return aaa
But in this code, it returns +id+
I tried to use articleId=id instead of articleId="+id_"
But this also does not work...
Can anyone help?

A: You can use a fake article ID and replace it with the real id:
"{{ url_for('articles.article_detail', articleId=9999) }}".replace("9999", id)


text:
Q: Is $[0, 1) \times (0, 1] \to D \setminus \{ 0 \}$, $(\varphi, r) \mapsto r e^{2 \pi i \varphi}$ not a homeomorphism? In our lecture, it was claimed that
$$
\Psi \colon [0, 1) \times (0, 1] \to D \setminus \{ 0 \}, \
(\varphi, r) \mapsto r e^{2 \pi i \varphi},
$$
where $D$ denotes the unit disk in $\mathbb R^2 \cong \mathbb C$, is a homeomorphism.
On Wikipedia it states that "The fundamental group is a homotopy invariant—topological spaces that are homotopy equivalent (or the stronger case of homeomorphic) have isomorphic fundamental groups.", which I understand to mean: "If $f \colon X \to Y$ is a homeomorphism, then $\pi_1(X) \cong \pi_1(Y)$", where $X$ and $Y$ are connected topological spaces, so the fundamental group $\pi_1$ is independent of its basepoint.
It is well known, that $\pi_1(D \setminus \{ 0 \}) \cong \mathbb Z$ and we should have $\pi_1([0, 1) \times (0, 1]) \cong \{ e \}$, where $e$ is the identity element, since $[0, 1) \times (0, 1]$ is a convex set. Is my reasoning correct?
Nevertheless, the map $\Psi$ seems to be continuous as composition of continuous maps, and I think the inverse is given by
$$
\Psi^{-1}(t)
= \left( \frac{1}{2 \pi i} \log\left( \frac{t}{| t |}\right), | t |\right)
$$
which looks continuous also.

A: Yes, your reasoning is correct. If you want a direct proof of the fact that $\Psi$ is not a homeomorphism, consider the sequence $\left(1-\frac1n,\frac12\right)_{n\in\Bbb N}$ of points of $[0,1)\times(0,1]$. It diverges in that space, but it is mapped by $\Psi$ into the sequence $\left(\frac12e^{2\pi i(1-1/n)}\right)_{n\in\Bbb N}$, which converges to $\frac12$.


text:
Q: Mips: replace a bit by using andi and ori logic instructions let's suppose i have 16bit in $t0 and i need to change the 6 bit and 7 bit to 0 and 1 with preserving the other bits. So the bit 6 will have the value 0 and the bit 7 will have the value 0.
I know i can do that by using the logic instructions andi and ori.
Andi instruction can clear a bit and ori can set a value to a bit.
Let's see the code:

andi $t0,$t0,0x...
ori $t0,$t0,0x...
What hex should i put for replacing the bits? Thanks!


text:
Q: Check if the file is directory or not Program:
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/stat.h>
int main(int argc, char *argv[])
{
    DIR *dp;
    struct dirent *dirp;
    struct stat stbuf;
    if (argc != 2)
        printf("usage: ls directory_name\n");

    if ((dp = opendir(argv[1])) == NULL)
        printf("can't open %s", argv[1]);

    while ((dirp = readdir(dp)) != NULL){
        stat(dirp->d_name,&stbuf);
        if(S_ISDIR(stbuf.st_mode)){
            printf("Directory: ");
        }
        printf("%s\n",dirp->d_name);
    }

    closedir(dp);
    exit(0);
}

Output:
$ ./a.out test/
dir3
d
c
Directory: .
Directory: a
Directory: ..
Directory: dir4
Directory: dir2
Directory: dir0
Directory: b
Directory: e
Directory: dir1
$

The following are the list of files that the directory "test" contains.
$ ls -F test/
a  b  c  d  dir0/  dir1/  dir2/  dir3/  dir4/  e
$

The expected output is, if the file is directory the output will be "Directory: dir1/". Else only the file name.
But, the output of the program is not as expected. Is the program contains any error?. Is there any let me know.
Thanks in Advance...

A: Lets break it down into steps:

*

*You start your program from some directory. This directory will become the process current working directory (CWD).

*You call opendir on the directory test. This is actually the directory test in the CWD.

*You call readdir to get the first entry in the directory.

*This first entry is the . directory, which is short for current directory, all directories have it.

*You call stat with ., meaning you call stat on the CWD. It of course succeeds and stat fills in the structure with all the details of the CWD.

*Next iteration you get the entry a and you call stat on that entry. However since there is no a in the CWD, the stat call fails. You however doesn't check for that, and uses the stat structure that was filled in from the previous call (from the successful stat of the . directory).
And so on...
You need to tell stat to look for the entries in the given directory instead of the CWD. This can basically be done in only two ways:

*

*Format a string so that you prefix the entry with the directory you passed to opendir. E.g.
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1] ,dirp->p_name);
if (stat(path, &stbuf) != -1)
{
    // `stat` call succeeded, do something
}

*After calling opendir, but before looping that directory, change the CWD:
// Opendir call etc...

chdir(argv[1]);

// Loop using readdir etc.

Alternatively, start the program from the directory you want to check:
$ cd test
$ ../a.out .


text:
Q: getting error on command sudo apt-get update when trying to update npm version i am getting error after using this command
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

errors i am getting on sudo apt-get update:
W: The repository 'http://ppa.launchpad.net/chris-lea/node.js/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: The repository 'http://ppa.launchpad.net/openjdk-r/ppa/ubuntu utopic Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/chris-lea/node.js/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not Found
E: Failed to fetch http://ppa.launchpad.net/openjdk-r/ppa/ubuntu/dists/utopic/main/binary-amd64/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.


text:
Q: hklm\Security Vs Security\Policy I am researching the way an attacker would get a machine credentials.
I figured the most common methods are to dump
hklm\sam
hklm\security
hklm\system

I was able to figure what information is stored in the SAM and why would I want to save it, but wasnt able to figure the difference between the other 2 registries.
I have read many manuals by now, and the explanations for both always seem very similar, so I cant tell what is the difference


text:
Q: Zeppelin SqlContext registerTempTable issue I am trying to access some json data using sqlContext.jsonFile in zeppelin...
following code execute without any error:
import sys.process._
val sqlCon = new org.apache.spark.sql.SQLContext(sc)
val jfile = sqlCon.jsonFile(s"file:///usr/local/src/knoldus/projects/scaladay_data/scalaDays2015Amsterdam_tweets.json")

import sqlContext.implicits._
jfile.registerTempTable("jTable01")

output :
import sys.process._ sqlCon: org.apache.spark.sql.SQLContext =
  org.apache.spark.sql.SQLContext@7034473 jfile:
  org.apache.spark.sql.DataFrame = [id: struct, content:
  string, hashtags: array, score:
  struct, session:
  string, timestamp: bigint, tweetId: bigint, username: string] import
  sqlContext.implicits.

next I verify the table name which I just registered
sqlCon.tableNames().foreach(println)

output :
jTable01

but when I try to run following I get an error:
%sql
select * from jTable01

output :
no such table jTable01; line 1 pos 14

at the same time when I run the tutorial example for "bank" it works....
the only difference I could make out is that in bank tutorial we are using sc.textFile but in my case I wanted to use sqlContext.jsonFile.
could you please provide any guidance as how I can fix this issue?

A: found the solution removed
val sqlCon = new org.apache.spark.sql.SQLContext(sc)
from my code and used zeppelin default sqlContext
and it works!!!

A: In my case nothing resolved it until I removed
import org.apache.spark.sql.SQLContext


text:
Q: inputting in a multithreaded process Hey i am learning about networks and BSD sockets right now and i want to create a group chat.So after creating a multithreaded server(1 thread for each user) i have a question right now .
So basically my server works like this.Each threads waits for its client to send a massage then it sends to all other users in the chat.Now i am thinking do i have to make the client program 2 threaded.One thread will always wait for an massage from the server and the other one will wait for a user input.
But will it work??If i will just write in the second thread cin>>massage; Will everything be ok?
What if halfway through my input scheduler decides to give the CPU to the first thread.

A: You do not have to have a multi-threaded client.  You could but it is not required.
Look at select() and poll() to see if your socket is ready to read from. For a single-threaded program, you just interleave your reads and writes when you have data ready and sleep() or sched_yield() the rest of the time.


text:
Q: pySerial read missing bits I have the following write and read code for the serial port. But when I run them frequently, say 100 times write and read, there's always some times the read got wrong byte number, it should get 9 bytes, but sometimes it got only 8 bytes.
For example, normally when I send,  [1, 88, 0, 27, 192], it should return 9 bytes, like  [1, 88, 4, 0, 0, 3, 35, 182, 49]. But it always wrong at the number 89 times of write and read, it returns like [1, 88, 4, 0, 1, 209, 107, 180], 1 byte less. And after I detect this is 1 byte missing, I write and read the same sending message again like [1, 88, 0, 27, 192], the read data after this is always having one byte missing. However, after some other statements in between, the 1 byte missing problem won't appear every time.
I have got another problem like, the device cannot received my write sometimes on specific command, to be specific, there's no returns after I send a command when there should be, and since my serial device didn't receive so it doesn't execute. So I have to close() and open() such port and send command again for several times, to make is returns aka excute the command, such retries take so much time which makes me anoying waiting.
My configuration, FT232RL USB to Serial chip, 9600 baud rate, 8 bytesize, timeout is 1 second, stop bits 1, parity None.
def SendData(self, portID, cmd):
        """
        cmd is the pre-defined variables , they are the lists in front of this file.
        After send data, there is a delay.
        """
        global command_count
        if (self.isOpen(portID)):
            command_count += 1
            lock = threading.RLock()
            with lock:
                try:
                    COMlogger.debug("SendData command count %d" % (command_count))
                    writereturn = self.serdict[portID].write(list2bytestr(cmd))
                    # wait for output buffer to drain, reference from the miniterm example
                    self.serdict[portID].flush()
                    self.lastcmd = cmd
                    COMlogger.debug("SendData sent out %s" % (str(cmd)))
                    COMlogger.debug("SendData write returns %d bytes." % writereturn)
                except:
                    COMlogger.error("Sending data to %s with ID %d failed." % (self.portaddresslist[portID], portID))
                    return False
                finally:
                    time.sleep(0.2)

            return True
        return False

    def GetData(self, portID):
        """
        It take times to let the device respond, so remember to wait a bit after sending data.
        Before get data, there is a deley
        """
        time.sleep(0.2)
        global command_count
        if (self.isOpen(portID)):
            lock = threading.RLock()
            with lock:
                try:
                    # possibly time out here
                    #receivedmsg = self.serdict[portID].readline() # stop using readline since it wait for the \n or time out.
                    text = self.serdict[portID].read(1)
                    if text:
                        time.sleep(0.2)
                        n = self.serdict[portID].inWaiting()
                        if n:
                            text += self.serdict[portID].read(n)
                    receivedmsg = text
                    COMlogger.debug("GetData from ID %d returned %s" %(portID, str(bytestr2list(receivedmsg))))
                    return receivedmsg
                except:
                    COMlogger.error( "Receiving data from %s with ID %d failed." % (self.portaddresslist[portID], portID))
                    return None
        else:
            COMlogger.error("Error in GetData, port %d is not open." % portID)
        return None


text:
Q: Can't scrape names from a table using requests I'm trying to scrape names from a table populated upon selecting some options in a webpage. This is the options to generate the table in that site. however, When I try doing the same using the script below, I always get status 500. I got success using selenium, so I'm not after any solution based upon selenium.
webpage address
I've written so far:
import requests
from bs4 import BeautifulSoup

link = 'https://rederef-saude.appspot.com/proximidade/prestador/buscar?'

params = {
    'canal': '1',
    'latitude': '-23.5505199',
    'longitude': '-46.63330939999999',
    'categoria': '1',
    'produto': '557',
    'plano': '18051',
    'nome': '',
    'qualificacoes': '',
    'prefixoEmpresa': '',
    'empresa': '',
    'especialidade': '',
    'procedimento': '',
    'tipoPesquisaProcedimento': '1',
    'raio': '200000'
}

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
    'referer': 'https://rederef-saude.appspot.com/rederef/buscaPrestadores?login=publico&canal=1&data=23/04/2021&hora=00:16:55&tipoProduto=M&produto=557&plano=18051',
    'x-requested-with': 'XMLHttpRequest',
    'content-type': 'application/json;charset=utf-8',
    'accept': '*/*',
    'captcha-token': ''
}
with requests.Session() as s:
    s.headers = headers
    res = s.get(link,params=params)
    print(res.status_code)

How can I scrape the names from that table using requests?

A: When Checking the requests it does have recaptcha protection its just that its in a invisible mode which only comes to display if required and this would even need cookies from first call or else it will give invalid session error so for recaptcha automated solution(Paid but pretty cheap) their various providers for it for ex:2Captcha,Anti-Captcha,CapMonster,etc
I Have used 2Captcha for it you could follow the below code.
Reference to 2Captcha Library
import requests
from twocaptcha import TwoCaptcha

solver = TwoCaptcha('Twocaptcha API KEY')
result = solver.recaptcha(sitekey='6LdOzkUaAAAAANV9z7gQOokV2kNWI8WI_eSH80vC',
                          url='https://rederef-saude.appspot.com', invisible=1)["code"]
params = {
    'login': 'publico',
    'canal': 1,
    'data': '23/04/2021',
    'hora': '04:10:41',
    'tipoProduto': 'M',
    'produto': 557,
    'plano': 18051
}
cookies = requests.get(
    'https://rederef-saude.appspot.com/rederef/buscaPrestadores', params=params).cookies

headers = {
    'captcha-token': result,
}
params = {
    'canal': '1',
    'latitude': '-23.5505199',
    'longitude': '-46.63330939999999',
    'categoria': '1',
    'produto': '557',
    'plano': '18051',
    'nome': '',
    'qualificacoes': '',
    'prefixoEmpresa': '',
    'empresa': '',
    'especialidade': '',
    'procedimento': '',
    'tipoPesquisaProcedimento': '1',
    'raio': '200000'
}
response = requests.get('https://rederef-saude.appspot.com/proximidade/prestador/buscar', headers=headers,
                        params=params, cookies=cookies)

print(response.json())

Don't forget to update the Twocaptcha API KEY in the above Code.
You could use any provider you feel okay with.
Output would be in json so no need to use BeautifulSoup
Output:

Let me know if you have any questions :)


text:
Q: proving that $\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a}$ is the normal to the plane. $P$, $Q$, and $R$ are points in $ \mathbb{R}^3 $ which are not on the same line. if $\vec{a} = \vec{OP}$, $\vec{b} = \vec{OQ}$, and $\vec{c} = \vec{OR}$, show that  $\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a}$ is perpendicular to the plane containing $P$, $Q$, and $R$.
So far, I have defined:
$\vec{a} = <a_1, a_2, a_3>
, \vec{b} = <b_1, b_2, b_3>
, \vec{c} = <c_1, c_2, c_3>
$
The lines spanning between the points a, b, and c.
$
\vec{ab} = <b_1 - a_1, b_2 - a_2, b_3 - a_3>
$
$
\vec{bc} = <c_1 - b_1, c_2 - b_2, c_3 - b_3>
$
$
\vec{ca} = <a_1 - c_1, a_2 - c_2, a_3 - c_3>
$
The perpendicular lines to the planes ab, bc, and ca.
$
\vec{a \times b} = <a_2b_3 - a_3b_2, a_3b_1 - a_1b_3, a_1b_2 - a_2b_1>
$
$
\vec{b \times c} = <b_2c_3 - b_3c_2, b_3c_1 - b_1c_3, b_1c_2 - b_2c_1>
$
$
\vec{c \times a} = <c_2a_3 - c_3a_2, c_3a_1 - c_1a_3, c_1a_2 - c_2a_1>
$
Adding them I get:
$
<a_2b_3 + b_2c_3 + c_2a_3 - a_3b_2 - b_3c_2 - c_3a_2, a_3b_1 + b_3c_1 + c_3a_1 - a_1b_3 - b_1c_3 - c_1a_3, a_1b_2 + b_1c_2 + c_1a_2 - a_2b_1 - b_2c_1 - c_2a_1>
$
Dot-producting the vectors $\vec{ab}$, $\vec{bc}$, and$\vec{ca}$ with the vectors $\vec{a \times b}$, $\vec{b \times c}$, and $\vec{c \times a}$ expands like crazy.
What I have been going for so far is that since vectors $\vec{ab}$, $\vec{bc}$, and$\vec{ca}$ make up the plane, if I dot product each one with the cross-product, $\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a}$, it should result in zero, or at least everything cancelling out since this is supposed to be the perpendicular to the plane. Maybe I'm just tired, but it doesn't seem to be resulting in that.
I feel like I'm getting close, but not quite getting the result that I am looking for. What exactly am I missing? Am I going in the right direction even or is there something completely obvious that I am missing?

A: Since $P,Q,R$ are non-collinear, $\vec{PQ}$ and $\vec{PR}$ are two linearly independent vectors in the plane of $PQR$. Using the notation provided in the question,
$$\vec{PQ}=\vec{OQ}-\vec{OP}=\vec b - \vec a,\\
 \space \vec{PR}=\vec{OR}-\vec{OP}=\vec c - \vec a.$$
The cross product of $\vec{PQ}$ and $\vec{PR}$ is normal to $PQR$. Repeated application of the linearity property and anti-symmetry property of the cross product,
$$\vec{PQ}\times\vec{PR}=\left(\vec b - \vec a\right)\times\left(\vec c - \vec a\right)\\
=\vec b \times \left(\vec c - \vec a\right) - \vec a \times \left(\vec c - \vec a\right)\\
=\vec b \times \vec c - \vec b \times \vec a - \vec a \times \vec c + \vec a \times \vec a\\
=\vec b \times \vec c + \vec a \times \vec b + \vec c \times \vec a + \vec0\\
=\vec a \times \vec b + \vec b \times \vec c + \vec c \times \vec a.$$

A: Note: Nothing changes under a cyclic permutation ($a \rightarrow b \rightarrow c$)
The scalar product
$$
((a \times b)+(b\times c)+(c \times a)) \cdot (b - a) =\\
$$
reduces to
$$
(b \times c)\cdot a - (c \times a) \cdot b =0
$$

A: You are right so far.  The sum of cross products seems to be correct, and when I compute the dot products with it I get zero.  Make sure you are using $\vec{ab} = \vec{b} - \vec{a}$.
For another way to do this, just use algebra:
$$\left(\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a} \right) \circ \left(\vec{b} - \vec{a}\right)$$
Distribute property of dot product:
$$\left(\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a} \right) \circ \vec{b} - \left(\vec{a} \times \vec{b} + \vec{b} \times \vec{c} + \vec{c} \times \vec{a} \right) \circ \vec{a}$$
And again:
$$\left(\vec{a} \times \vec{b}\right) \circ \vec{b} + \left( \vec{b} \times \vec{c}\right) \circ \vec{b} + \left(\vec{c} \times \vec{a} \right) \circ \vec{b} - \left(\vec{a} \times \vec{b}\right) \circ \vec{a} - \left(\vec{b} \times \vec{c}\right) \circ \vec{a} - \left(\vec{c} \times \vec{a} \right) \circ \vec{a}$$
Now since we know that $\left(\vec{x} \times \vec{y}\right) \circ \vec{x} = 0$, most of the terms above are zero:
$$\left(\vec{c} \times \vec{a} \right) \circ \vec{b} - \left(\vec{b} \times \vec{c}\right) \circ \vec{a}$$
This actually leads to a nice property of cross products: $\vec{x} \circ \left (\vec{y} \times \vec{z}\right) = \vec{z} \circ \left (\vec{x} \times \vec{y}\right) = \vec{y} \circ \left (\vec{z} \times \vec{x}\right)$.  I don't know if you would actually be expect to prove this or not in your homework since it is well known.
Either way, your work that you've already done is on the right track, you are probably just making some $\pm$ error or something in the part you haven't shown us.

A: The easy way to do this is to use the following identity obeyed by the vector cross and dot product, which may be found in the Wikipedia page http://en.m.wikipedia.org/wiki/Cross_product:  for any three vectors $\vec a, \vec b, \vec c \in \Bbb R^3$,
$\vec a \cdot (\vec b \times \vec c) = \vec b \cdot (\vec c \times \vec a) = \vec c \cdot (\vec a \times \vec b). \tag{1}$
Now observe that $\vec a  - \vec b, \vec a - \vec c$ lie in the plane containing $P,  Q, R$, and they are linearly independent since these points are not collinear.  Then
$(\vec a - \vec b) \cdot (\vec a \times \vec b + \vec b \times \vec c + \vec c \times \vec a) = \vec a \cdot (\vec b \times \vec c) - \vec b \cdot (\vec c \times \vec a = 0 \tag{2}$
by virtue of (1).  Likewise the similar product with $(\vec a - \vec c)$ replacing $(\vec a - \vec b)$ on the left hand side of (2) vanishes as well.  Thus $\vec a \times \vec b + \vec b \times \vec c + \vec c \times \vec a$ is normal to the plane containing $P, Q, R$ since $\vec a - \vec b, \vec a - \vec c$ span it.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!


text:
Q: How to change date in database In my Mysql database, i have a set of date.
How can I increase for each and every date in my database by 3 years ?
For example the current date is :
2 January 2001
I want the date to be increased by three years:
2 January 2004

A: Try this -
UPDATE TABLE set fieldname =  DATE_ADD( fieldname, INTERVAL 3 YEAR )

For more information and play part with dates you can check this link :-
function_date-add
Working Fiddle -- http://sqlfiddle.com/#!2/9c669/1
EDIT
This solution updates date type is VARCHAR and structure of date like - 2 January 2001
It will update date to 2 January 2004 by the interval of 3
Although the best way to handle date is use date DATATYPEs(ex timestamp, datetime etc) instead of saving it in VARCHARs
Tested code --
UPDATE date
SET `varchardate`= DATE_FORMAT(DATE_ADD(  str_to_date(`varchardate`, '%d %M %Y'), INTERVAL 3 YEAR ) , '%d %M %Y')

A: Check date_add function, it should do the thing -http://www.w3schools.com/sql/func_date_add.asp

A: Below query is to update the date column and also changed to date format.
update date1 set dates =
DATE_ADD( (str_to_date(concat(
SUBSTRING_INDEX( dates,  ' ', 1 ),'-',
Substring(SUBSTRING_INDEX( SUBSTRING_INDEX( dates,  ' ', 2 ) ,  ' ', -1 ),1,3) ,
'-',
SUBSTRING_INDEX( dates,  ' ', -1 )),'%d-%M-%Y')), INTERVAL 3 YEAR )

OR
The second query is simply update the year by 3.
update date1 set dates =
concat( SUBSTRING_INDEX( dates,  ' ', 2 )  ,  ' ',
(SUBSTRING_INDEX( dates,  ' ', -1 ) +3) )

SQL Fiddle Demo


text:
Q: App doesn't respond for camera permission This is a part of QR Code scanner app. In the very beginning of the app it asks for camera permission, when i click to allow, app doesn't respond. but from second time, app works correctly. I think the error may be in checking permission. Please help me to find the mistake.
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {

                    cameraSource.start(surfaceView.getHolder());
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new
                            String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
                }

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

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            cameraSource.stop();
        }
    });


text:
Q: How paste video on TinyMce How paste video on Tinymce
When i want paste video but hook"paste_preprocess" return file type is image. I can't get media data. so i can't upload local video to server.
paste_preprocess: (editor, args) => {
  console.log(editor)
  console.log(args)
  // args.content += ' preprocess'
},

args: "image/type"


text:
Q: Oracle10g database/table Tuning I am using Oracle Datbase 10g Standard Edition for my ASP.NET website. There i have one table which is going to populate with data on daily basis (around 10000 rows daily). The growth rate of data in that table is 100% i.e. every year the number of rows will increase previous plus 10000 rows.
This is main table for reports like graphical and crystal.
I know when the data increases the select query performance degrade.
Here i would like your help to tune my Oracle database/ table so that the performance of select query always remain good?
I am not very good in oracle. Please help me..............

A: Actually there is no reason why the performance should degrade as the table increases.  If your query uses indexes, to retrieve individual rows or focused sets (i.e. INDEX RANGE SCAN) then the performance should remain stable as the table grows.  This partly depends on the profile of your data.  Indexes with a low clustering factor will continue to perform but indexes with high clustering factor will degrade.  Find out more.
Where you almost certainly will have a problem is running queries which don't use indexes or which use INDEX FAST FULL SCAN.  Such queries obviously will degrade over time as the table grows.  To deal with that scenario you can build materialized views which pre-aggregate the data.
The best general advice is

*

*Read the Oracle online
documentation.  It is pretty
comprehensive.

*Start benchmarking your queries'
performance now (using Statspack).
That way you will be able to do
trend analysis and spot when things
start to go awry.

A: Simple really, make sure your indexes match up with your query.  Check your explain plans, usual oracle stuff - Read around on the subject and you'll find lots of info!
It does depend on how your queries run.  You could benefit hugely by partitioning by month if your queries only pull back a months worth of data.  Then you'll only hit a 1/12th of the data you would have done otherwise.  But if the queries are not constrained in that way then this may not help.
Finally make sure you're not reading all the data just to summarise it in the report.  So if you are doing this consider creating an overnight job to create an aggregate table, and query that instead.
Oh; Also if insert speed is an issue you may want to keep number of indexes down - if that is the case you may need to have a separate reporting table to the one where you insert the live data, and then sync the data across nightly or something.

A: Generate extra test data and test if the performance indeed degrades. Maybe you worry for nothing:)


text:
Q: send method in Ruby I just read about what send does in Ruby and I'm still confused when looking at this code (it's from a quiz but its past due date anyways)
x = [1,2,3]
x.send :[]=,0,2
x[0] + x.[](1) + x.send(:[],2)

I understand that the first line assigns an array to x
then I don't understand what :[] = ,0,2 does at all and i dont understand why send is needed there
I dont get what x.[](1) does and x.send(:[],2) do on the last line
I'm really confused and I just cant find this information online.
I found the what send does but I'm still a little bit confused and a lot of bit confused about this code as a whole.

A: send is a way to achieve reflection calls in ruby. Thus this line:
x.send :[]=,0,2

Is equivalent to:
x[0] = 2

you read it that way: the name of the method is symbol (in your case []=) and then you pass in the parameters - 0 and 2.

A: First of all, things like [] (array index) and []= are just methods in Ruby. x is an Array, and arrays have a []= method, which accepts two arguments, an index and a value to set.
Using send lets you pass an arbitrary "message" (method call) to object, with arbitrary parameters.
You could call x.send :sort, for example, to send the "sort" message to the array. Sort doesn't need any parameters, though, so we don't have to pass anything extra to it.
x#[]=,  on the other hand, accepts two arguments. Its method can be thought of to look like this:
def []=(index, value)
  self.set_value_at_index(index, value)
end

So, we can just invoke it with send :[]=, 0, 2, which is just like calling x[0] = 2. Neat, huh?

A: In Ruby, a[0] = 2 is actually syntactic sugar for a.[]=(0, 2).
Knowing this, that's what your second line does—it calls the []= method with two arguments using metaprogramming, as you correctly guessed.
This is the same for your third line: a[0] is syntactic sugar in Ruby for x.[](0).
The following code is a simpler equivalent to your example:
x = [1, 2, 3]
x[0] = 2
x[0] + x[1] + x[2]

A: Don't worry. Ruby can be a little bit tricky in these cases. Let's examine the code line by line:
x = [1,2,3]
x.send :[]=,0,2
x[0] + x.[](1) + x.send(:[],2)

First line
First line is clear to you: it assigns an array of three elements to x. And that's just about it.
Second line
Second line calls the Object#send method of x passing a symbol (remember that everything that starts with : is a symbol in ruby) :[]=, 0 (a Fixnum) and 2 (another Fixnum).
Now you just have to take a look at what the send method does (as you said you've already done):

Invokes the method identified by symbol, passing it any arguments specified

This means that it will invoke the method identified by :[]= and pass 0 and 2 to it. Now let's take a look at the Array#[]= method. This method definition (which can be overloaded by you if you need to do so) is:
class Array
    # ...
    def []=(a, b)
        # ...
    end
end

This method is called by send as x.[]=(0, 2) which is pretty ugly if you ask me. That's why Ruby defines a syntactic sugar version: x[0] = 2 and in general:
x.[]=(a, b)  -->  x[a] = b

In the Array case we also have the following:
x.[](a)  -->  x[a]

In both cases you are free to call whatever version makes sense to you in the specific context.
Third line
Now for the third and last line:
x[0] + x.[](1) + x.send(:[],2)

things gets really tricky. Let's divide it into:

*

*x[0]

*x.[](1)

*x.send(:[], 2)
The first one is pretty straight forward. It returns the first element of the array.
The second one is the syntactic sugar that we have seen earlier which can be basically be converted into x[1] which returns the second element of the array.
The third one uses Object#send to call the method [] passing 2 to it. Which means that it calls x.[](2) which means x[2].
Conclusion
The code
x = [1,2,3]
x.send :[]=,0,2
x[0] + x.[](1) + x.send(:[],2)

can be converted using:
x.send(:[]=, a, b)  -->  x.[]=(a, b)
x.send(:[], a)  -->  x.[](a)
x.[]=(a, b)  -->  x[a] = b
x.[](a)  -->  x[a]

to:
x = [1,2,3]
x[0] = 2
x[0] + x[1] + x[2]

which can be reduced to:
2 + 2 + 3

which results in:
7

A: x[0]+x[1]+x[2]=2+2+3=7
i guess this must be the answer


text:
Q: LinkedIn API - Refresh Access Token after 60 days - PHP I need to refresh token after 60 days in linkedin PHP API
Can you tell me how to send API request .I also tried this link
https://developer.linkedin.com/blog/tips-and-tricks-refreshing-access-token..
Please give some idea to refresh the access token of Linkedin API

A: Send the user through the exact same process you created for them to Authenticate the account in the first place.
If the User is logged in to the authenticated LinkedIn account already, then LinkedIn will send the user straight to your callback URL that you have defined, along with a brand new Access Token with a fresh 60 days on it.
Unfortunately, LinkedIn doesn't implement the oAuth grant_type=refresh token defined in the standard.

A: LinkedIn only handle the automatic code refresh if the user is logged into Linked In with the same browser.
So, here is how the worklflow looks like:
a) I'm logged into LinkedIn:

*

*I have a link
href="https://www.linkedin.com/uas/oauth2/authorization?response_type=code&redirect_uri=my_redirect_uri"

*Everytime I'm redirected to my_redirect_uri I get a GET parameter"code" which allows me to request a new access token throw
"https://www.linkedin.com/uas/oauth2/accessToken"
b) I'm not logged in on LinkedIn on this browser:
I need to re-authenticate every time I click on the link...


text:
Q: How to run make from Cygwin environment? I am trying to run linux driver on linux environment .. Following instruction  to run winkvm .. stuck on point run make command using cygwin environment ..
like

*

*Building original KVM drivers using Cygwin environment:
cd kvm/kernel  ## Do not type configure
make           ## you will get id: unrecognised emulation mode: elf_i386 but it's not error
make cpobjs    ## If you get not a directory message, make it and try again
How to run make command .. from which console of cygwin..
getting error bash make command not found .. from cygwin terminal

A: You have to install the make command.
Run the Cygwin installation/configuration program, setup-x86_64.exe or setup-x86.exe (you should already have it, downloaded from here). When you get to the screen that lets you select packages to install, find make and select it (it's probably under "Development" or something similar).
Then you'll be able to run make from the Cygwin bash command line.

A: If you have cygwin running, terminate it. Download the setup-x86_64.exe utility from the cygwin site (https://www.cygwin.com/). Run the utility and continue by clicking "Next" until you get to the window where you can select packages.

Type into the search panel the word "make". This works like a filter that leaves only packages related to make functionality. In category "Devel" select "make: the GNU version of 'make' utility". That is.


text:
Q: How to remove an image from a component in Angular before a new one is obtained from API I have a child component that gets a picture from an api and display it on the template. The parent component contains a list of items, when the user select one of the items, a request is send to an api to get a picture that belongs to the item, the child component is displayed and the picture that belongs to that item is shown.
The problem I have is that when the user selects a new item from the list, the child component is displayed, but the picture from the previous item is shown until a request from the api is received and the new picture is rendered.
I want to avoid displaying the previous picture, since is confusing and inconsistent for the user. Any suggestions how to accomplish this are appreciated.
Here is the parent component template where the child component is called:
    <ng-container matColumnDef="expandedDetail">

            <image-card [img64]="img64"></image-card> -->

    </ng-container>

Child img64 @Input:
@Input()
  public set img64(value: blob) {
    this.loadingData = true;
    if (value) {
      this.image = value.base64Image;
      const objectURL = 'data:image/jpeg;base64,' + this.image;
      this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
    }
  }

A: The way I solved this problem it was setting the 'this.image' value to null on parent and child components at the beginning of the functions respectively.
Parent component where the service call the api:
displaySelectedItem(id: number) {
    this.selectedImage = null;
    this.selectedItemService.
    getItemData(id).pipe(takeUntil(this._unsubscribe$))
    .subscribe((itemImage: ItemImage)=> (this.selectedImage = itemImage));
}

Child component:
@Input()
public set itemImage(value: ItemImage) {
    this.selectedImage = null;
    if(value) {
        this.itemImage = value.itemImage
    }
}


text:
Q: Is this the correct proof of absolute convergence? Absolute convergence theorem says that if $\sum |a_n|$ is convergent, so is $\sum a_n$
We have by triangle inequality :
$$|a_1+a_2+\cdots+a_n|\le |a_1|+|a_2|+\cdots+|a_n|$$
Now if $S_n$ is the sequence of partial sums of $\sum a_n$ and $P_n$ is sequence of partial sums of $\sum|a_n|$ and assuming $P_{\infty}=L$, we have:
$$|S_n|\le P_n$$
Taking limit we get:
$$\left|\lim_{n\to \infty}S_n\right|\le L$$
Hence:
$$-L \le S_{\infty}\le L$$
Hence $\sum a_n$ is convergent.

A: Hint:
Show instead that the Cauchy criterion is satisfied using
$$|S_m-S_n|=\left|\sum_{k=n+1}^m a_k\right| \leqslant \sum_{k=n+1}^m |a_k|$$

A: We can use that
$$b_n=-|a_n|\le a_n \le |a_n|=c_n$$
and conclude that
$$\sum |a_n|<\infty \implies \sum a_n<\infty$$
indeed $\sum (c_n - b_n)$ converges and therefore since
$$0\le a_n-b_n \le c_n-b_n$$
also $\sum (a_n - b_n)$ converges and since
$$\sum a_n = \sum(b_n+(a_n-b_n))= \sum b_n+\sum (a_n-b_n)$$
we conclude that $\sum a_n$ is the sum of two convergent series.


text:
Q: Why this way is bad for use git? I read on facebook group a post on git commit flow and the user ask this:
"I use this for commit my code"
git add . && git commit -m "commit message" && git push origin master

Some users commented on like that:
"This is the wrong way to use git" and more comments like that.
For my projects I use the same "flow", why is bad ? I can't find anything to exaplain why this is wrong.

A: git add . adds/stages all of the files in the current directory. This is for convenience, and can still be used if you have certain files you don't want to add by using a .gitignore.
It is always a good practice to check git status after staging files for a commit to look for any unnecessary files which might have been staged. You might accidentally push the environment variables or maybe any undesired file without your knowledge thus polluting your codebase.


text:
Q: Can we create a control like Account name in the convert lead page? Can we create a control like account name in the lead conversion page in a VF page? Its like a picklist with lookup.
How does salesforce determine if there is already an account is already present? Is it just by checking the account name? or checks if there is a contact with the same name and email and then verifies the account from the contact too ?

A: You could create it, but you'd have to do the heavy lifting yourself - there's no apex:inputfield or equivalent that provides this capability.
I've never seen any detail on how the matching takes place - your guesses sound plausible, but I haven't researched it to find out.  Generally, I've produced custom lead conversion because the customer has hard rules around matching and wants to enforce those (or there are a variety of additional objects to be created as part of the conversion).