text:
Q: Yii - Route without Controller I'm using an existing upload script that require user authentication. However since I did not write the upload script, it's nearly impossible for me to read the source code and make it into separate view and controller file. The problem is if the script does not get routed by the bootstrap file, it has no access to the Yii variable and thus user log in information.
I tried to set a custom session variable when the user login. However it work barely because my custom session would expire before the session set by Yii.
Any help would be appreciated.

A: You are using a Framework with mvc pattern so controllers are preferred way to route requests .As per your problem i would suggest you to use htaccess file to do the routing to the required file and handle other files by Yii

A: copy code from existing source to new Yii Controler/Action ... done :D

A: Because of the way the script is written I've only been able to find one way of doing this. It will involve re-writing some elements of the script.

*

*Save the filemanager in protected/vendors.

*You need a controller to handle the routing of the request. This will also give you the access control that you need. Call it FileUpload and create it where you normally create controllers in your project. Right at the start of the controller, before the class is declared, import the fileUpload files from it's previously saved location; Yii::import('application.vendors.*');

*You need an action to handle the incoming request. Call this actionIndex. Give it the following code.
public function actionIndex() {
    //Start capturing the output from the script
    ob_start();
    require_once('filemanager/dialog.php');

    //Finish capturing output, and save to a variable
    $output = ob_end_clean();
    $this->render('index', array('output' => $output));
}

*Then you need a view file. Call it 'output.php' and it just contains one line; <?php echo $output; ?>
This will render the html generated by the script, and hopefully contain it within your existing template.
Your first problem is that the script sends headers which aren't discarded by ob_start. You will need to delete these from the script. It also starts a session, which will throw an error 'Session already started', which can be cured by changing the first line of config.php to
if(!isset($_SESSION))
    {
        session_start();
    }

Your next problem will be that none of the scripts and stylesheets are loaded, because the vendor hasn't used relative filepaths, and also because you've just deleted the headers. You will need to re-write lots of the script to include the necessary files. Fortunately, you now have access to Yii functions, so can use the asset manager to publish all the js and css files needed by the script.
Your final (hopefully!) problem will be the urls used by the script page. Currently they are all pointing to files within the script. You will need to rewrite these to use Yii routing. Fortunately, inside the main file dialog.php you should have access to all the normal Yii functions, so you can set $baseUrl as $this->createUrl() etc. If you need to add extra actions to the controller you can follow the pattern above to call other files, like the upload.php file in the script.
Hope that all works for you!


text:
Q: plpgsql code that worked in postgresql 8.3 fails in 9.2 I have a problem with an array parameter going into a plpgsql function.  My code works in PostgreSQL 8.3, but fails when called on a 9.2.1 server.
I have written a dummy function that shows the problem.  This is based on some of the first plpgsql code I have written.  I know it is ugly, so if it is not possible to escape my quotes in a way that works for both server versions, I am open to suggestions on rewriting this code so that it works on both server versions.  Actually I am open to suggestions no matter what.  I am not too good at plpgsql
So here's the dummy code that demonstrates the problem:
CREATE OR REPLACE FUNCTION get_test(collection text[])
  RETURNS text AS
$BODY$
DECLARE
counter int8; directive text; condition text; querytype text;
BEGIN
    counter = array_lower(collection, 1);
    WHILE (counter <= array_upper(collection, 1)) LOOP
        SELECT INTO directive  "?column?"[counter] FROM (SELECT collection) AS foo ;
        counter = counter + 1;
        SELECT INTO condition  "?column?"[counter] FROM (SELECT collection) AS foo ;
        counter = counter + 1;
        SELECT into querytype  "?column?"[counter] FROM (SELECT collection) AS foo ;
        counter = counter + 1;
    END LOOP;
    RETURN 'dummy';
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION get_test(text[]) OWNER TO postgres;

The collection parameter is built in sets of three (a simple string, a SQL condition, and another string).  Here is an example call that works in 8.3 and fails in 9.2:
select * from get_test('{"dynamic","(tr.PROJECT_NAME = \'SampleProject\')","1"}')

This gives back 'dummy' as expected on 8.3, but fails on 9.2 with:
ERROR: syntax error at or near "SampleProject"
The caret points to the S of SampleProject, right after the single-quote, so I know I am
not escaping the single quotes in the embedded SQL correctly.
I have tried this without the backslashes in front of the single quotes, with two backslashes, and finally with two single quotes, all to no avail.  The original code is called by a Java client, but I have been testing this under pgadmin3 (version 1.16), connecting to two servers of the versions in question, trying different things.
Any ideas as to how I can make this call work?

A: Most likely reason is a different setting for standard_conforming_strings.
Try this call:
The SQL-standard way (and recommended in PostgreSQL) to escape single quotes inside a single-quoted string literal is to double them:
SELECT *
FROM get_test('{dynamic,(tr.PROJECT_NAME = ''SampleProject''),1}'::text[])

OR:
SELECT *
FROM get_test('{dynamic,"(tr.PROJECT_NAME = ''SampleProject'')",1}'::text[])

Or you can resort to dollar-quoting to avoid multiple layers of escaping quotes
SELECT *
FROM get_test($${dynamic,"(tr.PROJECT_NAME = 'SampleProject')",1}$$::text[])

Or even an ARRAY constructor:
SELECT *
FROM get_test(ARRAY['dynamic','(tr.PROJECT_NAME = ''SampleProject'')','1'])

redpajama_set_name: RedPajamaStackExchange


text:
Q: apk installation error : INSTALL_FAILED_DEXOPT I am getting following error while installing apk on device:
10-03 20:17:35.012: I/PackageManager(11692): Running dexopt on: package name
10-03 20:17:35.932: E/dalvikvm(19729): outsSize (9) > registersSize (8)
10-03 20:17:35.932: E/dalvikvm(19729): Trouble with item 904 @ offset 0x33174
10-03 20:17:35.932: E/dalvikvm(19729): Swap of section type 2001 failed
10-03 20:17:35.932: E/dalvikvm(19729): ERROR: Byte swap + verify failed
10-03 20:17:35.971: E/dalvikvm(19729): Optimization failed
10-03 20:17:36.001: W/installd(39): DexInv: --- END '/data/app/packagename-1.apk' --- status=0xff00, process failed
10-03 20:17:36.001: E/installd(39): dexopt failed on '/data/dalvik-cache/data@app@package-1.apk@classes.dex' res = 65280


text:
Q: VBScript/Classic ASP permission denied with fso.OpenTextFile after several uses I have a process that loops through a moderate amount of data (1MB) storing it in an array and then periodically writes it to the disk.  After several iterations, the script fails at fso.OpenTextFile() in my else section as though the file has not been closed or finished closing from the previous time the function was called.  The iteration # doesn't seem to be specific as it's happened anywhere between the 2nd and 10th iteration that I can tell.  The file is actually created and being appended to so it doesn't appear to be a permissions issue.  I considering adding a time delay to the process but don't want to necessarily add overhead to an already long process.
OS:  Windows 2012 R2
Any thoughts or suggestions appreciated.
'Write array to disk
sub writeFile()
        'on error resumenext
        set fso = Server.CreateObject("Scripting.FileSystemObject")
        if needToCreateFile then
            set objTextFile = fso.CreateTextFile(server.mappath("google/linklist.html"),true)
            objTextFile.writeLine("<!DOCTYPE html>")
            objTextFile.writeLine("")
            objTextFile.writeLine("<title>")
            objTextFile.writeLine("Content Listing")
            objTextFile.writeLine("</title>")
            needToCreateFile = false
        else
            ' OpenTextFile Method needs a Const value
            ' ForAppending = 8 ForReading = 1, ForWriting = 2
            Set objTextFile = fso.OpenTextFile (filename, ForAppending, True)
        end if

        'Write contents of array to file
        for each link in linkList
            if link <>"" and not isNull(link) then
                objTextFile.writeLine(link & "
")
            end if
        next
        objTextFile.writeLine("")
        objTextFile.Close
        set fso = nothing
        set objTextFile = nothing
        'on  error goto 0

end sub

Follow Up - Solved
Adding a 3 second delay solved the problem, but significantly delayed the processing time.  So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay.
sub writeFile()

        if needToCreateFile then
            set objTextFile = fs.CreateTextFile(server.mappath("google/linklist.html"),true)
            objTextFile.writeLine("<!DOCTYPE html>")
            objTextFile.writeLine("")
            objTextFile.writeLine("<title>")
            objTextFile.writeLine("Content Listing")
            objTextFile.writeLine("</title>")
            needToCreateFile = false
        end if

        'Write contents of array to file
        for each link in linkList
            if link <>"" and not isNull(link) then
                objTextFile.writeLine(link & "
")
            end if
        next
        objTextFile.writeLine("")
       ' objTextFile.Close
       ' set fso = nothing
       ' set objTextFile = nothing
end sub

A: Adding a 3 second delay solved the problem, but significantly delayed the processing time. So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay.  See modified script above.


text:
Q: sppsvc Error 5: Access Denied Recently, my PC started having an issue. sppsvc would fail to load. When trying to manually initiate it, I would get an Error 5: Access is Denied message.
Now, I used EventVwr and Process Monitor to see what's going on. This suspicious little message made me wonder:

Upon exploring that file, I realized that something was horribly wrong. I can't copy it or do anything to it without needing admin permissions which would always loop ("You need permission from Administrator" > "You need permission from NETWORK SERVICE"). Doing additional testing, I figured out that I can't even open the file. It's like it's just there but can't have anything done to it.
I tried fixing permissions myself. Output of ICACLS on this file:
C:\Windows\System32\spp\store\2.0>ICACLS data.dat
data.dat BUILTIN\Administrators:(F)
         NT SERVICE\sppsvc:(F)
         NT AUTHORITY\SYSTEM:(F)
         BUILTIN\Users:(R)

Successfully processed 1 files; Failed processing 0 files

C:\Windows\System32\spp\store\2.0>
I am unsure on how to proceed. I am also unsure if this file even really exists. What would happen if I were to delete it?

Yes, I know that "reinstalling Windows" would probably be the best option, but it is one I am not able to do. I am willing to do anything to my system as long as:

*

*I never format the OS

*I don't expose myself to every virus ever made in the history of ever.


text:
Q: .gif image display using OpenGl Can I display *.gif image in openGL?
I want to use it like texture of glQuad display list.
glNewList(base+loop,GL_COMPILE);                // Start Building A List
            glBegin(GL_QUADS);                          // Use A Quad For Each Character
                glTexCoord2f(cx,1-cy-0.0625f);          // Texture Coord (Bottom Left)
                glVertex2i(0,0);                        // Vertex Coord (Bottom Left)
                glTexCoord2f(cx+0.0625f,1-cy-0.0625f);  // Texture Coord (Bottom Right)
                glVertex2i(16,0);                       // Vertex Coord (Bottom Right)
                glTexCoord2f(cx+0.0625f,1-cy);          // Texture Coord (Top Right)
                glVertex2i(16,16);                      // Vertex Coord (Top Right)
                glTexCoord2f(cx,1-cy);                  // Texture Coord (Top Left)
                glVertex2i(0,16);                       // Vertex Coord (Top Left)
            glEnd();                                    // Done Building Our Quad (Character)
            glTranslated(10,0,0);                       // Move To The Right Of The Character
        glEndList();

Thx
I m using yhis libraries
#include <windows.h>        // Header File For Windows
#include <stdio.h>          // Header File For Standard Input/Output
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sstream>
//#include "glut.h"
#include <gl\gl.h>          // Header File For The OpenGL32 Library
#include <gl\glu.h>         // Header File For The GLu32 Library
#include <gl\glut.h>
#include <gl\glaux.h>

A: I recommend you to use SFML - it supports lot of image formats and image loading/processing is made simple with it. Here's an example application with textured cube using SFML:
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    // Create main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML OpenGL");
    App.PreserveOpenGLStates(true);

    // Create a sprite for the background
    sf::Image BackgroundImage;
    if (!BackgroundImage.LoadFromFile("datas/opengl/background.jpg"))
        return EXIT_FAILURE;
    sf::Sprite Background(BackgroundImage);

    // Load an OpenGL texture.
    // We could directly use a sf::Image as an OpenGL texture (with its Bind() member function),
    // but here we want more control on it (generate mipmaps, ...) so we create a new one
    GLuint Texture = 0;
    {
        sf::Image Image;
        if (!Image.LoadFromFile("datas/opengl/texture.jpg"))
            return EXIT_FAILURE;
        glGenTextures(1, &Texture);
        glBindTexture(GL_TEXTURE_2D, Texture);
        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr());
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    }

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glClearDepth(1.f);

    // Setup a perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.f, 1.f, 1.f, 500.f);

    // Bind our texture
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, Texture);
    glColor4f(1.f, 1.f, 1.f, 1.f);

    // Create a clock for measuring the time elapsed
    sf::Clock Clock;

    // Start game loop
    while (App.IsOpened())
    {
        // Process events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();

            // Escape key : exit
            if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
                App.Close();

            // Adjust the viewport when the window is resized
            if (Event.Type == sf::Event::Resized)
                glViewport(0, 0, Event.Size.Width, Event.Size.Height);
         }

        // Draw background
        App.Draw(Background);

        // Clear depth buffer
        glClear(GL_DEPTH_BUFFER_BIT);

        // Apply some transformations
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(0.f, 0.f, -200.f);
        glRotatef(Clock.GetElapsedTime() * 50, 1.f, 0.f, 0.f);
        glRotatef(Clock.GetElapsedTime() * 30, 0.f, 1.f, 0.f);
        glRotatef(Clock.GetElapsedTime() * 90, 0.f, 0.f, 1.f);

        // Draw a cube
        glBegin(GL_QUADS);

            glTexCoord2f(0, 0); glVertex3f(-50.f, -50.f, -50.f);
            glTexCoord2f(0, 1); glVertex3f(-50.f,  50.f, -50.f);
            glTexCoord2f(1, 1); glVertex3f( 50.f,  50.f, -50.f);
            glTexCoord2f(1, 0); glVertex3f( 50.f, -50.f, -50.f);

            glTexCoord2f(0, 0); glVertex3f(-50.f, -50.f, 50.f);
            glTexCoord2f(0, 1); glVertex3f(-50.f,  50.f, 50.f);
            glTexCoord2f(1, 1); glVertex3f( 50.f,  50.f, 50.f);
            glTexCoord2f(1, 0); glVertex3f( 50.f, -50.f, 50.f);

            glTexCoord2f(0, 0); glVertex3f(-50.f, -50.f, -50.f);
            glTexCoord2f(0, 1); glVertex3f(-50.f,  50.f, -50.f);
            glTexCoord2f(1, 1); glVertex3f(-50.f,  50.f,  50.f);
            glTexCoord2f(1, 0); glVertex3f(-50.f, -50.f,  50.f);

            glTexCoord2f(0, 0); glVertex3f(50.f, -50.f, -50.f);
            glTexCoord2f(0, 1); glVertex3f(50.f,  50.f, -50.f);
            glTexCoord2f(1, 1); glVertex3f(50.f,  50.f,  50.f);
            glTexCoord2f(1, 0); glVertex3f(50.f, -50.f,  50.f);

            glTexCoord2f(0, 1); glVertex3f(-50.f, -50.f,  50.f);
            glTexCoord2f(0, 0); glVertex3f(-50.f, -50.f, -50.f);
            glTexCoord2f(1, 0); glVertex3f( 50.f, -50.f, -50.f);
            glTexCoord2f(1, 1); glVertex3f( 50.f, -50.f,  50.f);

            glTexCoord2f(0, 1); glVertex3f(-50.f, 50.f,  50.f);
            glTexCoord2f(0, 0); glVertex3f(-50.f, 50.f, -50.f);
            glTexCoord2f(1, 0); glVertex3f( 50.f, 50.f, -50.f);
            glTexCoord2f(1, 1); glVertex3f( 50.f, 50.f,  50.f);

        glEnd();

        // Draw some text on top of our OpenGL object
        sf::String Text("This is a rotating cube");
        Text.SetPosition(250.f, 300.f);
        Text.SetColor(sf::Color(128, 0, 128));
        App.Draw(Text);

        // Finally, display the rendered frame on screen
        App.Display();
    }

    // Don't forget to destroy our texture
    glDeleteTextures(1, &Texture);

    return EXIT_SUCCESS;
}

Note: And do not use glaux - it is terribly lost in time.
Note: demo uses .jpg image format. This one is better than .gif, because it is more lightweight and, afaik, widespreaded and easier to implement in application.

A: It's kind of overkill if you just want to support GIF, but DevIL supports GIF (among many others). There are lighter solutions around as well. Alternatively, you can get the GIF spec, and write it yourself (makes a nice, relaxing afternoon project as I recall).


text:
Q: Creating a Maven release containing multiple files & direcories How can I create a multiple files release using Maven? I.e. the release of my application need to be given as a set of directories and files within them, e.g. like a installed JBoss directory structure. How it is possible to do this with Maven? I could produce the main jar file of the application. I have to give it inside a release direcotory, within which there can be a number of other directories like the dependent libs direcotry and some application specific directories.

A: The maven-assembly-plugin serves this purpose. You add a src/main/assembly directory to your main project into which you put one or more assembly descriptors. These define what files, dependencies and project modules go into the artifact, using which filtering properties, encoding and line endings. The end result can be a zip or a compressed tar file. If you need more than one package (e.g. Windows and Linux), create multiple assembly-*.xml files.


text:
Q: Unable to create MongoClient bean in springboot from appContext.xml: credential type conversion I have an existing Java library that uses MongoDB Spring. The library contains applcationContext.xml and config.properties files that configures it to connect to a remote MongoDB instance and does so correctly.
I am trying to use this library in a SpringBoot application, using the exact same two files, but SpringBoot seems to have trouble wiring up the MongoDB client, exception below.  Here is my application class/configuration:
@SpringBootApplication
@ImportResource({"applicationContext.xml"})
public class MySpringBootApplication {

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

}

Here is the exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'com.mongodb.MongoCredential[]' for property 'credentials'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.mongodb.MongoCredential' for property 'credentials[0]': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at org.MyCompany.MySpringBootApplication.main(MySpringBootApplication.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'com.mongodb.MongoCredential[]' for property 'credentials'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.mongodb.MongoCredential' for property 'credentials[0]': no matching editors or conversion strategy found
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:605)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:617)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:216)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1577)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1536)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    ... 20 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.mongodb.MongoCredential' for property 'credentials[0]': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:306)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:143)
    at org.springframework.beans.TypeConverterDelegate.convertToTypedArray(TypeConverterDelegate.java:503)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:216)
    at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:590)
    ... 26 more

The applicationContext.xml has the following config for mongoDB:
<context:property-placeholder
  location="classpath:config.properties" />
<mongo:mongo-client
  id="mongo"
  replica-set="${mongo.replica.set}"
  credentials="${mongo.credentials}" />

Where config.properties has the values for mongo.credentials.
I have used spring-boot-mongodb and added the configuration and connected successfully, but there are many dozens of other beans configured in that file that I am not sure how to wire up in SpringBoot that depend on the mongoClient. It would be much faster (I hope) to figure out how to tell SpringBoot to create the MongoCredential correctly.
Do I need to implement a StringToMongoCredentialConverter? Or am I doomed to pull everything in applicationContext.xml to some Java config class?
Using spring-boot 1.5.4, spring-core 4.3.9, spring-data-mongo 1.9.2

A: Per the answer in Connecting to MongoDB 3.0 with Java Spring, ended up replacing the  element with the following:
<!-- Seeds -->
<bean id="mongoSeedListID" class="java.util.ArrayList">
<constructor-arg>
    <list>
        <ref bean="mongoSeedlID" />
    </list>
</constructor-arg>
</bean>

<bean id="mongoSeedlID" class="com.mongodb.ServerAddress">
        <constructor-arg type="java.lang.String" name="host" value="DATABASE_HOST" />
        <constructor-arg type="int" name="port" value="DATABASE_PORT" />
</bean>

<!-- Credentials -->
<bean id="mongoCredentialListID" class="java.util.ArrayList">
<constructor-arg>
    <list>
        <ref bean="mongoCredentialID" />
    </list>
</constructor-arg>
</bean>

<bean id="mongoCredentialID" class="com.mongodb.MongoCredential">
        <constructor-arg name="mechanism" value = "#{T(com.mongodb.AuthenticationMechanism).SCRAM_SHA_1}" />
        <constructor-arg type="java.lang.String" name="userName" value="DATABASE_USERNAME" />
        <constructor-arg type="java.lang.String" name="source" value="DATABASE_SOURCE" />
        <constructor-arg type="char[]" name="password" value="DB_USER_PASS" />
</bean>

<!-- MongoClient -->
<bean id="mongoClientID" class="com.mongodb.MongoClient">
        <constructor-arg ref="mongoSeedListID" />
        <constructor-arg ref="mongoCredentialID"  />
</bean>

and it worked!


text:
Q: how to use $.post() to send request and add data to database in yii2 I would like to achieve something like these below code. just that the code is making a request from the database, i want to send request to the database
$.post( "/trobay/categories/default/lists?parent_id="+$(this).val(), function( data ) {

how to send request adding attribute name and attribute value to be save in DB
below is my code i have already
    <?php
  $script = <<< JS
  $(document).ready(function(){
    //setup before functions
         var typingTimer;
         var doneTypingInterval = 3000;
         var \$TitleInput = $('#product-product_title');

         //on keyup, start the countdown

        \$TitleInput.on('keyup input change paste',function(){
            clearTimeout(typingTimer);
            if (\$TitleInput.val()) {
                typingTimer = setTimeout(doneTyping, doneTypingInterval);
            }
        });

         //user is "finished typing," do something
         function doneTyping () {

             data = \$TitleInput.val();

                 $.ajax({
        url: '/trobay/draft/create',
        type: 'POST',
        data: data,
        success: function (data) {
                      alert(data)
            },
            error: function(jqXHR, errMsg) {
             // handle error
                alert(errMsg);
            }
        });

         }

  });
 JS;
 $this->registerJs($script);
 ?>

in my controller i have this
public function actionCreate()
{
    $model = new Draft();

    if ($model->load(Yii::$app->request->post())) {
        $model->created_at = \time();
        if($model->save()){
            return draftId;
        }else{
            return '0';
        }

    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

and in my view i have this
<?php $form = ActiveForm::begin(['id'=>$model->formName(),
                                          'enableClientValidation'=> true,
                                          'fieldConfig' => ['template' => '{label}{input}{hint}']]); ?>

              <?= $form->field($model, 'product_title')->textInput([
                'class'=>'title-input',
                'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
                ])->label(false) ?>

      E.g Men's blue addidas glide running shoes size 11

    <?= $form->field($model, 'user_id')->textInput() ?>

<?= $form->field($model, 'product_title')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>

<?= $form->field($model, 'category_id')->textInput() ?>

Now my question is I just want to grab the value of each field input and send it to server side for save in the DB without having to submit the whole form
The about JS code works enough to get the value but how do i send this to the server for save up

A:     //user is "finished typing," do something
    function doneTyping () {
        data = \$TitleInput.val();
        $.ajax({
              url: '/trobay/draft/create',
              type: 'POST',
              data: {title: data}
              success: function (data) {
                       alert(data)
              },
              error: function(jqXHR, errMsg) {
                    // handle error
                    alert(errMsg);
              }
        });
    });

If you need to send more key value just add those as comma seperated value like
data: {title: data, attr:"value"}

and so on...and you can receive this value as post parameter in your controller.


text:
Q: How to permanently allow an RDS instance to connect to my server? I'm using an Amazon RDS instance as a slave to replicate my bare metal MySQL server, as a backup.
I'm authorizing the RDS  instance's IP in my server's firewall this way:
# iptables \
  --insert INPUT \
  --source xxxxxxx.yyyyyyy.eu-west-1.rds.amazonaws.com \
  --protocol tcp \
  --destination-port mysql \
  --jump ACCEPT

This works fine, however iptables resolves the instance's host to its EC2 counterpart, and stores this one instead:
# iptables --list
...

ACCEPT  tcp  --  ec2-x-x-x-x.eu-west-1.compute.amazonaws.com  anywhere  tcp  dpt:mysql

The problem is, whenever the RDS instance is restarted/modified/upgraded, it's usually moved to another EC2 instance, so even though the *.rds.amazonaws.com host stays the same, the *.compute.amazonaws.com host changes, and the RDS instance loses the connection to my server.
The solution involves, right now, a manual intervention from me to re-issue the iptables command.
Is there a solution to permanently allow incoming connections from an IP, as long as a domain in the firewall configuration resolves to this IP?
I'd accept a solution involving firewalld as well.

A: No. (Linux) firewalls are IP driven, not domain name driven, and and domains used are resolved when the firewall is loaded/reloaded - to do otherwise would massively impact performance.
Firewalld won't help as its a really a wrapper around iptables.
You may have some luck by frequently reloading the firewall rules or doing checks and removing and reading the appropriate rule if changes occur using a script (eg via crontab).


text:
Q: How to clone Azure DevOps repository using VS2019 I just installed a fresh copy of VS2019 Pro on a new Windows 10 Pro machine.  My issue is that I'm unable to clone repos from Azure Devops.  It creates a local folder and then hangs.  It never does anything after that.
I have done the following to troubleshoot:

*

*Installed Git for Windows

*Verified that my firewall is not blocking anything using a MS tesst page I found via a troubleshooting page.

*Deleted all cookies from all browser as the troubleshooter suggested.

*Tried both the old VisualStudio.com and dev.azure.com server URLS when making a connection    via the Team menu.

*Tried using Git for Windows to clone but get the same results  as in VS2019.

However, I still get nothing but an empty folder.  The Team Explorer tells me it is "Initiating clone..." and the output pane says it's cloning to the local path that I entered but never gets any further.  And there's no other messages that I can find to tell me what's going on.
So I'm not sure if I missed a setup step or if this is related to something in DevOps that wasn't necessary  for the old Visualstudio.com repos.
Would someone please suggest a way I can further troubleshoot this issue, or let me know what I've missed during setup?

A: This issue turned out to be that another software programs on my machine (a screen reader named JAWS 2019) was somehow blocking communication with the DevOps server.  As soon as I turned it off everything DevOps releated began to act normally again - including cloning and creating repos.
Thanks to all who commented.
-Dan


text:
Q: Need help in string parsing (regex) I hava a string cd   /Users/bob/temp and I need to parse it to a string array, but

*

*my input string may begin by any number of spaces (    cd)

*between "cd" and path can be any number of spaces (cd
/Users/bob/temp)

*path may contain any character, including dor       (for hidden
directories)

My try String[] exp = action.split("^cd++[\\w\\W]*");

A: I think that you can use the method split() on your String :
String s = cd /Users/bob/temp;
String[] split = s.split("/");

A: First, I assume that your tokens are cd and /path/to\ my/foo/bar.
When it comes to escaping, regular expressions aren't the best approach as they get slow and unclear. Writing a parser is usually a better way to go.
Since your string looks like bash snippet (which allows the escaping), you might rather want to take the parser way.


text:
Q: Pointer value exceeds available memory? How? I work on Peano-Hilbert data ordering (c++ 4.9, linux 64x) to coalesce dynamically allocated memory. For control I am trying to visualize the actual data distribution in the memory. For this I convert pointers to my data to integers like follows
unsigned long int address =  *(unsigned long int*)(&pointer);

and then plot them as some 2D-map. It works fine for most of the case but sometimes I get values exceeding by far available memory, e.g. 140170747903888, which corresponds ~127 TB shift whereas I have only 16 GB of RAM. What the hell?

A: The memory management system does not handle memory in a linear way. It is free to tell a process that some memory block is in the address 0x1234123412345678, even if you only had 128MB of memory. This is called paging. The data might not even be in physical memory, but pages out to disk.
This means that you have no way of knowing where in physical memory anything is from the pointer value, since it might change all the time (or it might not even be in memory), you only know the virtual address the OS has happened to give you. And it is totally implementation dependent how it gives them out.

A: AMD 64 bit uses 48 bits for virtual memory addresses, which corresponds to 256TB.  Virtual address space is distinct from physical RAM: the addresses are looked up in a table on the CPU and actual RAM faulted in when the pages in question are first accessed.


text:
Q: Roll back A if B goes wrong. spring boot, jdbctemplate I have a method, 'databaseChanges', which call 2 operations: A, B in iterative way. 'A' first, 'B' last.
'A' & 'B' can be Create, Update Delete functionalities in my  persistent storage, Oracle Database 11g.
Let's say,
'A' update a record in table Users, attribute zip, where id = 1.
'B' insert a record in table hobbies.
Scenario: databaseChanges method is been called, 'A' operates and update the record. 'B' operates and try to insert a record, something happen, an exception is been thrown, the exception is bubbling to the databaseChanges method.
Expected: 'A' and 'B' didn't change nothing. the update which 'A' did, will be rollback. 'B' didn't changed nothing, well... there was an exception.
Actual: 'A' update seems to not been rolled back. 'B' didn't changed nothing, well... there was an exception.

Some Code
If i had the connection, i would do something like:
private void databaseChanges(Connection conn) {
   try {
          conn.setAutoCommit(false);
          A(); //update.
          B(); //insert
          conn.commit();
   } catch (Exception e) {
        try {
              conn.rollback();
        } catch (Exception ei) {
                    //logs...
        }
   } finally {
          conn.setAutoCommit(true);
   }
}

The problem: I don't have the connection (see the Tags that post with the question)
I tried to:
@Service
public class SomeService implements ISomeService {
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate npjt;

    @Transactional
    private void databaseChanges() throws Exception {
        A(); //update.
        B(); //insert
    }
}

My AppConfig class:
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

@Configuration
public class AppConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(dataSource);
    }
}

'A' makes the update. from 'B' an exception is been thrown. The update which been made by 'A' is not been rolled back.
From what i read, i understand that i'm not using the @Transactional correctly.
I read and tried several blogs posts and stackverflow Q & A without succeess to solve my problem.
Any suggestions?

EDIT
There is a method that call databaseChanges() method
public void changes() throws Exception {
    someLogicBefore();
    databaseChanges();
    someLogicAfter();
}

Which method should be annotated with @Transactional,
changes()? databaseChanges()?

A: @Transactional annotation in spring works by wrapping your object in a proxy which in turn wraps methods annotated with @Transactional in a transaction. Because of that annotation will not work on private methods (as in your example) because private methods can't be inherited => they can't be wrapped (this is not true if you use declarative transactions with aspectj, then proxy-related caveats below don't apply).
Here is basic explanation of how @Transactional spring magic works.
You wrote:
class A {
    @Transactional
    public void method() {
    }
}

But this is what you actually get when you inject a bean:
class ProxiedA extends A {
   private final A a;

   public ProxiedA(A a) {
       this.a = a;
   }

   @Override
   public void method() {
       try {
           // open transaction ...
           a.method();
           // commit transaction
       } catch (RuntimeException e) {
           // rollback transaction
       } catch (Exception e) {
           // commit transaction
       }
   }
}

This has limitations. They don't work with @PostConstruct methods because they are called before object is proxied. And even if you configured all correctly, transactions are only rolled back on unchecked exceptions by default. Use @Transactional(rollbackFor={CustomCheckedException.class}) if you need rollback on some checked exception.
Another frequently encountered caveat I know:
@Transactional method will only work if you call it "from outside", in following example b() will not be wrapped in transaction:
class X {
   public void a() {
      b();
   }

   @Transactional
   public void b() {
   }
}

It is also because @Transactional works by proxying your object. In example above a() will call X.b() not a enhanced "spring proxy" method b() so there will be no transaction. As a workaround you have to call b() from another bean.
When you encountered any of these caveats and can't use a suggested workaround (make method non-private or call b() from another bean) you can use TransactionTemplate instead of declarative transactions:
public class A {
    @Autowired
    TransactionTemplate transactionTemplate;

    public void method() {
        transactionTemplate.execute(status -> {
            A();
            B();
            return null;
        });
    }

...
}

Update
Answering to OP updated question using info above.

Which method should be annotated with @Transactional:
  changes()? databaseChanges()?

@Transactional(rollbackFor={Exception.class})
public void changes() throws Exception {
    someLogicBefore();
    databaseChanges();
    someLogicAfter();
}

Make sure changes() is called "from outside" of a bean, not from class itself and after context was instantiated (e.g. this is not  afterPropertiesSet() or @PostConstruct annotated method). Understand that spring rollbacks transaction only for unchecked exceptions by default (try to be more specific in rollbackFor checked exceptions list).

A:
Any RuntimeException triggers rollback, and any checked Exception does not.

This is common behavior across all Spring transaction APIs. By default, if a RuntimeException is thrown from within the transactional code, the transaction will be rolled back.  If a checked exception (i.e. not a RuntimeException) is thrown, then the transaction will not be rolled back.
It depends on which exception you are getting inside databaseChanges function.
So in order to catch all exceptions all you need to do is to add rollbackFor = Exception.class
The change supposed to be on the service class, the code will be like that:
@Service
public class SomeService implements ISomeService {
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate npjt;

    @Transactional(rollbackFor = Exception.class)
    private void databaseChanges() throws Exception {
        A(); //update
        B(); //insert
    }
}

In addition you can do something nice with it so not all the time you will have to write rollbackFor = Exception.class. You can achieve that by writing your own custom annotation:
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor = Exception.class)
@Documented
public @interface CustomTransactional {
}

The final code will be like that:
@Service
public class SomeService implements ISomeService {
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate npjt;

    @CustomTransactional
    private void databaseChanges() throws Exception {
        A(); //update
        B(); //insert
    }
}

A: The first code you present is for UserTransactions, i.e. the application has to do the transaction management. Usually you want the container to take care of that and use the @Transactional annotation. I think the problem in you case might be, that you have the annotation on a private method. I'd move the annotation to the class level
@Transactional
public class MyFacade {

public void databaseChanges() throws Exception {
    A(); //update.
    B(); //insert
}

Then it should rollback properly. You can find more details here
Does Spring @Transactional attribute work on a private method?

A: Try this:
@TransactionManagement(TransactionManagementType.BEAN)
public class MyFacade {

@TransactionAttribute(TransactionAttribute.REQUIRES_NEW)
public void databaseChanges() throws Exception {
    A(); //update.
    B(); //insert
}

A: What you seem to be missing is a TransactionManager. The purpose of the TransactionManager is to be able to manage database transactions. There are 2 types of transactions, programmatic and declarative. What you are describing is a need for a declarative transaction via annotations.
So what you need to be in place for your project is the following:
Spring Transactions Dependency (Using Gradle as example)
compile("org.springframework:spring-tx")

Define a Transaction Manager in Spring Boot Configuration
Something like this
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource)
{
    return new DataSourceTransactionManager(dataSource);
}

You would also need to add the @EnableTransactionManagement annotation (not sure if this is for free in newer versions of spring boot.
@EnableTransactionManagement
public class AppConfig {
...
}

Add @Transactional
Here you would add the @Transactional annotation for the method that you want to participate in the transaction
@Transactional
public void book(String... persons) {
    for (String person : persons) {
        log.info("Booking " + person + " in a seat...");
        jdbcTemplate.update("insert into BOOKINGS(FIRST_NAME) values (?)", person);
    }
};

Note that this method should be public and not private. You may want to consider putting @Transactional on the public method calling databaseChanges().
There are also advanced topics about where @Transactional should go and how it behaves, so better to get something working first and then explore this area a bit later:)
After all these are in place (dependency + transactionManager configuration + annotation), then transactions should work accordingly.
References
Spring Reference Documentation on Transactions
Spring Guide for Transactions using Spring Boot - This has sample code that you can play with


text:
Q: Ubuntu 18.04 Connected to Wi-Fi but no internet? I just installed Ubuntu on my laptop and I've been having some issues connecting to the internet. When I login to my account, the UI tells me I am connected to my Wi-Fi network, however when I open Firefox and try to go to Google, I get a message telling me I am not connected to the internet.
Lots of solutions on here tell people to type sudo service network-manager restart into the terminal, but that doesn't work at all for me. In fact once I type that, the computer cannot see any Wi-Fi networks at all until I reboot.
I made sure that my Wi-Fi password is correct, and I have tried rebooting several times. Any help would be amazing.
Thanks!

A: I had this issue  that I can connect to the router but can't connect to other sites (when Im connected to wifi) and it keep saying resolving host and if I switched to the wired connection, internet worked correctly
to fix it I tried many answers, finally, I did the following
go to
sudo nano /etc/network/interfaces
the file should look like this
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

## comment out these things if you have them
#allow-hotplug eno1
#iface eno1 inet dhcp

A: Look at the Network Manager logs with journalctl $(type -p NetworkManager).
Use /sbin/ifconfig to find the name of your WiFi interface (I'll use wlan0 in the following example, replace wlan0 with your interface name). Use /usr/sbin/arp -an to find the IP address of your router. (I'll use 11.22.33.44 in the example)
sudo ip route add default via 11.22.33.44 dev wlan0


text:
Q: struct termios unknown behavior in C With this code, when I take input, the input does not appear, when I comment it out it appears, what is this code doing below,
struct termios origConfig;
tcgetattr(0, &origConfig);
struct termios newConfig = origConfig;
newConfig.c_lflag &= ~(ICANON|ECHO);
newConfig.c_cc[VMIN] = 1;
newConfig.c_cc[VTIME] = 1;
tcsetattr(fileno(stdin), TCSANOW, &newConfig);

A: newConfig.c_lflag &= ~(ICANON|ECHO);

will reset the echo and canonical-input flags. If you don't want to reset the echo flag (but keep everything else), just use:
newConfig.c_lflag &= ~(ICANON);

altough you may also want to examine how the canonical-input flag works as well. For example, see the Linux termios man page.
In any case, it may be unwise to use one without the other since one of the major use cases on non-canonical input is things like editors, where you don't want characters echoed.
Non-caconical input gives you each character as it's typed (rather than an entire line when you hit ENTER), ideal for editors. If your editor needs to handle things like CTRL-W to move forward one word, you probably don't want it banging the ^W in the middle of your screen display.
Instead, you'd want it to leave the output up to the program, rather than the terminal interface. Non-canonical, non-echo terminal I/O gives you much more power over the interface.

A: The tcsetattr() function controls the behavior of the user terminal. In this particular case, the code clears the ECHO flag in the control structure (newConfig.c_lflag &= ~ECHO does that), so what the user types isn't echoed back.


text:
Q: ChildBrowser on phonegap 2.2 and ios 6 (ipad) not working I'm trying to get ChildBrowser plugin work using phonegap 2.2 on iOS 6 and latest xCode. I followed official instructions in the plugin's github wiki/readme. It seems that the plugin is loading but when I call
window.plugins.childBrowser.showWebPage('http://www.google.com',{ showLocationBar: true });
nothing happens!
Any clue? Thoughts?
Thanks!

A: If you just get the "Loading..." message make sure you're referencing the childbrowser.js that came with the Ios ChildBrowser Plugin and not the one for another platform like Android. If you're not getting anything make sure you have "ChildBrowser" -> "ChildBrowserCommand" in Cordova.plist and NOT "ChildBrowser" -> "ChildBrowser.js". Also, make sure your device ready event is getting fired, I once accidentally copied cordova-2.2.0.js from an android project over to IOS which caused all events to stop getting fired.

A: There is an outstanding issue with iOS 6 for the ChildBrowser plugin.
You should be able to test to see if this is iOS6 specific. Run your app under an iOS5 simulator. If ChildBrowser works, then you know that you're hitting the iOS 6 specific problem.
A support issue has been opened, but I know of no solution yet...
https://github.com/phonegap/build/issues/55

A: 1) use build.phonegap.com
2) add the config.xml with following under assets\www folder
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns = "http://www.w3.org/ns/widgets"
    xmlns:gap = "http://phonegap.com/ns/1.0"
    id        = "com.phonegap.example"
    version   = "1.0.0">

<name>PhoneGap Build Application</name>

<description>
A simple PhoneGap Build application.
</description>

<author href="https://example.com" email="you@example.com">
Your Name
</author>
    <preference name="orientation"     value="portrait" />
<feature name="http://plugins.phonegap.com/ChildBrowser/2.0.1" />
<access origin="*" />
</widget>

3) remove all phonegap2.x.x.js and childbrowser2.x.x.js which is referred from that particular page where your using childbrowser features (like index.html)
then simply add the following even though it is not in the folders (phonegap builder will use the updated version)

4) just put the following for testing

Click here to open

Hope for the best :)


text:
Q: Angle between two vectors not in same plane I want to know how calculate the angle between two vectors and both are not in same plane, which means that they don't intersect at any point?
For example how do I calculate angle between AB and EF in this figure
https://docs.google.com/file/d/0B6ehLXK0eP7sV3ByekxQZlZnQ1U/edit
I also have a doubt about the dot product. Can it be only used when the two vectors lie in the same plane ??
Thank you
MN

A: You are confusing rays with vectors.  Vectors represent length and direction.  They are, thus, relative quantities.  To say that two vectors aren't in the same plane is meaningless, because they have no origin.  You can, however, say that two non-zero vectors always describe a plane.
Rays, on the other hand, have magnitude, direction, and origin, and certainly, the angle between them is well defined.  So, your question seems to be more about whether the dot product can be used to find the angle between two rays, and the short answer is, yes.
While you are correct that two rays might not lie on intersecting lines, you can always find two parallel rays that do lie on intersecting lines.  To see this, just draw a line segment from the origin of one ray, which we'll call ray A, to the origin of the other, which we'll call ray B.  Then, draw another line segment of equal length, starting from the "tip" of ray A parallel to the first line segment.  Finally, join the free ends of these two line segments, and you will get a ray parallel to ray A that shares its origin with ray B, as in the following crudely drawn picture:

Now, you have two co-planar rays, and you can use dot product confidently to your heart's content.  Just make sure that you use the vectors of the rays, and not their origins.

A: You find the angle between them using the dot product like you usually would. The thing is, even if you are imagining the vectors in different places in space they are defined as going through the origin.


text:
Q: Heat map from data file I have a file with data arranged in the following way:

...
0.051 0.056 0.269639
0.051 0.057 0.252626
0.051 0.058 0.23856
...

I'd like to plot an heat map and I've managed something like this:
ListDensityPlot[  Import["\HeatMap.txt", "Data"],   PlotRange -> All, ColorFunction -> Hue]

Wich gives me:

The problem is that I don't know what the colors are corresponding to in terms of values. Can I mark colors for specific value ranges? Or how can I find out how the color gradient is comparing to the values?
Also, there is a particular point of interest in the data, how can I show it?

A: ListDensityPlot[{{1, 1, 1, 1}, {1, 2, 1, 2}, {1, 1, 3, 1}, {1, 2, 1,
   4}}, PlotLegends -> Automatic,
 ColorFunction -> (Blend[{Yellow, Red}, #] &)]

Generates labels where the values in the plot range between Yellow and Red.
You can check the colour for the scale:
Blend[{Yellow, Red}, 0.5]

For instance gives the colour for the median value.

This epilogue finds the lowest value, (which in this case is of course not unique, but I needed an easy dataset)
data = Table[
   With[{r = RandomReal[{0, 5}],
     t = RandomReal[{0, 2 Pi}]}, {r Cos[t], r Sin[t],
     Sin[r^2]/r^2}], {10^4}];
ListDensityPlot[data, PlotRange -> All,
 ColorFunction -> (Blend[{Yellow, Red}, #] &),
 Epilog -> {Black, PointSize -> 0.01,
 Point[Flatten[MinimalBy[data, Last]][[1 ;; 2]]]}]


text:
Q: GET data from REST API using Azure Data Factory I am trying to get data from Pendo through REST API using Azure Data Factory. The PYTHON code for this activity is
import requests
url = "https://app.pendo.io/api/v1/aggregation"
data = "{\"response\":{\"mimeType\":\"application/json\"},\"request\":{\"pipeline\":[{\"source\":{\"guideEvents\":null,\"timeSeries\":{\"first\":\"1506977216000\",\"count\":-10,\"period\":\"dayRange\"}}}]}}"
headers = {
    'x-pendo-integration-key': "[add_your_pendo_int_key_here]",
    'content-type': "application/json"
}
response = requests.post(url, data = data, headers = headers)

How do I define the data part of the code through Azure Data Factory?
I've put the content-type and x-pendo-integration-key in the additional headers.

A: Problem solved. The data part of the PYTHON code(with out the \) is put in the Request Body of Copy Activity in Azure Data Factory and the Request Method is POST.

A: You can use HTTP Connector to retrieve data from HTTP endpoint. This HTTP connector is supported for the following activities:

*

*Copy activity with supported source/sink matrix

*Lookup activity
You can copy data from an HTTP source to any supported sink data store. For a list of data stores that Copy Activity supports as sources and sinks, see Supported data stores and formats.

Note: To test an HTTP request for data retrieval before you configure the HTTP connector in Data Factory, learn about the API specification for header and body requirements. You can use tools like Postman or a web browser to validate.
https://learn.microsoft.com/en-us/azure/data-factory/connector-http
Here is a sample Custom activity for POST:
{
    "name": "HttpSourceDataInput",
    "properties": {
        "type": "HttpFile",
        "linkedServiceName": {
            "referenceName": "<HTTP linked service name>",
            "type": "LinkedServiceReference"
        },
        "typeProperties": {
            "relativeUrl": "<relative url>",
            "requestMethod": "Post",
            "requestBody": "<body for POST HTTP request>"
        }
    }
}

You can check ADF related samples here.Also find this for additional reference.
Hope it helps.


text:
Q: Cannot find module 'models/PermissionModel' error when I try to require my javascript file I created a folder called models under my node server project
inside it a javascript file called PermissionModel.js
   var express = require('express');
var mongoose = require('mongoose');
var Schema=mongoose.Schema,
Objectid=Schema.Objectid;

var permissionSchema=new mongoose.Schema({
        docType:'string',
        permission:'array'

});
var PermissionModel=mongoose.model('permission',permissionSchema);

module.exports=PermissionModel;

then I try to import it inside my server.js file
var PermissionModel=require('models/PermissionModel');

when try to run my node project this error occured
Cannot find module 'models/PermissionModel'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/sankha/Documents/Projects/HealthApp/blu_kross_server/server.js:4:21)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

please help me to solve this
thank you very much!!

A: Change your require line to:
var PermissionModel=require('./models/PermissionModel');

If you don't put the . before the model, Node will look for the module only inside node_modules folder.
For further information read the docs of node, you can also ask google and find  this

A: inside your models directory create a file index.js
then export PermissionModel.js in your index.js file
exports.PermissionModel = require('./PermissionModel');

inside your server.js import the whole directory as below
var PermissionModel=require('./models');


text:
Q: Slow GUI performance using a  Radeon HD5770 I'm fresh Ubuntu user.
My PC is pretty fast (Phenom x4 3.6GHz/HD5770/4GB RAM) so i was very disappointed when firstly saw how laggy is the interface - lags when I try to move any window.
I think my problem is caused by graphics drivers but i have no idea how to resolve it...
I tried to install and uninstall fglrx on every way I found but it didn't help.
It's the same both on x64 and x86 Ubuntu.
(Sorry if my English is bad ;) )
I installed Propierty Drivers from Ubuntu system settings (jockey?) And from AMD website through console - both were the same laggy.
I think those were the newest one - AMD Catalyst™ 11.11 Proprietary Linux x86 Display Driver
I have noticed that everything runs smoothly when I run Ubuntu from LiveUSB
Setting "Sync to VBlank" to off in Compiz Manager doesnt help too...

A: Try to replace the Device block in your xorg.conf file with this one:
Section "Device"
 Identifier "ATI Radeon"
 Driver "ati"
 Option "AccelMethod" "EXA"
 Option "MigrationHeuristic" "greedy"
 Option "AccelDFS" "true"
 Option "EnablePageFlip" "true"
 Option "EnableDepthMoves" "true"
EndSection

It's working for me and I have very smooth windows!
Also save Sync to VBlank off and auto frame rate count in composite off too.

A: Initially, I would assume this is an apparently typical error with fglrx and compiz' 'sync to vblank'.
First, download 'CompizConfig Settings Manager', either through the Software Center or by running 'sudo apt-get install compizconfig-settings-manager' in a terminal. Next, open the manager through the dash and hit the OpenGL icon. You should see an option for 'Sync To VBlank' there. Try disabling it and see if it does any good. It did the trick for me.

A: I had the same issue here and I solved it by installing the original driver from ATI by downloading it from the official site.


text:
Q: FastText - Cannot load model.bin due to C++ extension failed to allocate the memory I'm trying to use the FastText Python API https://pypi.python.org/pypi/fasttext Although, from what I've read, this API can't load the newer .bin model files at https://github.com/facebookresearch/fastText/blob/master/pretrained-vectors.md as suggested in https://github.com/salestock/fastText.py/issues/115
I've tried everything that is suggested at that issue, and furthermore https://github.com/Kyubyong/wordvectors doesn't have the .bin for English, otherwise the problem would be solved. Does anyone know of a work-around for this?

A: Try the following steps to solve the issue. Its worked with me for Python 3.5 while loading a language identification model.
git clone https://github.com/facebookresearch/fastText.git
cd fastText
pip install .

A: You can't use the package fasttext installed by pip. You use install fastText (capital T) from fasttext repo.

A: This error generally comes because of the version mismatch. Make sure you are using the same version of fasttext during the training and model loading time.

A: The package you are looking for is not on PyPI yet. You have to install it yourself by cloning the original repo and running the install script.
There is, however, an up-to-date version in  PyPi Test which you can test and use.
You can also use this mirror, which has a copy of the official package you are looking for.

A: you may try pyfasttext instead:
!pip3 install pyfasttext
from pyfasttext import FastText
model = FastText("./model_position")

works, but some compatibility problems, e.g. you may use model.args["dim"] to replace get_dimension()


text:
Q: Accessing a linux file content through an url I want to access a Linux file content through an url. When we access the url we can see the content of that file being displayed in the screen. Is there any procedure to do this.

A: If you have a file with path /x/y/z, curl can use the file:// protocol to do that:
curl file:///x/y/z

Example:
$ curl file:///etc/hosts
#
# /etc/hosts: static lookup table for host names
#

#<ip-address>   <hostname.domain.org>   <hostname>
127.0.0.1   localhost.localdomain   localhost
::1     localhost.localdomain   localhost


text:
Q: Error: No match for 'operator>>' Overloading istream operator learning C++ right now and ran into a bit of a problem. While trying to complete an example and make sure it works ran into the error:
error: no match for 'operator>>' (operand types are 'std::istream' and 'const int')
conversion of argument 1 would be ill-formed
Here is my code,
#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;

class Distance {
    private:
        int feet;
        int inches;
    public:
        Distance() {
            feet = 0;
            inches = 0;
        }
        Distance(int f, int i) {
            feet = f;
            inches = i;
        }
        friend ostream &operator<<( ostream &output, const Distance &D ) {
            output << D.feet << "\'" << D.inches << "\"" << endl;
            return output;
        }
        friend istream &operator>>( istream &input, const Distance &D ) {
            input >> D.feet >> D.inches;
            return input;
        }
};

int main() {
    Distance D1(11,10), D2(5,11), D3;
    cin >> D3;
    cout << "First Distance : " << D1 << endl;
    cout << "Second Distance : " << D2 << endl;
    cout << "Third Distance : " << D3 << endl;
    return 0;
}

Trying to overload the istream and ostream operators, but running into problems with the istream operator >>.
First thought to convert the variable D.feet and D.inches to char* but that doesn't seem right considering that I have to feed an int into the variables. Not sure what is wrong with my code, can anyone help?

A: Remove const in >> operator overload.
Your Distance is const'd.

A: [SOLVED]
Figured out the problem in this was that the 'const' in
ostream &operator>>( istream &input , const Distance &D )

Can't explain the actual processes and why this is a conflict, but perhaps somebody else could please explain? I'd really like to know it in depth.
Thanks!


text:
Q: Ruby app times out (deployed on Amazon EC2 with Phusion Passenger) I'm trying to deploy SequenceServer on Amazon EC2 (Ubuntu + Apache + Passenger), but it "hangs": http://ncwebguru.com/sequenceserver.
Same stuff happens to a "helloworld" app: http://ncwebguru.com/sequenceserver1
It works fine on my physical linux server (not EC2).
It doesn't log anything into apache log file so I'm not sure how to troubleshoot it. Any help on how to fix or troubleshoot the issue is greatly appreciated.
Apache conf:
<VirtualHost *:80>
    DocumentRoot /var/www
    <Directory /var/www>
        Allow from all
    </Directory>

    RackBaseURI /sequenceserver
    RackBaseURI /sequneceserver1

    <Directory /var/www/sequenceserver>
        Options -MultiViews
    </Directory>
</VirtualHost>

/var/www directory:
sequenceserver # sym link to /path/to/actual/sequenceserver/public
sequenceserver1 # sym link to /path/to/helloworld/public

/path/to/helloworld directory:
tmp/ # empty
public/ # empty
config.ru # helloworld ruby rack app

config.ru
app = proc do |env|
    return [200, { "Content-Type" => "text/html" }, "hello world"]
end
run app

A: Looks like you need to set the TimeOut directive in Apache's configuration file.  Timeout is indicated in seconds. For example, the following will set timeout to 5 minutes:
TimeOut 300


text:
Q: How to show Infragistics's UltraDesktopAlert from thread i am facing problem from many days. I have a thread listening for notificaitons from other system. whenever i receive a notification over socket i want to display it in Alert window using Infragistics's UltraDesktopAlert control. there is no winform in this class library.
please tell me how to display it using a thread. a sample is here
  void tcpServerListenter_OnCommReceive(object sender, CommEventArgs e)
        {
            string xmlString = Encoding.UTF8.GetString((byte[])e.data);
            try
            {
                XDocument xmlDoc = XDocument.Parse(xmlString);
                var res = (from msg in xmlDoc.Descendants("consoleNotification")
                           select msg.Element("value").Value).FirstOrDefault();

                this.notificationMsg = res;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

// here Alert window is not displaying.
ultraDesktopAlert1.Show("Notification", this.notificationMsg);
        }

but this code is not displaying alert window.
i checked the following link also
How to update the GUI from another thread in C#?
but problem is that i have no Winform in my class library. what i wants to display alert window whenever i receive notification on socket.

A: The easiest way to do this is save the UI thread's synchronization context and Send a lambda over to the UI thread...
On the UI Thread, when/before initiating your Async operation...
SynchronizationContext syncContext = SynchronizationContext.Current;

Save this into the class that is doing the aSync work, then you want to Send your code to run on the saved synchronization context.
syncContext.Send((stateMsg) => ultraDesktopAlert1.Show("Notification", stateMsg), this.notificationMessage);

Note that if you need to retrieve the Current SynchronizationContext from the UI thread, you can't get the UI threads synchronization context from a non UI thread.

A: You need to do safe cross threading since the ultraDesktopAlert1 Infragistics object was created by the main thread but being accessed on a different thread.
Check out this MSDN Documentation on how to do it.


text:
Q: Connect to a FTPS server within shell script I'm trying to connect to a FTPS (explicit TLS FTP) server within a shell script and i'm kinda confused.
I tried using the regular FTP command, but i get 534 error "policy requires SSL" and 504 "Security mechanism not implemented"
ftp -inuv myhost

Returns 504 then
quote USER myuser

Returns 534
I also tried sftp  but i get "couldn't read packet: connection reset by peer".
That damn peer is making my life a nightmare since IRC ;)
sftp myuser@myhost:mydirectory/ -P21

Connexion reset by peer and it says it can't connect to port 22, which is weird since i specified port 21...
Thanks for your help

A: There is a diference between ftps and sftp : sftp is ftp over ssh, so in your case you cannot use sftp. ftps is ftp that use ssl/tls
You need an ftp client that manages TLS, for instance http://lftp.yar.ru/ (found on the net)


text:
Q: Overriding a log4j.properties file I am trying to make log4j work in a project that uses a software framework that also uses log4j. The framework uses a log4j.properties file, so does that mean that I also have to use a properties file? I prefer the xml format. Let me know if that should create problems, it is not working as of now with my xml config file and I am very confused.

A: I think you should be able to replace the log4j.properties file with your own log4j.xml file. However, you probably want to make sure that the loggers/appenders etc that were in the original properties file also exist in your new log4j.xml file (or you may start missing log events).
If your log4j.xml is currently not working (what exactly are you seeing, btw), check that your classpath does not contain another log4j.properties or log4j.xml file (perhaps inside a jar?) If another log4j.properties exists, even in the final element of the classpath, it will still be loaded before a log4j.xml file in the beginning of the classpath.
Furthermore, you can enable log4j internal debugging with system property -Dlog4j.configDebug=true. This may give you a clue on what the problem is with the log4j.xml file.


text:
Q: for loop check all count together in one loop in react native I am using maps in react native to check whatever the current location matching the a specific location and I am using for loop to check if the location checked 10 times then need to quit and navigate to other screen, but when I used for loop it directly set the count to 10 and navigate to another screen
 renderLocationInfo() {

            for (var i = 0; i < 10; i++) {
                console.log(i)
                if (this.state.latitudeR != this.state.latitude && this.state.longitudeR != this.state.longitude) {
                    if (i < 9) {
                        return (

                            <View style={styles.container}>
                                <Text style={styles.btn}>Not matching </Text>

                            </View>

                        );
                    } else {
                        alert("time is out, please try again");
                        this.props.navigation.navigate("dashboard")
                    }

                } else if (this.state.latitudeR == this.state.latitude && this.state.longitudeR == this.state.longitude ) {

                    return (

                        <View style={styles.container}>
                            <Text style={styles.btn}>Matched</Text>
                            this.props.navigation.navigate("dashboard")

                        </View>

                    );

                }

            }
        }


text:
Q: Insert into mysql from gridview getting null exceptions I have a datagridview in c# that i am filling from a mysql database. The user reviews the info and then saves it to a different mysql database. I know the connections to both work and like my title says I'm getting a null exception on the first string in the for loop.
there are only 6 columns in the row and the only thing i can think of is i am looking at rows and not columns but not sure what the code should be for that edit I changed it as most had said to < instead of <= and I know why i get the error but don't know how to get the information i need. The error is coming from the fact that the cell shows as null even though there is a value in the cell.
string ConnectionString2 = ConfigurationSettings.AppSettings["ConnectionString2"];
MySqlConnection connection2;
connection2 = new MySqlConnection(ConnectionString2);

int i;
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
    string day = dataGridView1.Rows[i].Cells[0].Value.ToString();
    string Desc = dataGridView1.Rows[i].Cells[1].Value.ToString();
    string item = dataGridView1.Rows[i].Cells[2].Value.ToString();
    string prod = dataGridView1.Rows[i].Cells[3].Value.ToString();
    string vol = dataGridView1.Rows[i].Cells[4].Value.ToString();
    string qty = dataGridView1.Rows[i].Cells[5].Value.ToString();

    MySqlCommand cmdwk = new MySqlCommand("INSERT INTO spt_proposal_line_lab (proposal_Id,day_Name,proposal_Desc,proposal_Vol,product_Id,proposal_Qty,item_Id) VALUES (@propid,@day,@desc,@vol,@prod,@qty,@item)", connection2);
    MySqlParameter propid = new MySqlParameter("@propid", b);
    MySqlParameter day1 = new MySqlParameter("@day", day);
    MySqlParameter Desc1 = new MySqlParameter("@desc", Desc);
    MySqlParameter vol1 = new MySqlParameter("@vol", vol);
    MySqlParameter prod1 = new MySqlParameter("@prod", prod);
    MySqlParameter qty1 = new MySqlParameter("@qty", qty);
    MySqlParameter item1 = new MySqlParameter("@item", item);

    cmdwk.Parameters.Add(day1);
    cmdwk.Parameters.Add(propid);
    cmdwk.Parameters.Add(Desc1);
    cmdwk.Parameters.Add(prod1);
    cmdwk.Parameters.Add(vol1);
    cmdwk.Parameters.Add(qty1);
    cmdwk.Parameters.Add(item1);
}

The datagrid is called and filled in the load this is done on a button
Edit Seeing I am one point away from my img post ability I will try to explain this more
When the button is clicked and this code runs the error comes up at
string day = dataGridView1.Rows[i].Cells[0].Value.ToString();

the error is
Object reference not set to an instance of an object.

System.NullReferenceException was unhandled
  HResult=-2147467261
   Message=Object reference not set to an instance of an object.
    Source=SpectLabRemake2
    StackTrace:
   at SpectLabRemake2.Form6.btn_Save_Click(Object sender, EventArgs e)

A: I think it's this line:
for (i = 0; i <= dataGridView1.Rows.Count; i++)

You are going one row too far.  Try:
for (i = 0; i < dataGridView1.Rows.Count; i++)

A: Well for everyone that has this problem I will post my code that fixed the issue and Thank YOU soo much to everyone that was SOOOO helpful here with this issue.
  for (i = 0; i < dataGridView1.Rows.Count-1; i++)
        {

            string ConnectionString2 = ConfigurationSettings.AppSettings["ConnectionString2"];
            MySqlConnection connection2;

            connection2 = new MySqlConnection(ConnectionString2);
            connection2.Open();

                string day = dataGridView1.Rows[i].Cells[0].Value.ToString();
                string Desc = dataGridView1.Rows[i].Cells[1].Value.ToString();
                string item = dataGridView1.Rows[i].Cells[2].Value.ToString();
                string prod = dataGridView1.Rows[i].Cells[3].Value.ToString();
                string vol = dataGridView1.Rows[i].Cells[4].Value.ToString();
                string qty = dataGridView1.Rows[i].Cells[5].Value.ToString();

                MySqlCommand cmdwk = new MySqlCommand("INSERT INTO spt_proposal_line_lab (proposal_Id,day_Name,proposal_Desc,proposal_Vol,product_Id,proposal_Qty,item_Id) VALUES (@propid,@day,@desc,@vol,@prod,@qty,@item)", connection2);
                MySqlParameter propid = new MySqlParameter("@propid", b);
                MySqlParameter day1 = new MySqlParameter("@day", day);
                MySqlParameter Desc1 = new MySqlParameter("@desc", Desc);
                MySqlParameter vol1 = new MySqlParameter("@vol", vol);
                MySqlParameter prod1 = new MySqlParameter("@prod", prod);
                MySqlParameter qty1 = new MySqlParameter("@qty", qty);
                MySqlParameter item1 = new MySqlParameter("@item", item);

                cmdwk.Parameters.Add(day1);
                cmdwk.Parameters.Add(propid);
                cmdwk.Parameters.Add(Desc1);
                cmdwk.Parameters.Add(prod1);
                cmdwk.Parameters.Add(vol1);
                cmdwk.Parameters.Add(qty1);
                cmdwk.Parameters.Add(item1);
                cmdwk.ExecuteNonQuery();

            }
        }

    }
}

Brent


text:
Q: USB 3.0 host controller suddenly stopped working sudo lshw
        *-usb:0 UNCLAIMED
             description: USB controller
             product: 7 Series/C210 Series Chipset Family USB xHCI Host Controller
             vendor: Intel Corporation
             physical id: 14
             bus info: pci@0000:00:14.0
             version: 04
             width: 64 bits
             clock: 33MHz
             capabilities: pm msi xhci cap_list
             configuration: latency=0
             resources: memory:f7120000-f712ffff

Only the two USB 2.0 controllers function properly:
sw3@pc90313-sw3:~$ ls /dev/bus/usb
001  002

The 3.0 controller was listed as 004, but now it's suddenly gone.
sw3@pc90313-sw3:~$ dmesg | grep USB
[    0.156319] ACPI: bus type USB registered
[    0.459505] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver
[    0.459593] ehci-pci 0000:00:1a.0: new USB bus registered, assigned bus number 1
[    0.472274] ehci-pci 0000:00:1a.0: USB 2.0 started, EHCI 1.00
[    0.472286] usb usb1: New USB device found, idVendor=1d6b, idProduct=0002
[    0.472287] usb usb1: New USB device strings: Mfr=3, Product=2, SerialNumber=1
[    0.472355] hub 1-0:1.0: USB hub found
[    0.472493] ehci-pci 0000:00:1d.0: new USB bus registered, assigned bus number 2
[    0.488286] ehci-pci 0000:00:1d.0: USB 2.0 started, EHCI 1.00
[    0.488293] usb usb2: New USB device found, idVendor=1d6b, idProduct=0002
[    0.488294] usb usb2: New USB device strings: Mfr=3, Product=2, SerialNumber=1
[    0.488364] hub 2-0:1.0: USB hub found
[    0.488449] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver
[    0.488453] uhci_hcd: USB Universal Host Controller Interface driver
[    0.488543] xhci_hcd 0000:00:14.0: new USB bus registered, assigned bus number 3
[    0.784538] usb 1-1: new high-speed USB device number 2 using ehci-pci
[    0.916941] usb 1-1: New USB device found, idVendor=8087, idProduct=0024
[    0.916943] usb 1-1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[    0.917078] hub 1-1:1.0: USB hub found
[    1.188920] usb 1-1.1: new low-speed USB device number 3 using ehci-pci
[    1.285374] usb 1-1.1: New USB device found, idVendor=046d, idProduct=c05a
[    1.285375] usb 1-1.1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[    1.285376] usb 1-1.1: Product: USB Optical Mouse
[    1.357061] usb 1-1.2: new full-speed USB device number 4 using ehci-pci
[    1.451516] usb 1-1.2: New USB device found, idVendor=1366, idProduct=0101
[    1.451517] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[    1.521200] usb 1-1.3: new low-speed USB device number 5 using ehci-pci
[    1.619030] usb 1-1.3: New USB device found, idVendor=046d, idProduct=c31c
[    1.619031] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[    1.619032] usb 1-1.3: Product: USB Keyboard
[   25.307285] xhci_hcd 0000:00:14.0: USB bus 3 deregistered
[   25.358978] usbhid: USB HID core driver
[   25.362327] input: Logitech USB Optical Mouse as /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1:1.0/input/input2
[   25.362388] hid-generic 0003:046D:C05A.0001: input,hidraw0: USB HID v1.11 Mouse [Logitech USB Optical Mouse] on usb-0000:00:1a.0-1.1/input0
[   25.362469] input: Logitech USB Keyboard as /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.3/1-1.3:1.0/input/input3
[   25.362517] hid-generic 0003:046D:C31C.0002: input,hidraw1: USB HID v1.10 Keyboard [Logitech USB Keyboard] on usb-0000:00:1a.0-1.3/input0
[   25.364344] input: Logitech USB Keyboard as /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.3/1-1.3:1.1/input/input4
[   25.364394] hid-generic 0003:046D:C31C.0003: input,hidraw2: USB HID v1.10 Device [Logitech USB Keyboard] on usb-0000:00:1a.0-1.3/input1
[   25.517596] usb 2-1: new high-speed USB device number 2 using ehci-pci
[   25.650056] usb 2-1: New USB device found, idVendor=8087, idProduct=0024
[   25.650058] usb 2-1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[   25.650208] hub 2-1:1.0: USB hub found

What could be going on?
sw3@pc90313-sw3:~$ uname -a
Linux pc90313-sw3 3.11.0-13-generic #20-Ubuntu SMP Wed Oct 23 07:38:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

A: This was a very strange situation.
My PC is dual-boot with a Windows7. I had logged into windows for a short while, and while shutting it off, it began installing updates.
Next I logged in Ubuntu and the described problems occurred.
Going back to Windows for it to finish updating (at boot time), and then back to Linux solved the problem.
I am still wondering how did windows manage to mis-configure the very hardware.
The issue's gone now.


text:
Q: Batch inserting array values into Database Node.js, Oracle, orawrap I have an application that runs in the Browser and communicates with a REST service. The rest service can has to write data to an Oracle DB lets say it has to write an Entity like this:
var entity =  {
    "id": 0,
    "date": new Date(),
    "comment": 'test'
};

And I have a Statement, that looks like this:
ar statement = 'INSERT INTO MY_TABLE ( '
        + '    THE_ID '
        + '  , THE_DATE '
        + '  , THE_COMMENT '
        + ' ) VALUES ( '
        + ' :id, '
        + " :date, "
        + ' :comment'
        + ')';

The array of entities is called:
var entities = [];

Now lets say i have an array of entity with the length of around 30. I tried recursive:
var i = 0;
// Function that Batch inserts an Array.
var insertArray = function (statement, entities, i, cb) {
    if (i >= entities.length) {
        console.log("exit insertArray.");
        return cb(null, true);
    }

    insert(statement, entities[i], function (err, val) {
        if (err) {
            console.log('error insertArray: ', err);
            return cb(err, null);
        }

        insertArray(statement, entities, ++i, cb);
    });
};

This is the function that inserts an entity into the DB
var insert = function (statement, entity, cb) {
    orawrap.execute(
        statement,
        {
            "id": { val: entity.id, dir: oracledb.BIND_INOUT, type: oracledb.NUMBER },
            "date": { val: entity.date, dir: oracledb.BIND_INOUT, type: oracledb.DATE },
            "comment": { val: entity.comment, dir: oracledb.BIND_INOUT, type: oracledb.STRING }
        },
        cb);
};

This code stops inserting after around 3 recursive calls.
i tried in a for loop as well. But since its nicer to use callbacks in an asynchronous environment, the recursive idea seems nicer to me. Anyhow the iterative approach did not batch insert the values as well.
Do you have an idea how to solve this?

A: The easiest way to do these kinds of tasks in Node.js is with the async library. Checkout the eachSeries method of the async library:
https://github.com/caolan/async#each
That link points to each, but eachSeries is just a variation on each that runs things in series (one after the other) rather than in parallel. You just pass your array, the function that should be run for each element in the array, and another function to be invoked when the iteration is all done.


text:
Q: Keep process running while program continues C++ I want to be able to call a function in a python script through C++. The function will print some text to stdout.
However, the python script takes about 1 minute to load the global variables to memory, so I want to keep the process alive in interactive mode, where I would be able to simply call the function again without loading all the variables again.
I know that I can run system commands using system, but the command must terminate before I can use the output. I am also aware that I can use CPython and call PyRun_SimpleFileEx on the file, but this will have to reload all the variables again
I don't have any code to show since I don't know how to do this. Is there any way I can do this without rewriting the whole python script in C++?

A: Every PyRun_* function runs in the __main__ module, so any functions or variables you define stick around for future executions.
For example, say we want to run the do_it function from this file (helper.py) multiple times:
from datetime import datetime as dt
from time import sleep
print("First load")

def do_it():
    print("Helper function called on demand: %s" % dt.now())
    sleep(1)

do_it()

We can simply invoke PyRun_SimpleFile once, and then access the function again using PyRun_SimpleString("do_it()\n");.
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    FILE *fp = fopen("helper.py", "rb");
    PyRun_SimpleFile(fp, "helper.py");
    for (int i = 0; i < 10; i++) {
        PyRun_SimpleString("do_it()\n");
    }
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

Note that this makes use of the "Very High Level Embedding" and is thus limited to evaluating strings. For more complex arguments you may want to use the "Pure embedding" instead to grab the PyFunctionObject from the module and invoke it.
Finally, you may want to look at pybind11, a C++11 bridge between Python and C++. This should make it very easy to grab Python the function and call it directly from C++.


text:
Q: Classifying data in R I'm using R and I want to use some type of machine learning technique (SVM, perhaps) to classify data. I have data that looks like this, for example
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    4    5    6    0
[2,]    2    6    7    3    1
[3,]    7    1    4    6    1
[4,]    3    4    5    9    0

Where columns 1, 2, 3, and 4 are variables with some provided data, and column 5 is the classification. So, data entry 1 has values 3, 4, 5, and 6 for the four variables, and is classified as a 0. Classifications can be either 0 or 1. I want to be able to build an SVM so that given a new set of variables, it will classify it as "0" or "1"
What is the best way to do this?

A: This is not really a question for CrossValidated, but here is a primer for doing that in R:
groups <- factor( a[,5] )
train  <- a[,-5]
library( kernlab )
ksvm.model <- ksvm( train, groups )

There are other options, though. There are numerous supervised machine learning algorithms, and it is not possible to say which one is best. In my hands and in the context of my data, SVM perform worse than random forests (package randomForest in R) or partial least squares discriminant analysis (PLS-DA, R package e.g. mixOmics).


text:
Q: Antlr4 "Test Rig" and maven I am struggling a little bit to figure out how I can use the antlr4 maven plug in to run the TestRig class?
I've read though the output of mvn antlr4:help -Ddetail=true, which is the only documentation I have been able to find, but this doesn't mention how to use the TestRig. So, what's the recommended way of using the test rig together with maven? using the grun alias method doesn't seem very elegant here.
UPDATED - Reasoning
Hello :)
Right, don't get me wrong but I really don't understand why you wouldn't want this functionality in the maven plugin? And I don't understand why its soul purpose should be to compile grammars?
Currently, if I maintain a build with Maven, and I use the antlr4-maven-plugin , it will install both the plugin and the antlr 4.1 in my maven repository. With this already there, why would I start adding things to my classpath and creating aliases when maven can take care of that? I mean, this is what maven is for really. If I had a antlr4:TestRig goal, then all I would do was use that. No need to manually maintain the class path, or create bash aliases. It would just work.
And be far far more elegant that hard-coding elements from my local maven repository in my class path, and maintaining bash aliases. Or alternatively, maintain two installations per. version of antlr I wish to use (one maintained by me, simply to use TestRig, and one maintained by maven for everything else).
Additionally, if I wanted to use a different version of antlr, then I wouldn't need to update the classpath and my aliases, maven would simply manage all this for me :)

A: This is how I invoke TestRig with Maven:
mvn exec:java -Dexec.mainClass="org.antlr.v4.runtime.misc.TestRig"
-Dexec.args="<DOT_NOTATION_GRAMMAR_CLASSPATH> <START_RULE>
-gui <INPUT_FILE>"

So if you've got MyGrammar.g4 in src/main/antlr4/com/test/parser with a starting rule of startRule:
mvn exec:java -Dexec.mainClass="org.antlr.v4.runtime.misc.TestRig"
-Dexec.args="com.test.parser.MyGrammar startRule
-gui <INPUT_FILE>"

A: I had a similar question, in that I wanted to use the TestRig -gui option for debugging my grammar.  I didn't find a way to run the GUI via the antlr4-maven-plugin, but I did manage to build a satisfactory CLASSPATH.  The key was to include target/classes.
# Assuming your project is in $PROJECT ..
CLASSPATH=".:/usr/local/lib/antlr-4.1-complete.jar:$PROJECT/target/classes"
alias grun='java org.antlr.v4.runtime.misc.TestRig'
mvn -q compile
grun MyGrammer startingRule -gui < test_input

Should produce a lovely GUI view of the syntax tree.

A: Why would the Maven plugin run the TestRig class? The Maven plugin's job is converting the .g4 grammar files to .java source files in the proper package locations and ensuring those generated files get compiled. TestRig is not used for any part of that.
Edit: I have been using ANTLR for many years, in many applications. In all that time I have never updated my system classpath, nor operated ANTLR/gunit/TestRig from the command line or created aliases for it. Doing so is not helpful for automated testing and inevitably leads users into the problems you described. That said, the thought that TestRig needed special support in the Maven plugin also never crossed my mind, because better solutions already exist.
Some alternatives

*

*You can use the surefire plugin, and write a JUnit test that performs operations on your grammar directly (create a lexer/parser, parse some input, and perhaps even call inspect() on the resulting parse tree.

*You can use the surefire plugin, and write a JUnit test that explicitly calls TestRig.main(String[]) with the correct arguments.

*You can modify the ANTLR 4 Maven plugin to add a new goal for running TestRig, and submit a pull request to the project to have it included in a future release (you would need to make a very compelling case since there are already 2 alternatives that are more suited to long-term successful testing of a project using ANTLR 4).

A: I like the idea of using Maven to run the TestRig. But I do not like to add the dependency org.antlr:antlr4 to my code (because I already have org.antlr:antlr4-runtime) so my solution is to configure the exec plugin with an additional dependency.
<properties>
    <antlr.version>4.7.1</antlr.version>
</properties>
...
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <id>TestRigGui</id>
            <phase>none</phase>
            <goals>
                <goal>java</goal>
            </goals>
            <configuration>
                <mainClass>org.antlr.v4.gui.TestRig</mainClass>
                <arguments>
                    <!-- Grammar -->
                    <argument>de.humanfork.experiment.antlr.Hello</argument>
                    <!-- start rule -->
                    <argument>hello_rule</argument>
                    <!-- enable gui -->
                    <argument>-gui</argument>
                    <!-- input file -->
                    <argument>example.txt</argument>
                </arguments>
                <includePluginDependencies>true</includePluginDependencies>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4</artifactId>
            <version>${antlr.version}</version>
        </dependency>
    </dependencies>
</plugin>

Then use: mvn exec:java@TestRigGui to start the GUI
BTW: in ANTLR 4.7.1 the TestRig main class is: org.antlr.v4.gui.TestRig


text:
Q: Is this buffer overflow working on Mac OSX? Was reading through some text and playing around with attempting to write past the size of an array in C i.e buffer overflow. The text indicates that whenever you attempt to write to say array[5] when the length of the array is 5 then you get a segmentation fault but I dont seem to be getting that When using the code below. The code actually runs.
#include <stdio.h>
#include <string.h>

int main ()
{
    int i;
    int array[5] = {1, 2, 3, 4, 5};
    for (i = 0; i <= 255; i++)
    {
        array[i] = 10;
    }
    int len = sizeof(array) / sizeof(int);
    printf("%d\n", len);
    printf("%d\n", array[254]);
}

On execution of the last statement, a 10 is printed. Am wondering whether this is a vulnerability or if there is something I am missing. I am running the code from iterm2 on a macbook pro.

A: Writing past the end is Undefined Behaviour- anything may happen.

A: You are writing data past the end of an array. This is undefined behavior. Undefined behavior means it may work on a Friday but crashes on a Saturday.
Here is the C paragraph that says it is undefined behavior:

(C99, 6.5.3.2p4) If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

A: You'll be able to examine any memory owned by your current process.  When you hit the end of that block of memory you'll get an EXC_BAD_ACCESS error.  Try this amended version of the code that loops until the OS kills it:
#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    int i = 0;
    int array[5] = {1, 2, 3, 4, 5};
    while (1)
    {
        printf("%llu - %d\n", i, array[i]);
            // if (&i == &array[i]) printf("Overwriting i\n");
            // array[i] = 2;
        ++i;
    }
}

If you uncomment the commented out lines you should find that you get stuck in an infinite loop between i values of 3 and 6.  You're overwriting the memory located at the address of the i integer.