text:
Q: Find all SQL Server databases in an Instance using Java How can I list all SQL Server databases within a known instance on my machine?

A: You can try with DatabaseMetaData#getCatalog() from JDBC (works with MS SQLServerDriver and jTDS driver):
import java.sql.*;
public class ListDatabases
{
  public static void main(String [] args)
  {
    Connection con = null;
    try {
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       con = DriverManager.getConnection("jdbc:sqlserver://localhost:1269;"
               + "user=sa;password=HerongYang");

       DatabaseMetaData meta = con.getMetaData();
       ResultSet res = meta.getCatalogs();
       System.out.println("List of databases: ");
       while (res.next()) {
          System.out.println(res.getString("TABLE_CAT"));
       }
       res.close();
    } catch (Exception e) {
       System.err.println("Exception: " + e);
    } finally {
       con.close();
    }
  }
}


text:
Q: Unable to load ASCII file into R I've followed a couple of these posts here and here but am still struggling with loading an ASCII file.
I'm trying to pull down the county-level Area Health Resources File but it's not loading correctly. I've now tried:
> df <- read.table("DATA/ahrf2018.asc")
Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  line 1 did not have 312 elements
> dim(df)
[1] 3350    5
> df <- read.delim("DATA/ahrf2018.asc")
> dim(df)
[1] 3229    1
> df <- read.csv("DATA/ahrf2018.asc")
> dim(df)
[1] 3350    5
> df <- read.csv("DATA/ahrf2018.asc", header = FALSE, skip = 1)
> dim(df)
[1] 3350    6

And I looked into the LaF package, but don't know the column types which are required.
Is there something painfully simple I am overlooking?
EDIT:
Example of output, where columns not getting created:
    V1
1  01001AHRF 01001               20181821232435Alabama            ALAutauga                  Autauga
2  01003AHRF 01003               20181821232435Alabama            ALBaldwin                  Baldwin
3  01005AHRF 01005               20181821232435Alabama            ALBarbour                  Barbour
4     01007AHRF 01007               20181821232435Alabama            ALBibb                     Bibb

redpajama_set_name: RedPajamaStackExchange


text:
Q: Audio playing too fast If any of my fellow Xuggler users can tell me what I'm doing wrong, that would be awesome! I am doing the following:

*

*Reading from ogv (ogg video)

*Queueing the audio and video

*Writing back to ogv

sounds simple right? The problem I am experiencing in my QueueMixer class is that the output file plays the audio 2x too fast, and no matter what I check or change with regards to pts it doesnt improve.
The eclipse project and all files being used are at this link:
http://dl.dropbox.com/u/7316897/paul-xuggled.zip
To run a test, compile and execute the StreamManager class; a test ogv file is included. Before anyone asks, yes I have to queue the data as it will be mixed with other data in a future version.

A: Audio has a sample rate. Make sure that you copy the sample rate from the input to the output, otherwise the system might use a default (like 44KHz while the original data was sampled at 22KHz which would create such an effect).

A: The fix is to multiply the sample count by two when extracting them from the ShortBuffer.

samples = new short[(int) audioSamples.getNumSamples() * 2];
audioSamples.getByteBuffer().asShortBuffer().get(samples);

Having half the samples causes the audio to play twice as fast.


text:
Q: Syntax error on token "start" , identifier expected after this token I've been trying to create an agent thanks to Jade on Java with this code:
import jade.core.ProfileImpl;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;

public class Agents {
    jade.core.Runtime rt= jade.core.Runtime.instance();
    ProfileImpl pMain= new ProfileImpl();
    AgentContainer mc = rt.createMainContainer(pMain);
    AgentController rma= mc.createNewAgent("rma", "jade.tools.rma.rma", null);
    rma.start();
}

I keep getting the error "Syntax error on token "start" , identifier expected after this token" and I cannot understand why.

A: By not going into finding problems with your code, I suggest to use the code below to solve your error.
Initialization code for agent and adding to the container
package package.se.samplejade;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;

public class LaunchAgents {
    private static final String AGENT_CLASS_STRING ="package.se.samplejade.SampleAgent";
    private static final String AGENTNAME_STRING = "sampleAgent";

     public static void main(String[] args) {
         LaunchAgents LaunchAgents = new LaunchAgents();
         LaunchAgents.initilizeAgent();

    }

    /**
     * Creates a new agent and adds it to the container
     *
     * @param
     * @return  true or false
     */
    public boolean initilizeAgent() {

     AgentController agentcontroller = null;
     Object[] initObjects = new Object[2];
     initObjects[0] = new Object(); // add any object needed to initialize the agent
     initObjects[1] = new Object();
      try {
            agentcontroller = Container.getController().createNewAgent(AGENTNAME_STRING, AGENT_CLASS_STRING,
                    initObjects);
            agentcontroller.start();
            return true;
         } catch (StaleProxyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
         }
      }

    }

The JADE container initialization
package.se.samplejade ;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.ContainerController;

public final class Container {

    // get a JADE runtime
    private static jade.core.Runtime runtime = jade.core.Runtime.instance();
    // Create a profile, where the launch arguments are stored
    private static Profile profile2 = new ProfileImpl();
    private static Profile profile = new ProfileImpl();
    // create the Main-container
    private static ContainerController mainContainer = null;
    private static ContainerController containerController = null;
        /**
         * Returns the path of the container to the JADE agents
        */
    public synchronized static ContainerController getController() {

        // create the Main-container
        if (mainContainer == null) {
            profile.setParameter(Profile.CONTAINER_NAME, "Container");
            profile.setParameter(Profile.GUI, "true");
            mainContainer = runtime.createMainContainer(profile2);
            containerController = runtime.createAgentContainer(profile);
        }

        return containerController;
    }

  }

The agents code
  package.se.samplejade;
  import jade.core.Agent;
  public class SampleAgent  extends Agent  {

     @Override
      protected void setup() {
          //Put your agent initialization code with the objects passed in the initialization

       }

    }


text:
Q: Get the class attributes of specific I which have class "active" My html code is this, i need to get all the class attributes of the active li.

1

2

3

4

 ul > li').hasClass('active').attr('class');

A: You need
jQuery('ul.daily > li.active').attr('class');

A: $('.daily li.active').attr('class');

li.active selector will bring all li having active class.

A: daily is not id it is a class name
try this
$('.daily li.active').attr('class');

A: You can do this...
var allclasses = jQuery('.daily li.active')[0].className.split(/\s+/)


text:
Q: Find index of returned list result C# How do you find the index of an entry within a list. My code below.
listFrom and listTo contain entries of strings.
I am getting the error:

Severity   Code    Description Project File    Line    Suppression State
  Error   CS1503  Argument 1: cannot convert from 'System.Collections.Generic.List' to 'string'

List<string> listFrom = new List<string>(); //Contains a list of strings
List<string> listTo = new List<string>(); //Contains a list of strings

List<string> lineStart = listFrom.Except(listTo).ToList(); //Will always return a single value
List<string> lineEnd = listTo.Except(listFrom).ToList(); //Will always return a single value

int startLineIndex = listFrom.IndexOf(lineStart);            //Error on this line
Console.WriteLine("Index of Start: " + startLineIndex);

A: As the error states, it cannot convert from 'System.Collections.Generic.List' to 'string'. However I never knew the function SingleOrDefult() existed.
All credit to @maccettura even though he didn't know what I was trying to do! xD
Code change below for the answer:
List<string> listFrom = new List<string>(); //Contains a list of strings
List<string> listTo = new List<string>(); //Contains a list of strings

string lineStart = listFrom.Except(listTo).SingleOrDefault();
string lineEnd = listFrom.Except(listTo).SingleOrDefault();

int startLineIndex = listFrom.IndexOf(lineStart);            //Error on this line
Console.WriteLine("Index of Start: " + startLineIndex);

A: It's because when you call listFrom.IndexOf(lineStart); it's expecting a String. lineStart in your code is defined as a List of Strings so you would either need to call on a specific value inside the list, or change lineStart to a string.


text:
Q: View output of a script using screen I'm trying to run multiple scripts in detached screen sessions at the same time.
This is the code I currently have.
#!/bin/bash
screen -mdS Name_Screen1 "python /path/to/file/file.py arg1 arg2 arg3"
screen -mdS Name_Screen2 "python /path/to/file/file.py arg3 arg4 arg5"
screen -mdS Name_Screen3 "python /path/to/file/file.py arg6 arg7 arg8"

When typing "screen -list" to see what screens are available, I don't see any of the screens I'm currently running. This scripts outputs some information to the screen, which depends on the arguments given. I've looked through some of the problems posted in here, but I can't find an answer for this.
Is there any way I can look at the outputs of these screens without having to do something like "> out.txt"?
Update
So I finally figured it out. I ended up creating just one screen session and multiple windows within the session.
#!/bin/sh
Lum_Types=("Window1" "Window2" "Window3" )
Windowname="Screen_session"
screen -mdS $Windowname
for Lum in ${Lum_Types[@]}
do
    screen -S $Windowname -X screen -t $Lum
    screen -S $Windowname -p $Lum -X stuff $"python /Path/to/file arg1 arg2"
    screen -S $Windowname -p $Lum -X stuff $'\n'
done

One key part was to add the $ after the -X stuff in order to pass the string to the screen session and windows.

A: So I finally figured it out. I ended up creating just one screen session and multiple windows within the session.
#!/bin/sh
Lum_Types=("Window1" "Window2" "Window3" )
Windowname="Screen_session"
screen -mdS $Windowname
for Lum in ${Lum_Types[@]}
do
    screen -S $Windowname -X screen -t $Lum
    screen -S $Windowname -p $Lum -X stuff $"python /Path/to/file arg1 arg2"
    screen -S $Windowname -p $Lum -X stuff $'\n'
done

One key part was to add the $ after the -X stuff in order to pass the string to the screen session and windows.
– Victor

A: All you need to do is separate the words of the command.
screen -mdS "Name_Screen1" python /path/to/file/file.py "arg1" "arg2" "arg3"

with them grouped in a sngle strin screen won't execute them, it just quits straight away,
that's why they don't show in the list.


text:
Q: I need to fill a textbox from the data selected in a listbox in another form I am trying to make a textbox in one of the forms get data from a listbox in another form. the other form will be a pop-up form of a query that will be launched upon the clicking on the text box. so this is how it goes

*

*Form A is open

*Textbox A is clicked on

*Clicking on Textbox A opens Form B which has a listbox

*Listbox value selected

*Close button in form B pressed

*Now textbox A in form A should contain the data we selected in the
listbox in form B

I think it can be done by creating variables (public variables if I am not mistaken) but i am a total newbie and have no idea what code to use.
the thing is, i have several textboxes in the same form which will run the same code and get the value in the textbox from the same form.

A: Could this be something like,
Private Sub textBoxA_OnClick()
    DoCmd.OpenForm "FormB", OpenArgs:= "textBoxA"
End Sub

Private Sub textBoxB_OnClick()
    DoCmd.OpenForm "FormB", OpenArgs:= "textBoxB"
End Sub

Then select the ListBox item you want to. Then on click the button, you could make a small check if item was selected. Then based on that you could put that data into the textbox.
Private Sub formBButton_OnClick()
    If Me.FormBList.ListCount = 0 Then
        MsgBox "You have not made any selection, please select an option.", _
                vbInformation
        Exit Sub
    End If

    If Len(Me.OpenArgs & vbNullString) <> 0 Then _
        Forms("FormA").Controls(Me.OpenArgs) = Me.FormBList

    DoCmd.Close acForm, Me.Name
End Sub

A: Here is what i used.
I hid all the text boxes and made them invisible.
I added an add button.
Add button opens the form (frmslctattendee)
In the form the value of the combo box is selected from query
Then the code behind the command button is as follows.
Private Sub Command5_Click()
    If Forms!frmmeetings!txtat8.Visible = True Then
        Forms!frmmeetings!txtat9.Visible = True
        If Len(Forms!frmmeetings!txtat9 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat9.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat7.Visible = True Then
        Forms!frmmeetings!txtat8.Visible = True
        If Len(Forms!frmmeetings!txtat8 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat8.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat6.Visible = True Then
        Forms!frmmeetings!txtat7.Visible = True
        If Len(Forms!frmmeetings!txtat7 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat7.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat5.Visible = True Then
        Forms!frmmeetings!txtat6.Visible = True
        If Len(Forms!frmmeetings!txtat6 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat6.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat4.Visible = True Then
        Forms!frmmeetings!txtat5.Visible = True
        If Len(Forms!frmmeetings!txtat5 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat5.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat3.Visible = True Then
        Forms!frmmeetings!txtat4.Visible = True
        If Len(Forms!frmmeetings!txtat4 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat4.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat2.Visible = True Then
        Forms!frmmeetings!txtat3.Visible = True
        If Len(Forms!frmmeetings!txtat3 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat3.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat1.Visible = True Then
        Forms!frmmeetings!txtat2.Visible = True
        If Len(Forms!frmmeetings!txtat2 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat2.Value = cmbnameselect.Value
        End If
    End If

    If Forms!frmmeetings!txtat1.Visible = False Then
        Forms!frmmeetings!txtat1.Visible = True
        If Len(Forms!frmmeetings!txtat1 & vbNullString) = 0 Then
            Forms!frmmeetings!txtat1.Value = cmbnameselect.Value
        End If
    End If

    DoCmd.Close
End Sub

it does the job.
waiting for your comments.


text:
Q: Usage of the Friedman test I have done an experiment in which I have measured the energy required to chew three different food samples on 10 subjects with 3 repetitions per sample. I am interested therefore in finding out whether there is a difference between samples according to the energy consumed.
I have performed a Friedman test by ranks followed by multiple comparison procedure (Tukey's honestly significat difference for ranks) as Friedman test was significant.
However someone told me that for using that test I should make sure that the error for order effect was not significant, ans I don't fully understand this.
I provided my samples in the same order for all subjects. That is A,B,C -A1 B1 C1 and A3 B3 C3 for each subject.
I will be very grateful if you can tell me

*

*whether the test I used (Friedman) is the correct for my purpose?

*whether the sequence in which I gave the samples affects my result from Friedman test?

*if what I have done is incorrect, what to do instead?

A: *

*Given your data, the Friedman test sounds like the right approach.  I am not aware of there being any agreement regarding the post hoc testing.  One of the commenters refers to the Nemenyi test, but it has pretty low power.  Using Tukey HSD on the ranks (which I assume is what you have done), is probably OK but I doubt you will find much academic literature to support that approach.

*The sequence can have an impact.  Imagine that the subject was tired after the first sample.  Then, by the time they got to the second sample, it may take longer.  Or, even if fatigue was not at issue, something else could occur (e.g., people got bored towards the end of the experiment).  Your experiment in its current form confounds the order with which the samples were test with the three different food samples and there is no statistical way of disentangling these and working out whether order did or did not have an impact.

*The standard approach when conducting sensory research is to randomize the order with people are given the samples (or, use an experimental design and allocate people into different blocks with different pre-determined orders).  Then, you can estimate a general linear model or ANOVA which takes into account the order as well as the food samples, permitting you to disentangle the different effects.


text: Q: What determines when a user was "seen"? Right now, my Stack Overflow user page says I was "seen" 33 minutes ago. The last entry on the activity list was at 54 minutes ago. I'm pretty sure I didn't vote on any questions or comments in the meantime. Furthermore, I just flagged a comment here on Meta and my Meta user page still says I was seen 10 minutes ago. What actions reset the "seen" counter to zero, and what actions are ignored?


text:
Q: ¿Cómo puedo extraer la parte de array de enteros de este JSON en C#? Si fueran tan amables me pueden decir ¿Cómo puedo extraer el array de enteros de este JSON? que realmente ya me tiene con dolor de cabeza, lo he intentado de muchas formas. La cuestión es que primero probé con transportarlo a C# como List, luego solo Object y después JObject.
{
  "pObjParametros": [{
    "prol_codigo":19,
    "aEVAS_FECHA_INI":"2012-07-11",
    "aeVAS_FECHA_FIN":"2013-08-01",
        "amotivo":[
      12,
      2
    ],
    "aEVAS_CARGO_A":[
      1,
      3
   ]
    }]
}

¡Muchas gracias por vuestra ayuda!

A: Una opcion es utilizar newtonSoft para deserializar el json. puedes pasarlo a un objeto dinamico o defines el modelo que representa el json(recomendable).
Ejemplo:
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
var lista = results.pObjParametros;
foreach (var element in lista)
{
    var prol_codigo=element.prol_codigo;
    var aEVAS_FECHA_INI=element.aEVAS_FECHA_INI;
    foreach (var motivo in element.amotivo)
    {
       Console.WriteLine(motivo);
    }
    //...
}

con modelo
public class modelo{
    IEnumerable<ObjParametros> pObjParametros { get; set; }
}
public class ObjParametros
{
   int? prol_codigo { get; set; }
   string aEVAS_FECHA_INI { get; set; }
   string aeVAS_FECHA_FIN { get; set; }
   IEnumerable<int> amotivo { get; set; }
   IEnumerable<int> aEVAS_CARGO_A { get; set; }
}

modelo results = JsonConvert.DeserializeObject<modelo>(json);

A: Me dieron esta otra opción de realizar lo solicitado, la cuestión con esta otra forma es q me toca extraer del JToken:
 JArray jObject = JsonConvert.DeserializeObject<JArray> (JsonConvert.SerializeObject( parametros.pObjParametros));
JToken jObject1 = jObject.FirstOrDefault().SelectToken("amotivo");


text:
Q: Combine yql auth.basic and ymail.messages to get yahoo emails? I have this:
    select * from auth.basic
where url="mail.yahoo.com"
and username="username"
and password="password"

and this:
select * from ymail.messages where numMid='3'

Can I somehow combine them? I think you can imagine why I want this?

A: The basic auth wont work with this table. The ymail.messages table supports OAuth so you can use 3 legged oauth described at http://developer.yahoo.com/oauth/ and then use the oauth Authorization header to get the mail data from these tables.
Yahoo does support a couple of different languages including java and php. Let us know if you need a hand at that.


text:
Q: Practice or practise? I learnt in Merriam-Webster and other reliable sources that advice differs from advise. Advice is a noun while advise is a verb. Same goes with the words device and devise.
However, the word practice does not differ from practise as stated by the Merriam-Webster Dictionary. Is it true? Or the rule is still the same like on the words advice and advise? Here are some examples the Webster Dict. used:

You need to practice what you preach.- It is a verb because it entails that
  you need to apply or carry out what you have been preached.
Being a good musician takes a lot of practice- It is used as a noun
  because it entails a systematic exercise for proficiency in music.

A: Surprising to me, practice is used for the noun and practise is for the verb, except in the U.S. where "practice" is used for both. So you would be best off only writing "practice" if you are in the U.S. since most people will think "practise" is a misspelling.
Source


text: Q: How to get a list of all valid ip address in a local network in android I can find gateway address and netmask address in android. How to get a list of all valid ip address in a local network in android with this gateway and netmask?


text:
Q: Continuous Function Maps Open Interval to Open Sets? Given a continuous function $f$. Then is it true that $\{f(x):x\in (a,b)\}$ is open and $\{f(x):x \in (a,b]\}$ connective?
I know in general a continuous function doesn't map open sets to open sets if it's not open mapping. But I can't find a counterexample here.

A: A continuous function $f:\mathbb R \to\mathbb R$ is open if and only if $f$ is strictly monotone.
Suppose $f$ is not strictly monotone.  Then there exist $x<y<z$ such that $f(y)$ is not strictly between $f(x)$ and $f(z)$; WLOG (because we would consider $-f$) suppose $f(y)\geq f(x)$ and $f(y)\geq f(z)$.  By continuity $f$ attains a maximum value on $[x,z]$, and because of the last sentence this maximum value must be attained on the interior.  Hence $f((x,z))$ has a maximum value, which implies it is not open.
Suppose $f$ is strictly monotone.  WLOG (because we could consider $-f$) suppose $f$ is strictly increasing.  Then for all $x<y$, $f((x,y))=(f(x),f(y))$, using that $f$ is increasing and using the Intermediate Value Theorem.
So constant functions give counterexamples, but also any function not always increasing or always decreasing, like $x^2$, $\sin(x)$, $\frac{x}{1+x^2}$, or a nowhere differentiable continuous function.
Note that strict monotonicity is equivalent to injectiveness, so $\mathbb R$ has the property that every continuous injective $f:\mathbb R\to \mathbb R$ is an open map, hence is a homeomorphism onto its image.
(Pawel already answered the connectedness part, which could also be thought of in terms of the Intermediate Value Theorem.)

A: Regarding your first question, consider a constant function $f(x)=0$. Then it is a continuous function that maps an open set (open interval) to a set that is not open (point).
Regarding your second question, continuous functions map connected sets to connected sets. Thus, since any interval is connected, its image will also be connected.


text:
Q: Accessing application settings from class library using Microsoft.Extensions.Configuration I'm trying to figure out how to access application settings in a class library. The application settings are read and build in a console application, and a project referenced class library must access these, as this library is the data access layer and need access to a connection string.
In the main console app I have this code - it works fine
   var config = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json", optional: true, loadOnChange: true)
    .Build();

                Console.WriteLine($"Contents of Message Property: {config["Message"]}");

How do I access the information in a project referenced class library. I guess it shouldn't be necessary to re-read the json file with settings from each library?


text:
Q: How to Reset Credit Card Form after Submit the Form in Square Connect In Square Connect, I am creating Credit Card Nonce using sqPaymentForm. Once I submit the form and create the Nonce, I would like to reset form/clear all
 textboxes. I am using Angular 7 and FormGroup doesn't work with the sqPaymentForm. so how can I reset my form on form Submit?
this.paymentForm = new SqPaymentForm({

        // Initialize the payment form elements
        applicationId: this.applicationId,
        locationId: this.locationId,
        autoBuild: false,
        inputClass: 'sq-input',
        // Initialize the credit card placeholders
        cardNumber: {
          elementId: 'sq-card-number',
          placeholder: 'Valid Card Number'
        },
        cvv: {
          elementId: 'sq-cvv',
          placeholder: 'CVV'
        },
        expirationDate: {
          elementId: 'sq-expiration-date',
          placeholder: 'Expiration'
        },
        postalCode: {
          elementId: 'sq-postal-code',
          placeholder: 'Zip Code'
        },
        // SqPaymentForm callback functions
        callbacks: {
          /*
           * callback function: methodsSupported
           * Triggered when: the page is loaded.
           */

          /*
           * callback function: cardNonceResponseReceived
           * Triggered when: SqPaymentForm completes a card nonce request
           */
          cardNonceResponseReceived: (errors, nonce, cardData) => {
            if (errors) {
              // Log errors from nonce generation to the Javascript console
              console.log("Encountered errors:");
              errors.forEach(function (error) {
                console.log('  ' + error.message);
              });
              return;
            }

            this.updateCustomerCard(nonce, cardData.billing_postal_code);
          },

          /*
           * callback function: paymentFormLoaded
           * Triggered when: SqPaymentForm is fully loaded
           */
          paymentFormLoaded: function () {
            /* HANDLE AS DESIRED */
          }
        }
      });

      this.paymentForm.build();
    }

A: There's no way to directly edit any of the fields, so you won't be able to reset the fields one-by-one. However, you do have the ability to call destroy() on the payment form, and then call build() to rebuild the form (which would essentially reset all of the fields).


text:
Q: How to access multiple databases in rails 3.1.0 app? In our rails 3.1.0 app, we would like to access multiple databases based on user credential. There are multiple solutions. One is to install one app for each user and every app only accesses one database. The problem is that if there are many databases (such as hundreds), there would be equal number of app installations. Maintenance of large number of apps may be a hassle.  Another approach is to access multiple databases within the app. However this approach seems not readily supported in rails 3.1.0. Certainly there would be a code within the app to decide which database to access for the user who just logs in. Can someone provide solutions and insights about pros and cons of the approache? thanks so much.

A: You should be able to use ActiveRecord::Base.establish_connection to dynamically connect to any database you like within a certain context. How you implement this is entirely application-specific, but Rails does have this capability.
Here's a very contrived example:
class User
  def books
    ActiveRecord::Base.establish_connection(
      :adapter  => "mysql",
      :host     => "localhost",
      :username => self.username,
      :password => self.password,
      :database => self.database
    )

    Book.all
  rescue Exception => e
    # ...
  end
end

You would want to do actual error handling and probably establish the connection somewhere outside of an instance method, but that's up to you to decide.

A: The apartment gem might be exactly what you're looking for:

Apartment provides tools to help you deal with multiple databases in
  your Rails application. If you need to have certain data sequestered
  based on account or company, but still allow some data to exist in a
  common database, Apartment can help.


text:
Q: Steel Catch 22 in Starbound
Note: This question refers to content found only in Starbound beta. As of the 1.0 stable version of the game, Steel is not available in the game. It has been replaced with tungsten, which is directly mined as ore and melted into tungsten bars in a furnace.

I want to make Steel bars
To make steel you need iron and oil
to collect oil you need an upgraded Matter Manipulator
to upgrade the Matter Manipulator you need refined copper
to refine copper you need a Refinery
to make a Refinery you NEED STEEL!!!
this is impossible

A: A Refinery is a crafting device that allows you to transform ores and their derivatives into pixels. You're looking to smelt Copper Ore into Copper Bars, which you can do at a Stone Furnace.


text:
Q: Multi-threaded loop through collection with C# I have seen lots of examples on how to do this (read through lots of threads on this site), but I'm having a very hard time getting something that works without locking up the UI thread AND allows me to control the number of threads executing at a time.
I have this method, which loops through the collection and calls an async method to process the items, but it locks up the UI...
    async Task ProcessItems()
    {
        using (var semaphore = new SemaphoreSlim(5))
        {
            var tasks = MyCollection.Select(async (MyItem) =>
            {
                await semaphore.WaitAsync();
                try
                {
                    await ProcessItem(MyItem);
                }
                finally
                {
                    semaphore.Release();
                }
            }).ToArray();

            await Task.WhenAll(tasks);
        }
    }

The 'ProcessItem' method calls another method, which makes some API calls over the internet to upload some files.
This has been working, but I have no control over how many threads are executed at a time...
    foreach (MyItemClass MyItem in MyCollection)
    {
        MyItemClass tmp = logItem;
        Thread thread = new Thread(() => ProcessItem(tmp));
        thread.Start();
    }

EDIT: Here's the ProcessItem method...
    public async Task<string> ProcessItem(MyItemClass MyItem)
    {
        MyItem.Status = "Transferring";

        HelperClass.UploadFileOrFolder(
            siteUrl,
            MyItem.DocumentLibrary,
            MyItem.RootFolder,
            srcRootPath,
            MyItem.SourcePath);

        MyItem.Status = "Transferred";

        return "Transferred";
    }

And here is the UploadFileorFolder method, which is using the SharePoint.Client.File.SaveBinaryDirect method to upload a file to SharePoint...
    public static void UploadFileOrFolder(string siteUrl, string libraryName, string rootFolder, string path, string file)
    {
        ClientContext ctx = GetSPContext(siteUrl);

        using (fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true))
        {
            Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fs, true);
        }
    }

A: Your ProcessItem method is marked as async, and it returns a Task, which indicates it's supposed to be asynchronous, but it is not in fact asynchronous.  it will execute entirely synchronously.  async merely allows the use of await in a method, and does nothing to actually make a method asynchronous.  You are currently getting a compiler warning informing you of this fact.
If the API you're using exposes an actually asynchronous method to upload the file you're trying to upload, you should be using that instead of the synchronous version.  If it doesn't, then while it's undesirable, you'll need to use Task.Run (or an equivalent) to run the synchronous method in a thread pool thread asynchronously.


text:
Q: SimpleBlobDetector - Isolate blobs that are distinct from surrounding I'm using SimpleBlobDetector to locate the decimal dots and other types of punctuation marks, as can be seen in the image below, sometimes the detector picks up blobs out of the solid areas of the text (The bottom of the middle 9), I'm looking for a way to filter out those detections either through the SimpleBlobDetector or in post process.
Is there a way to specify that a blob must be separated from it's background color? Maybe an edge detection method?
Your help is appreciated.
Detector code is:
    params = cv2.SimpleBlobDetector_Params()
    params.filterByArea = True
    params.minArea = 30
    params.minThreshold = 50
    params.maxThreshold = 200
    params.filterByConvexity = True
    params.minConvexity = 0.87
    params.filterByColor = True
    detector = cv2.SimpleBlobDetector_create(params)
    detections = detector.detect(img)

Output image with detections

Original:

A: Instead of using SimpleBlobDetector, here's a solution utilizing edge/contour detection which allows for more filtering control. The main idea is

*

*Convert image to grayscale

*Gaussian blur

*Threshold image to separate main features from background

*Perform canny edge detection

*Dilate canny image to enhance and close contours

*Find contours in image and filter using a min/max threshold area

Threshold image

Canny edge detection

Dilate to enhance contours

Detected and filtered contours based on area

Output results

contours detected: 1

import numpy as np
import cv2

original_image = cv2.imread("1.jpg")
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(blurred, 110, 255,cv2.THRESH_BINARY)[1]
canny = cv2.Canny(thresh, 150, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
dilate = cv2.dilate(canny, kernel, iterations=1)

cv2.imshow("dilate", dilate)
cv2.imshow("thresh", thresh)
cv2.imshow("canny", canny)

# Find contours in the image
cnts = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

contours = []

threshold_min_area = 1100
threshold_max_area = 1200

for c in cnts:
    area = cv2.contourArea(c)
    if area > threshold_min_area and area < threshold_max_area:
        cv2.drawContours(original_image,[c], 0, (0,255,0), 3)
        contours.append(c)

cv2.imshow("detected", original_image)
print('contours detected: {}'.format(len(contours)))
cv2.waitKey(0)


text:
Q: new Canvas(bitmap) crashs on galaxy s but works on nexus can someone tell me why my app works fine on samsumg galaxy nexus but crashes on samsung galaxy s?
i found out that it crashes at this line:
bMapRpm=BitmapFactory.decodeResource(getResources(), R.drawable.canvasback);
canvasRpm = new Canvas(bMapRpm);

the BitmapFactory.decodeResource works fine but when i create the new Canvas it crashes.
i can't post the logcat because my galaxy s (i don't know why) doesn't support logcat
can someone help me?

A: I guess, bitmap must be mutable. Doc: "Construct a canvas with the specified bitmap to draw into. The bitmap must be mutable."
You can:
bMapRpm=BitmapFactory.decodeResource(getResources(), R.drawable.canvasback);

Bitmap mutableCopy = Bitmap.createBitmap(bMapRpm.getWidth(),bMapRpm.getHeight(),bMapRpm.getConfig());
canvasRpm = new Canvas(mutableCopy);
canvasRpm.drawBitmap(bMapRpm, null, null);
bMapRpm.recycle();

..do whatever want with canvas

A: Easy way to create mutable bitmap,
use Bitmap.copy(confit, is_mutable),
you can try it:
bMapRpm=BitmapFactory.decodeResource(getResources(), R.drawable.canvasback);
Bitmap mutableCopy = bMapRpm.copy(Bitmap.Config.ARGB_8888, true);
canvasRpm = new Canvas(mutableCopy);


text:
Q: golang и mssql ошибка "mssql: Cannot convert a char value to money. The char value has incorrect syntax." Есть старая база MSSQL и мне нужно наладить с ней контакт. Само подключение к ней происходит без проблем но с запросами происходит какая то беда.
Есть таблица [Сотрудники] с полями:
id, Name, E-mail и к примеру мне нужно вытянуть имя зная только почту.
Вот так выглядит мой метод:
func (w *Wrapper) GetAuthorInIntexOrder(email string) (string) {
    row := IntexDB.QueryRow("SELECT Name FROM [Сотрудники] WHERE [E-mail] = $1", email)

    var name string
    err := row.Scan(
        &name,
    )

    if err != nil {
        log.Warn("[database]GetAuthorInIntexOrder->row.Scan: ", err.Error())
        return ""
    }
    return name
}

В ответ я получаю ошибку: "[database]GetAuthorInIntexOrder->row.Scan: mssql: Cannot convert a char value to money. The char value has incorrect syntax." У Name тип nvarchar и я не понимаю почему вообще происходит конвертация в money, это же просто строка. Я пользуюсь драйвером github.com/denisenkom/go-mssqldb. Интересно что если убрать условие WHERE то запрос выполнится и я получу 1й элемент в таблице. Как думаете в чём может быть проблема?

A: Уверен - в запрос не попадает значение переменной email, а передается значение $1 типа money, поэтому при попытке преобразования значения из столбца [E-mail] получаете ошибку.
Попробуйте:
row := IntexDB.QueryRow("SELECT Name FROM [Сотрудники] WHERE [E-mail] = @p1", email)


text:
Q: Opening a new panel by just clicking a portion of the panel I am using Net beans drag and drop GUI and in that i am displaying a chart in a jPanel and i want that when i click a portion of that chart then another panel opens up.I know we can  write an event , when we click a whole panel(anywhere in panel) but i just want that  when i click the small potion of that chart only then another panel opens up, how is this possible?

A: Attach a MouseListener to the panel.  Detect the events, take action.  See How to Write a Mouse Listener for more details.


text:
Q: Current state of the stack ignores user needs I read the blog, I re-read it, I made notes and re-read it again, I walked away and then re-read it for a fifth and sixth time. I still found none of my concerns addressed (see end).
First, there will always be a part of me that loves Stack Exchange. It has been therapy for me and given me the opportunity to meet the characters of the Python room. Even if many of the ones I worked with, many of those closest to my field, have left - I still have fun with the Data Scientists, Physicists who claim not to be programmers (even if their Py knowledge is insane), and Human or Canine Ninjas, and it has directly help me progress in my own education.

I have sssooo many points, I cannot make them all. So I will simply start with Jobs:
I have never, in all my contract work, found a single job using SO and only two leads, from the start of SO.Jobs, offering in my area/field. I'd wonder if that's just my area but I still see nothing for developers, no data scientists, no data engineers (again, my field), no jobs, no anything in the technical field within your own job posting - linked within the Blog. The jobs are primarily marketing people and sales peoples. So, I'm sorry SE is not likely a place you would find us applying - those of us in the actually field of computer science, information systems, and information technology. Have you forgotten your heart? Have you forgotten you were built by developers? engineers? IT people? IS people? those of us who live, breath, and on good weeks even taste what it is to be in the industry of technology?
I am now in my 20th (not consecutive, there was a break for war) year in the IT/IS industry. I have begun teaching others just starting on their journey. A question I keep finding myself asking is: "Should I point them towards SO?". I don't mean this in the sense of "will they use SO to cheat?" but in the sense that I will give my students as many advantages as I can and "IS SO AN ADVANTAGE?". Once, this would be an easy call - now? The welcoming initiative, the way it was conducted, the lack of calls for developers in a system that almost begs for data people, for web developers, looking at a system that is losing questions more rapidly than has been acknowledged (2018: a year in asking and answering) - why would I point them towards SO? Just why would I point them to something that is losing its prominence and not even looking for people within the fields they aspire to and I live in. None of these are addressed.
Finally, I still have seen nothing from higher up on how it is treating its current userbase. Until I see that or a change within posts like this which truly acknowledges this (not with words - we are long past that and I will not forget - but within hiring, within corporate structure) it is impossible to trust anything said by the company.
TLDR;
SE no longer represents developers, data engineers, data scientists, or other coders. Its sub-sites (including SO) may but SE as a corporation has lost its connection with the IT/IS/Technology community and posts like this which link to Job offerings by SE which completely lack mid or higher technical positions (with only one entry-level IT position listed) - just point to how far away they've drifted from their original audience.
I tried to post this to the blog but comments are either disabled or otherwise filtered such that this will not get through, so I have posted here. If there is a question it is this:
How will SE address its disregard to current users and lack of focus on the IT/IS industry which was once its heart?
Earlier stated Concerns about SE policy (please don't upvote on meta unless you agree, "I said what I mean, I mean what I said" agree/disagree as you will):

*

*Are we creating divisions in our quest to make new users welcome?

*How do I draw attention to a meta post?

*Add a way for users to "opt out" of the new contributor indicator on their own posts

A: As noted in some of the comments on Journeyman Geek's answer, my role recently changed from "CTO" to "President and CTO". This is a made-up title that means that I'm now responsible for the entire exec team (engineering, product, marketing, sales, finance, etc) and putting together our plan for 2019, which is why I wrote the post.
A few things are different this year than previous years that maybe speak to your concerns:

*

*We're hiring a bunch, especially in engineering. Last year was a rebuilding year on the business side -- we had to fix a bunch of things to get ourselves into a better financial position. We did that, and now we're ready to start growing again. The only reason you don't see dev jobs on our hiring page is because whenever we post dev jobs we get more applications than we can handle. As of this moment we have... 373 applications to our dev job listing that we're still trying to sort through. As soon as we work that queue down, we'll post the job for a week or two and get another few hundred applications.

*We're putting more emphasis on dev community work. With the business side in much better shape, we're able to grow the team that works on public Q&A features. We're hiring for that team right now. We're also investing heavily in Stack Overflow for Teams & Enterprise, and a lot of that work spills back over into the community because they're working on the core Q&A engine (it's all the same codebase).

*We're working on making the community easier to use and more welcoming, which is about focusing on devs. This one you might not agree with me on, but I deeply believe that in order for the community to grow, we have to make it easier to use and encourage people to join who right now feel excluded. The overwhelming tendency of internet communities, especially technical ones, is to become more insular and hard on new users ("RTFM!"), and we have to actively work to resist that. So we're going to keep working on this, but also staff up a related effort to work on mod tools & expert user experience that's parallel to the Welcome Wagon effort.

*I'm... President?. I don't want to overstate my own value here, I'm still just one person and the real people making a difference are all the different people who work here, but I do think the fact that Joel chose me for this role (with my dev background) speaks to our belief that the dev community is at the heart of this company.

To the general feeling of being ignored and undervalued, I hear you. We haven't made community work enough of a priority the past few years, and I aim to fix that. It won't be immediate because it involves staffing a few teams back up while still supporting the business side (because we have to stay in business or there won't be a community), but change is in the air.

A: To add to David's answer, I feel like we finally have good problems.
What exactly do I mean by that? Well, moving slowly because you're in the process of seeking and hiring folks for roles, some of them incredibly difficult to fill, is a really good problem to have.
Why is that a good problem to have? Because you're moving with the confidence of knowing what you're going to do nine steps from now and the only thing that remains commensurate is finding and hiring the right people. There isn't any more "well, if this does well as we think it should, we can ... (yadda yadda)."
Abby was saying in comments that this time we're asking you to wait is a bit different than previous times. I think her point is important enough to amplify, hence this answer.
I can't lay out a firm hiring roadmap, or exactly what parts of open roles makes them difficult to fill, or even the order that we might need to fill them for everything to come together (one might, after all, want to make a specific hire after hiring someone more apt at interviewing such candidates, for instance). But I can say, we have a solid plan that I am very excited to help David execute, and I'm really excited about us bringing on more folks to make it happen.
You'll see additional evidence of priorities refocusing way sooner than later, but since I'd rather surprise you than disappoint you, I'm going to stop there. I will say that I have been here since 2008, I served as your elected moderator for 4+ years, and have been in senior management at this company for about the same amount of time. I feel really good about what's coming up.
And, well, the people that tend to be good about fixing all the problems tend to be the ones doing it, instead of running around the Internet yodeling about fixing all the problems. That pretty accurately describes how David has been handling his demotion to President and CTO, though I have no idea how well he can or can't yodel.
It's safe to feel optimistic. I'll end it there for now.

A: I don't work at SE – and I've complained pretty loudly in the past about the focus on careers. I've gotten a few sentiments from folk who work here though. I'd also say – David's been on SE for ages primarily on the engineering side. I actually think it's interesting he wrote it – as a long time employee at the pointy end of the engineering stick, rather than marketing. (I got informed he's the president and CTO in the comments - which adds more weight, but also that this is someone intimately involved in what he's talking about)

*

*The blog's primarily marketing. It's aimed at selling the product, and for the most part, the product that makes SE money is Careers (though less so), channels and hosted SE instances and ads. We're not the target audience.

*Feels a lot like we're in the middle of a course correction. While SE isn't huge, it's not small enough to go "Hey, we need to suddenly change things".

*Hiring takes time – the layoffs were a year ago, and things have suffered from it. I for one am keeping an eye on the "work here" page. It's probably heavy on "manager"/"Lead" type jobs, cause those sectors are stuff that needs people, and they can build a team around that. I for one am expecting to see more QA end jobs there.
I do see UX jobs, product managers, information security (which is a new thing for SE)... The enterprise sales jobs probably reflect the fact that that's growing. The management level stuff reflects that, well it's growing, and they'll be the ones working out what's needed – especially in roles that haven't been needed that much.
I'd love to see more devs, more CMs and such but I don't think that's something that will turn up immediately right after such an announcement.
I'm not going to say "All is good" – but the noises we're hearing from SO blogs (marketing focus aside) have been better than they have been in a few years.  While it's for them to win back lost trust - I don't think it'll be overnight.


text:
Q: Should I use common::sense or just stick with `use strict` and `use warnings`? I recently installed a module from CPAN and noticed one of its dependencies was common::sense, a module that offers to enable all the warnings you want, and none that you don't.  From the module's synopsis:
use common::sense;

# supposed to be the same, with much lower memory usage, as:
#
# use strict qw(vars subs);
# use feature qw(say state switch);
# no warnings;
# use warnings qw(FATAL closed threads internal debugging pack substr malloc
#                 unopened portable prototype inplace io pipe unpack regexp
#                 deprecated exiting glob digit printf utf8 layer
#                 reserved parenthesis taint closure semicolon);
# no warnings qw(exec newline);

Save for undef warnings sometimes being a hassle, I've usually found the standard warnings to be good.  Is it worth switching to common::sense instead of my normal use strict; use warnings;?

A: The "lower memory usage" only works if you use no modules that load strict, feature, warnings, etc. and the "much" part is...not all that much.

A: Not everyone's idea of common sense is the same - in that respect it's anything but common.
Go with what you know.  If you get undef warnings, chances are that your program or its input is incorrect.
Warnings are there for a reason.  Anything that reduces them cannot be useful.  (I always compile with gcc -Wall too...)

A: I have never had a warning that wasn't something dodgy/just plain wrong in my code. For me, it's always something technically allowed that I almost certainly don't want to do. I think the full suite of warnings is invaluable. If you find use strict + use warnings adequate for now, I don't see why you'd want to change to using a non-standard module which is then a dependency for every piece of code you write from here on out...

A: When it comes to warnings, I support the use of any module or built-in language feature that gives you the level of warnings that helps you make your code as solid and reliable as it can possibly be.  An ignored warning is not helpful to anyone.
But if you're cozy with the standard warnings, stick with it.  Coding to a stricter standard is great if you're used to it!  I wouldn't recommend switching just for the memory savings.  Only switch if the module helps you turn your code around quicker and with more confidence.

A: While I like the idea of reducing boiler-plate code, I am deeply suspicious of tools like Modern::Perl and common::sense.
The problem I have with modules like this is that they bundle up a group of behaviors and hide behid glib names with changeable meanings.
For example, Modern::Perl today consists of enabling some perl 5.10 features and using strict and warnings.  But what happens when Perl 5.12 or 5.14 or 5.24 come out with great new goodies, and the community discovers that we need to use the frobnitz pragma everywhere?  Will Modern::Perl provide a consistent set of behaviors or will it remain "Modern".  If MP keeps with the times, it will break existing systems that don't keep lock-step with its compiler requirements.  It adds extra compatibility testing to upgrade.  At least that's my reaction to MP.  I'll be the first to admit that chromatic is about 10 times smarter than me and a better programmer as well--but I still disagree with his judgment on this issue.
common::sense has a name problem, too.  Whose idea of common sense is involved? Will it change over time?
My preference would be for a module that makes it easy for me to create my own set of standard modules, and even create groups of related modules/pragmas for specific tasks (like date time manipulation, database interaction, html parsing, etc).
I like the idea of Toolkit, but it sucks for several reasons: it uses source filters, and the macro system is overly complex and fragile.  I have the utmost respect for Damian Conway, and he produces brilliant code, but sometimes he goes a bit too far (at least for production use, experimentation is good).
I haven't lost enough time typing use strict; use warnings; to feel the need to create my own standard import module.  If I felt a strong need for automatically loading a set of modules/pragmas, something similar to Toolkit that allows one to create standard feature groups would be ideal:
use My::Tools qw( standard datetime SQLite );

or
use My::Tools;
use My::Tools::DateTime;
use My::Tools::SQLite;

Toolkit comes very close to my ideal.  Its fatal defects are a bummer.
As for whether the choice of pragmas makes sense, that's a matter of taste.  I'd rather use the occasional no strict 'foo' or no warnings 'bar' in a block where I need the ability to do something that requires it, than disable the checks over my entire file.  Plus, IMO, memory consumption is a red herring.  YMMV.
update
It seems that there are many (how many?) different modules of this type floating around CPAN.

*

*There is latest, which is no longer the latest.  Demonstrates part of the naming problem.

*Also, uni::perl which adds enabling unicode part of the mix.

*ToolSet offers a subset of Toolkit's abilities, but without source filters.

*I'll include Moose here, since it automatically adds strict and warnings to the calling package.

*And finally Acme::Very::Modern::Perl
The proliferation of these modules and the potential for overlapping requirements, adds another issue.
What happens if you write code like:
use Moose;
use common::sense;

What pragmas are enabled with what options?

A: I would say stick with warnings and strict for two main reasons.

*

*If other people are going to use or work with your code, they are (almost certainly) used to warnings and strict and their rules. Those represent a community norm that you and other people you work with can count on.

*Even if this or that specific piece of code is just for you, you probably don't want to worry about remembering "Is this the project where I adhere to warnings and strict or the one where I hew to common::sense?" Moving back and forth between the two modes will just confuse you.

A: There is one bit nobody else seems to have picked up on, and that's FATAL in the warnings list.
So as of 2.0, use common::sense is more akin to:
use strict;
use warnings FATAL => 'all'; # but with the specific list of fatals instead of 'all' that is

This is a somewhat important and frequently overlooked feature of warnings that ramps the strictness a whole degree higher. Instead of undef string interpolation, or infinite recursion just warning you and then keeping on going despite the problem, it actually halts.
To me this is helpful, because in many cases, undef string interpolation leads to further more dangerous errors, which may go silently unnoticed, and failing and bailing is a good thing.

A: I obviously have no common sense because I going more for Modern::Perl  ;-)

A: Many of peoples argues in a comments with what if the MP changes, it will break your code. While this  can be an real threat, here is already MUCH things what are changes over time and break the code (sometimes after a deprecation cycle, sometimes not...).
Some other modules changed the API, so breaks things, and nobody care about them. E.g. Moose has at least two things what are deprecated now, and probably will be forbidden in some future releases.
Another example, years ago was allowed to write
for $i qw(some words)

now, it is deprecated. And many others... And this is a CORE language syntax.
Everybody survived. So, don't really understand why many of people argues againist helper modules. When they going to change, (probably) here will be a sort of deprecation cycle... So, my view is:

*

*if you write programs to yourself, use any module you want ;)

*if you write a program to someone, where someone others going to maintnanece it, use minimal nonstandard "pragma-like" modules (common::sense, modern::perl, uni::perl etc...)

*in the stackoverflow questions, you can safely use common::sense or Modern::Perl etc. - most of users who will answer, your questions, knows them. Everybody understand than it is easier to write use 5.010; for enable strict, warnings and fearures with 10 chars as with 3 lines...


text:
Q: Regular expression to match valid IP addresses over multiple lines How can I construct a regular expression that matches a valid IP address [1-255] and is able to be multiline and allow whitespace? The values will be typed out and submitted like this:
10.10.10.10
100.100.100.100
192.1.1.1.1
192.158.1.38

and so on with no limit.
I have this expression that I have tweaked but only does a fraction of what I need it to do:
"^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\/?[0-4]?[0-9]?\s?\r?\n?\.?\d)*$\b"

A: Something as simple as the following should do it:
\b(?<!\.)(?:(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])(?!\.)\b

Not too sure what you think you're doing with all the new line checks though, regex engines handle new lines on their own just fine. See it in action here.


text:
Q: How do I refresh when I reselect the tab I'm on in my bottom navigation bar? So this is the code I have for my bottom navigation bar, in my tabs I'm retrieving data from parse
my question is what do I put inside my  BottomNavigationView.OnNavigationItemReselectedListener in order for the tab that I reselect to reload/refresh
would very much appreciate any help!

    final Fragment fragment1 = new HomeFragment();
    final Fragment fragment2 = new UsersFragment();
    final Fragment fragment3 = new ProfileFragment();
    final Fragment fragment4 = new SettingsFragment();
    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = fragment1;

    @Override
    public void onBackPressed() {
        if(ParseUser.getCurrentUser() != null){
            Intent a = new Intent(Intent.ACTION_MAIN);
            a.addCategory(Intent.CATEGORY_HOME);
            a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(a);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_home);

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
     bottomNavigationView.setOnNavigationItemReselectedListener(navigationItemReselectedListener);

        fm.beginTransaction().add(R.id.fragment_container, fragment4, "4").hide(fragment4).commit();
        fm.beginTransaction().add(R.id.fragment_container, fragment3, "3").hide(fragment3).commit();
        fm.beginTransaction().add(R.id.fragment_container, fragment2, "2").hide(fragment2).commit();
        fm.beginTransaction().add(R.id.fragment_container,fragment1, "1").commit();

    }

    private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {

            switch (item.getItemId()){
                case R.id.nav_home:
                    fm.beginTransaction().hide(active).show(fragment1).commit();
                    active = fragment1;
                    return true;
                case R.id.nav_list:
                    fm.beginTransaction().hide(active).show(fragment2).commit();
                    active = fragment2;
                    return true;
                case R.id.nav_profile:
                    fm.beginTransaction().hide(active).show(fragment3).commit();
                    active = fragment3;
                    return true;
                case R.id.nav_settings:
                    fm.beginTransaction().hide(active).show(fragment4).commit();
                    active = fragment4;
                    return true;
            }
            return false;
        }
    };

    private BottomNavigationView.OnNavigationItemReselectedListener navigationItemReselectedListener = new BottomNavigationView.OnNavigationItemReselectedListener() {
        @Override
        public void onNavigationItemReselected(@NonNull @NotNull MenuItem item) {

        }
    };
}```

A: So you are calling the fragment through bottom navigation bar
So for every selection of an item in the bottom navigation yo do want to refresh the fragment
Do use attach() and detach() method while beginning the transaction. It refreshes each  time


text:
Q: How to tell if JDK is available from within running JVM? Note: All the similar questions are answering this from the perspective of the shell (e.g. Is javac available? java -version or which java). I'm looking explicitly for the perspective of the currently running JVM.
There are programs that require to be run from within a JDK's JRE, not "just" a JRE. I'm wondering if there's a simple way to find out what my currently running program is executed in.
I'm looking for a generic way to figure this out, rather than an analysis of the program in question and duplicating its use of JDK features. That's why I'd prefer not to execute an external process testing if javac is on the path, if possible. I'm rather looking for some code that will run within a JDK, but fail within a JRE.
It could be Class.forName with a class that's only available in a JDK. It could be a system property. Or anything else.
If I have to execute an external process with javac: So be it. But I'd prefer something simpler and generic.
Clarification from deep down in the comments:
From time to time I'm running into this problem with Liferay, which requires to be run from within a JDK's JRE. I was entertaining the thought to just deploy another plugin that provides a userfriendly error message if run without a JDK available. I shy away from analyzing which code is the one failing in a JRE-only environment, and I don't want to modify Liferay's code, rather add my own plugin to do the analysis and warn.

A: Class.forName("com.sun.tools.javac.Main");
If there is no exception, it is a JDK.
It works with current JDKs, but it's probably not part of any official spec.

A: javax.tools.ToolProvider.getSystemJavaCompiler() will return null if no compiler is available, and a JavaCompiler if it is.
Technically it just tells you if the compiler is available of course, but that in most scenarios will imply the existence of the JDK.


text:
Q: Python: Two lists to be compared for format match and made into a dictionary I'm using python 3: I have two lists and I want to have them combined in a dictionary using similar information:
first_list = [('1234', 'abcd', 'John Doe', 'good_status'),
              ('1234', 'efgh', 'John Doe', 'good_status'),
              ('1234', 'hijk', 'John Doe', 'bad_status'),
              ('5566', 'abjk', 'George Washington', 'good_status'),
              ('7889', 'zyxw', 'Jane Austin', bad_status')]

The second list might be:
second_list = [('1234', 'John Doe', 'abcd efgh hijk'),
               ('5566', 'George Washington', 'abjk'),
               ('7889', 'Jane Austin', 'zyxw')]

Desired Dictionary output:
dictionary = {'1234' : ('John Doe', 'abcd_good efgh_good hijk_baad')
              '5566': ('George Washington', 'abjk_good')
              '7889': ('Jane Austin', 'zyxw_bad')
              }

In first_list that entry [0] and [2] match the entry [0] and entry [1] of second_list.
first_list has entry [1] and [3] which should come together and match with second_list[2]
Oh... and the two lists are not really lined up like, index 0 of might not be the same name as index 0 of second_list.
I'm new and kinda in over my head, could use any advice.

A: My solution is only to use first_list without the reference of second_list.
The following code can be runnable under the environment of >=python 3.6, since I used f-string.
The full code listed below:
first_list = [
    ('1234', 'abcd', 'John Doe', 'good_status'),
    ('1234', 'efgh', 'John Doe', 'good_status'),
    ('1234', 'hijk', 'John Doe', 'bad_status'),
    ('5566', 'abjk', 'George Washington', 'good_status'),
    ('7889', 'zyxw', 'Jane Austin', 'bad_status')]

dictionary = dict()

# Loop over the given list
for i in first_list:

    # Extract the index
    new_key = i[0]

    # If the new key is not existed,
    # make a new item and initialize it with empty string
    # The reason for using `list` instead of `tuple`
    # is that `list` object is mutable
    if new_key not in dictionary.keys():
        new_name = i[2]
        dictionary.update({new_key: [new_name,""]})

    # Parse the new status string
    # and append it into the existing string
    # If you are using python version under 3.6,
    # try to use `format()` function
    new_str = f"{i[1]}_{i[3].split('_')[0]}"
    dictionary[new_key][1] += f" {new_str}"

# Transfer the lists to tuples using "dict comprehension"
dictionary = {k:tuple(v) for (k, v) in dictionary.items()}

print(dictionary)

A: I made a solution with two functions, make_dict_from_list and match_two_dicts.  There are ways to make these more succinct with list comprehensions, but I wrote them the long way so it's more clear what they're doing.
def make_dict_from_list(list):
    temp_dict={}
    for record in list:
        for word in record:
            if word == record[0]:
                temp_dict[record[0]] = []
            else:
                temp_dict[record[0]].append(word)
    return temp_dict

This method makes a temporary dictionary, and iterates through the list, record by record.  It makes the word at the first position (if word = record[0]) the key of the dictionary, and sets an empty array as the value of that key.  If it's not the first word (i.e. else), it appends any other words in the line to that array.  Next you can call these methods to make your dictionaries.  Expected result:
>>>>make_dict_from_list(first_list)
{'1234': ['hijk', 'John Doe', 'bad_status'], '5566': ['abjk', 'George Washington', 'good_status'], '7889': ['zyxw', 'Jane Austin', 'bad_status']}

>>>>make_dict_from_list(second_list)
{'1234': ['John Doe', 'abcd efgh hijk'], '5566': ['George Washington', 'abjk'], '7889': ['Jane Austin', 'zyxw']}

Now we can make our second method:
def match_two_dicts(dict1, dict2):
    for index1, key1 in enumerate(dict1):
        for index2, key2 in enumerate(dict2):
            if key1 == key2:
                print(f"ID {key1}: match at dict1[{index1}], dict2[{index2}]")

This splits the entries in dict1 & dict2 into a list of key-value pairs.  We use enumerate so we have an index of our position in each dictionary.  Then, if the IDs (i.e., the keys of each record) match, we can print out the positions of the match.
Expected result:
>>> match_two_dicts(dict1, dict2)
ID 1234: match at dict1[0], dict2[0]
ID 5566: match at dict1[1], dict2[1]
ID 7889: match at dict1[2], dict2[2]

edit: I just noticed that you have duplicate IDs in your first list, which my solution does not account for.  If this is necessary for your application, you will need to modify the code to use a list of dicts with one key, instead of a single dict with multiple keys.  If this is a problem for you let me know.

A: You need a double for loop to check for the status of each item and combine them into a dictionary based on the matches.
first_list = [
    ('1234', 'abcd', 'John Doe', 'good_status'),
    ('1234', 'efgh', 'John Doe', 'good_status'),
    ('1234', 'hijk', 'John Doe', 'bad_status'),
    ('5566', 'abjk', 'George Washington', 'good_status'),
    ('7889', 'zyxw', 'Jane Austin', 'bad_status')
]

second_list = [
    ('1234', 'John Doe', 'abcd efgh hijk'),
    ('5566', 'George Washington', 'abjk'),
    ('7889', 'Jane Austin', 'zyxw')
    ]

def CreateDict(list1, list2):

    #Dictionary to be created.
    dictionary = {}

    #Go through each given data.
    for search_key in list2:
        dict_data  = [search_key[1]]
        status     = ""

        #Go through the data we must check for the status.
        for element in list1:

            #If the number and the names match.
            if search_key[0] == element[0] and search_key[1] == element[2]:

                #Check the status of each data.
                data = search_key[2].split(" ")
                for d in data:
                    if d in element:

                        #         Data| status without the _status  |      add a space at the end.
                        status += d+"_"+element[3].replace("_status", "") +" "

        #Remove the last space added on the status string.
        status = status[:len(status)-1]

        #Append the status data on the list.
        dict_data.append(status)

        #Append the dict_data using the number as a key.
        dictionary[str(search_key[0])] = dict_data

    #Return the dictionary.
    return dictionary

print(CreateDict(first_list, second_list))


text:
Q: Why does this jquery .css line not work within 2 functions? this simple jquery .css statement does not activate within two functions, am I doing something wrong?
javascript:
function updateAllCSS(element, property, value) {

    function updateThemeCreatorCSS(element, property, value) {
        $(element).css(property, value)
    }
    updateThemeCreatorCSS(element, property, value)
}
}

updateAllCSS('h1', 'backgroundColor', '#f00')

HTML:

Test header

A: This should work:
function updateAllCSS(element, property, value) {
    function updateThemeCreatorCSS(element, property, value) {
        $(element).css(property, value)
    }
    updateThemeCreatorCSS(element, property, value);
}

updateAllCSS('h1', 'background-color', '#f00');

There was an extra } and the parameters being passed to updateAllCSS needed to have 'quotes'.

A: You had an extra } and you should quote your parameters.
jsFiddle example
function updateAllCSS(element, property, value) {
    function updateThemeCreatorCSS(element, property, value) {
        $(element).css(property, value)
    }
    updateThemeCreatorCSS(element, property, value);
}
updateAllCSS('h1', 'backgroundColor', '#f00');

A: Not sure why you have that nested function.  Here's a Fiddle of it working:
http://jsfiddle.net/cbbdW/


text:
Q: similar functions like sp.linalg.norm, sp.cross in C++ In python we have library scipy containing sp.linalg.norm, sp.cross. Are there any similar functions in C++ boost library?

A: There doesn't seem to be.
However, OpenCV has what you need!
L2 norm: http://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#norm
Cross: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#Point_
#include <opencv2/opencv.hpp>

int main(int argc, const char *argv[])
{
    cv::Point3d p1(1, 0, 0);
    cv::Point3d p2(0, 1, 0);

    cv::Point3d cross_prod = p1.cross(p2);

    std::cout
        << "<" << cross_prod.x
        << ", " << cross_prod.y
        << ", " << cross_prod.z
        << ">"
        << std::endl;

    std::cout << "L2 norm: " << cv::norm(cross_prod) << std::endl;

    return 0;
}

The output:
<0, 0, 1>
L2 norm: 1


text:
Q: Tensorflow Serving - Error passing image to the server I managed to get the server to work, but I can't POST the image to my network. My network is a modification of the example, and when I post it it gives the following error.
"error": "inputs is a plain value/list, but expecting an object as multiple input tensors required as per tensorinfo_map"
My cliente side is:
import requests
import json
import cv2
import numpy as np
from PIL import Image

import nsvision as nv

img = cv2.imread(r'./temp.png')
_, img_encoded = cv2.imencode('.png', img)

headers = {"content-type": "application/json"}

data = json.dumps({"signature_name": "serving_default", "inputs": [img_encoded.tolist()] })

json_response = requests.post(url="http://172.104.198.143:8501/v1/models/API_model:predict", data = data, headers = headers)

print(json_response.text)

My signature:
signature_def['serving_default']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['image'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 200, 50, 1)
        name: serving_default_image:0
    inputs['label'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, -1)
        name: serving_default_label:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['ctc_loss'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 50, 37)
        name: StatefulPartitionedCall:0
  Method name is: tensorflow/serving/predict


text:
Q: Find correspondig key of a specific value in dictionary I have a dictionary which vlaues are list type and they are unique for each key.
d = {'key1': [1,2,3], 'key2': [4,5,6], 'key3': [7,8,9]}
And I have a variable called a = 3. Now I want to find the key corresponding to this variable.
Thanks for help.

A:
required_key = None
for key,value in d.items():
    if a in value:
        required_key = key
        break
print(required_key)


text:
Q: The div containing tags for a question doesn't reflow, causing layout issues for questions with long/many tags This appears to be a css bug which (I think) has recently been introduced. It's most visible when viewing questions on Stack Exchange sites using mobile devices (the full site with responsiveness, not the mobile site) but can easily be reproduced by resizing a browser window on a question where the combined width of the tags is large.
A couple of example questions show this behaviour:

*

*On Meta Stack Overflow: Why are questions based on misunderstanding about a tool closed as "no longer reproducible"?

*On Meta Stack Exchange: Please notify us when a question we ask or answer is closed or reopened

Using the Meta Stack Overflow question to demonstrate (as the total width of the tags is larger):

*

*At 1100px, the tags just about fit into their containing div.

*At 800px, the tags appear on top of related questions:

*At 450px, the tags are now wider than the view (the last tag is completely off the screen), causing scroll bars to appear:

This doesn't happen to lists of questions - the tags flow onto multiple lines:

Reproduced on: { Firefox 81, Chrome 84, Edge 84 } on Windows 10, and Chrome 85 on Android 11.

A: This appears to have been fixed - the tags now have wrapping, e.g.:


text:
Q: Angular2 ngFor elements with Material Design Lite I'm struggling to make Material Design Lite component to work with dynamically added elements via *ngFor. I understand that I need to call componentHandler.upgradeElement, but where do I put this call? I was trying this and this directives but they don't seem to work.
Specifically, I need mdl-menu on each item of my array. Any suggestions on where to look at?

A: TLDR; You need to call componentHandler.upgradeElement after the elements have been injected into the DOM. An approach I've used in the past is described in the example below.
EDIT If you want a declarative solution this approach here seem like a pretty good one, but I have not used it myself.
I created a service that wraps the Material Lite componentHandler
import { Injectable } from '@angular/core';

export interface ComponentHandler {
    upgradeDom();

}

declare var componentHandler: ComponentHandler;

@Injectable()
export class MaterialService {
    handler: ComponentHandler;
    constructor() {
        this.handler = componentHandler;
    }

    // render on next tick
    render() {
        setTimeout(() => { this.handler.upgradeDom(); }, 0);
    }

}

Then you call the service's render function after the component has injected the elements into the DOM. In your case this is after the *ngFor
This is a very contrived example but demonstrates "where" to call render
import { Component, OnInit } from '@angular/core';
import { DataService } from 'services/data.service';
import { MaterialService } from 'services/material.service';

@Component({
    selector: 'app-thing',
    templateUrl: `
       <ul>
            <li *ngFor="let item of data">
              {{data}}
            </li>
       </ul>
    `
})
export class ThingComponent implements OnInit {
    data: string[]
    constructor(
        private service: DataService,
        private material: MaterialService
    ) { }

    ngOnInit() {
        this.service.getData()
        .subscribe(data => {
            this.data = data;
            this.material.render();
        });
     }
}

A: Problem: MDL does not watch dynamically created DOM element.
Solution: MDL library adds componentHandler property onto Window object.
execute the below code inside ngOnInit() method of the component in which you are adding element dynamically.
setTimeout(() => {
  window['componentHandler'].upgradeDom();
}, 0);


text:
Q: Why does Ruby standard library Date Module start at -4712 year? Date.new results in # -4712-01-01.
Just as per the title, what logic am i missing, why start from -4712?

A: https://en.wikipedia.org/wiki/Julian_day
The Julian Period is a chronological interval of 7980 years beginning 4713 BC. It has been used by historians since its introduction in 1583 to convert between different calendars. 2015 is year 6728 of the current Julian Period. The next Julian Period begins in the year 3268 AD.

A: The internal representation of a Date or DateTime object is an astronomical Julian date: a fractional number of days since a "time zero" in 4712 BCE.
More information are also available in the Ruby documentation for Date.

The Julian day number is in elapsed days since noon (Greenwich mean time) on January 1, 4713 BCE (in the Julian calendar).
In this document, the astronomical Julian day number is same as the original Julian day number. And the chronological Julian day number is a variation of the Julian day number. Its days begin at midnight on local time.

From Wikipedia

The Julian day number can be calculated using the following formulas (integer division is used exclusively, that is, the remainder of all divisions are dropped):
The months (M) January to December are 1 to 12. For the year (Y) astronomical year numbering is used, thus 1 BC is 0, 2 BC is −1, and 4713 BC is −4712. D is the day of the month. JDN is the Julian Day Number, which pertains to the noon occurring in the corresponding calendar date.


text:
Q: Prevent Mobile on Desktop like Apple does I have a question that I have searched for hours and can't find any solution to my issue.
I am trying to make it so when you resize the browser the mobile versions and break points don't show when on a desktop.
So when you're on a desktop you should be able to resize the browser to a point where you will have to scroll horizontally, rather than showing a mixture of desktop and mobile version. apple.com does it where when you resize the browser it only goes so small and you never see the mobile version. Which you shouldn't because you're on a desktop.
Here is the site:
http://www.avrs.com/
To recreate the issue you can resize your browser and at about 1000px it breaks and is ugly. You may also say that I am doing the display: none; wrong which you are welcome to inform me of how to fix.
Also I am familiar with the http://getbootstrap.com/css/#responsive-utilities. But they didn't seem to fix this issue either.

A: The devs at Apple are using max-device-width (plus other media query rules, like dpi, min/max width, etc.) to determine if the mobile version will be shown. Because desktops typically have a larger physical screen, the max-device-width rules will rarely be shown on desktops (but it isn't full proof, as shown below - You'd want to look at adaptive design for a separation between desktops and mobile devices...)
You can test this by setting your resolution to something much smaller. Here's an example on my Macbook Pro at 720px x 450px (via Display Menu) running Chrome.

A: There are several techniques to achieve what you want. The easiest is to use CSS media-queries with specific properties.
Usually min-width or max-width are used for the CSS breakpoints to make your website mobile-friendly (Responsive Web Design). If you want to avoid this on desktop browsers you can use different properties with values specific to mobile devices:

*

*min-device-pixel-ratio

*min-device-width

*orientation
This source will provide more relevant information: article on css-tricks.
Another question is: Why would you want to make your website unresponsive and not user-friendly like that? In year 2014 I (and pretty much most of the users) expect websites to adapt to the browser's window size.
Scenario: I really like browsing websites with my browser on one half of the screen and eg. chatting with someone or watching a movie on the other half.
Consider this point. I think it's better to improve your website so it works nice in all different resolutions because you can never assume anything about your users and their devices (smartphones, tablets, netbooks, laptops, desktops…). Nowadays I can easily get a smartphone with higher resolution than my desktop computer, or a laptop with a touch screen.


text:
Q: Nested Serializers with django-rest-framework I'm trying to generate a nested Json output using django-rest-framework.
But can't find the correct way to go...
Can someone please drive me to correct direction?
Thanks a lot!
--
Here are my models:
class Pacmr(models.Model):
    package         = models.ForeignKey(Package)
    architecture    = models.ForeignKey(Architecture)
    component       = models.ForeignKey(Component)
    mirror          = models.ForeignKey(Mirror)
    release         = models.ForeignKey(Release)
    version         = DebVersionField()

Package, Architecture, Component, Mirror, Release are all equivalent to:
class Package(models.Model):
    name    = models.CharField(max_length=50)
    comment = models.CharField(max_length=200)

An example of the Pacmr table content:
SELECT id, package_id, architecture_id, component_id, mirror_id, release_id, version from pacmr_pacmr where package_id = 20671;

   id   | package_id | architecture_id | component_id | mirror_id | release_id |   version
--------+------------+-----------------+--------------+-----------+------------+--------------
 965201 |      20671 |             236 |          146 |        73 |        111 | 3.0-2.1b-1
 965200 |      20671 |             236 |          146 |        73 |        109 | 3.0-2.1b-2.1
 965199 |      20671 |             236 |          146 |        73 |        113 | 3.0-2.1a-5
 691277 |      20671 |             236 |          146 |        73 |        105 | 3.0-2.1b-3
 691276 |      20671 |             236 |          146 |        73 |        107 | 3.0-2.1b-3
 691275 |      20671 |             236 |          146 |        73 |        104 | 3.0-2.1b-3
 691274 |      20671 |             236 |          146 |        75 |        113 | 3.0-2.1a-5
 691273 |      20671 |             236 |          146 |        72 |        111 | 3.0-2.1b-1
 691272 |      20671 |             236 |          146 |        72 |        110 | 3.0-2.1b-1
 691271 |      20671 |             236 |          146 |        72 |        109 | 3.0-2.1b-2.1
 691270 |      20671 |             236 |          146 |        72 |        108 | 3.0-2.1b-2.1
 691269 |      20671 |             236 |          146 |        72 |        113 | 3.0-2.1a-5
 691268 |      20671 |             236 |          146 |        72 |        115 | 3.0-2.1a-5
 691267 |      20671 |             236 |          146 |        72 |        107 | 3.0-2.1b-3
 691266 |      20671 |             236 |          146 |        72 |        106 | 3.0-2.1b-3
 691265 |      20671 |             236 |          146 |        72 |        104 | 3.0-2.1b-3
 691264 |      20671 |             236 |          146 |        72 |        103 | 3.0-2.1b-3
 691263 |      20671 |             236 |          144 |        71 |         97 | 3.0-2.1b-2.1
 691262 |      20671 |             236 |          144 |        71 |         67 | 3.0-2.1b-3
 691261 |      20671 |             236 |          144 |        71 |        114 | 3.0-2.1b-3
 691260 |      20671 |             236 |          144 |        71 |         68 | 3.0-2.1b-3
 691259 |      20671 |             236 |          144 |        71 |        101 | 3.0-2.1b-3
 691258 |      20671 |             236 |          144 |        71 |        100 | 3.0-2.1b-3
 691257 |      20671 |             236 |          144 |        70 |         97 | 3.0-2.1b-2.1
 691256 |      20671 |             236 |          144 |        70 |         98 | 3.0-2.1b-2.1
 691255 |      20671 |             236 |          144 |        70 |         67 | 3.0-2.1b-3
 691254 |      20671 |             236 |          144 |        70 |         99 | 3.0-2.1b-3
 691253 |      20671 |             236 |          144 |        70 |         68 | 3.0-2.1b-3
 691252 |      20671 |             236 |          144 |        70 |         96 | 3.0-2.1b-3

With joins it look like this:
SELECT pacmr_pacmr.id as id, pacmr_package.name as package, pacmr_architecture.name as architecture, pacmr_component.name as component, pacmr_mirror.name as mirror, pacmr_release.name as release, version from pacmr_pacmr, pacmr_package, pacmr_architecture, pacmr_component, pacmr_mirror, pacmr_release where package_id=pacmr_package.id and architecture_id=pacmr_architecture.id and component_id=pacmr_component.id and mirror_id=pacmr_mirror.id and release_id=pacmr_release.id and package_id = 20671;

   id   | package | architecture | component |      mirror       |     release     |   version
--------+---------+--------------+-----------+-------------------+-----------------+--------------
 965201 | jvim    | source       | main      | debian            | etch            | 3.0-2.1b-1
 965200 | jvim    | source       | main      | debian            | lenny           | 3.0-2.1b-2.1
 965199 | jvim    | source       | main      | debian            | sarge           | 3.0-2.1a-5
 691277 | jvim    | source       | main      | debian            | sid             | 3.0-2.1b-3
 691276 | jvim    | source       | main      | debian            | squeeze         | 3.0-2.1b-3
 691275 | jvim    | source       | main      | debian            | wheezy          | 3.0-2.1b-3
 691274 | jvim    | source       | main      | debian-amd64      | sarge           | 3.0-2.1a-5
 691273 | jvim    | source       | main      | debian-production | etch            | 3.0-2.1b-1
 691272 | jvim    | source       | main      | debian-production | etch-testing    | 3.0-2.1b-1
 691271 | jvim    | source       | main      | debian-production | lenny           | 3.0-2.1b-2.1
 691270 | jvim    | source       | main      | debian-production | lenny-testing   | 3.0-2.1b-2.1
 691269 | jvim    | source       | main      | debian-production | sarge           | 3.0-2.1a-5
 691268 | jvim    | source       | main      | debian-production | sarge-testing   | 3.0-2.1a-5
 691267 | jvim    | source       | main      | debian-production | squeeze         | 3.0-2.1b-3
 691266 | jvim    | source       | main      | debian-production | squeeze-testing | 3.0-2.1b-3
 691265 | jvim    | source       | main      | debian-production | wheezy          | 3.0-2.1b-3
 691264 | jvim    | source       | main      | debian-production | wheezy-testing  | 3.0-2.1b-3
 691263 | jvim    | source       | universe  | ubuntu            | hardy           | 3.0-2.1b-2.1
 691262 | jvim    | source       | universe  | ubuntu            | lucid           | 3.0-2.1b-3
 691261 | jvim    | source       | universe  | ubuntu            | oneiric         | 3.0-2.1b-3
 691260 | jvim    | source       | universe  | ubuntu            | precise         | 3.0-2.1b-3
 691259 | jvim    | source       | universe  | ubuntu            | quantal         | 3.0-2.1b-3
 691258 | jvim    | source       | universe  | ubuntu            | raring          | 3.0-2.1b-3
 691257 | jvim    | source       | universe  | ubuntu-production | hardy           | 3.0-2.1b-2.1
 691256 | jvim    | source       | universe  | ubuntu-production | hardy-testing   | 3.0-2.1b-2.1
 691255 | jvim    | source       | universe  | ubuntu-production | lucid           | 3.0-2.1b-3
 691254 | jvim    | source       | universe  | ubuntu-production | lucid-testing   | 3.0-2.1b-3
 691253 | jvim    | source       | universe  | ubuntu-production | precise         | 3.0-2.1b-3
 691252 | jvim    | source       | universe  | ubuntu-production | precise-testing | 3.0-2.1b-3
(29 rows)

Here an example of what I would like to have with django-rest-framework (hand written):
{
    "package_id": 20671,
    "package": "jvim",
    "mirrors": [
        {
            "name": "debian",
            "components": [
                {
                    "name": "main",
                    "releases": [
                        {
                            "name": "etch",
                            "version": "3.0-2.1b-1"
                        },
                        {
                            "name": "lenny",
                            "version": "3.0-2.1b-2.1"
                        },
                        {
                            "name": "sarge",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "sid",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "squeeze",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "wheezy",
                            "version": "3.0-2.1b-3"
                        }
                    ]
                }
            ]
        },
        {
            "name": "debian-amd64",
            "components": [
                {
                    "name": "main",
                    "releases": [
                        {
                            "name": "sarge",
                            "version": "3.0-2.1a-5"
                        }
                    ]
                }
            ]
        },
        {
            "name": "debian-production",
            "components": [
                {
                    "name": "main",
                    "releases": [
                        {
                            "name": "etch",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "etch-testing",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "lenny",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "lenny-testing",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "sarge",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "sarge-testing",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "squeeze",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "squeeze-testing",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "wheezy",
                            "version": "3.0-2.1a-5"
                        },
                        {
                            "name": "wheezy-testing",
                            "version": "3.0-2.1a-5"
                        }
                    ]
                }
            ]
        },
        {
            "name": "ubuntu",
            "components": [
                {
                    "name": "universe",
                    "releases": [
                        {
                            "name": "hardy",
                            "version": "3.0-2.1b-2.1"
                        },
                        {
                            "name": "lucid",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "oneiric",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "precise",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "quantal",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "raring",
                            "version": "3.0-2.1b-3"
                        }
                    ]
                }
            ]
        },
        {
            "name": "ubuntu-production",
            "components": [
                {
                    "name": "universe",
                    "releases": [
                        {
                            "name": "hardy",
                            "version": "3.0-2.1b-2.1"
                        },
                        {
                            "name": "hardy-testing",
                            "version": "3.0-2.1b-2.1"
                        },
                        {
                            "name": "lucid",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "lucid-testing",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "precise",
                            "version": "3.0-2.1b-3"
                        },
                        {
                            "name": "precise-testing",
                            "version": "3.0-2.1b-3"
                        }
                    ]
                }
            ]
        }
    ]
}

A: Answer myself...
Found a solution based on Django REST framework: non-model serializer
Maybe a better solution could be implemented?
class Pmcra(object):
    package    = None
    package_id = None

    def __init__(self, package, *args, **kw):
        self.package = package
        pass

    def do_work(self):

        my_dict = {}

        if self.package:
            pacmrs = Pacmr.objects.filter(package__name=self.package)
            mirrors = pacmrs.all().distinct('mirror')
            mirrors_array = []
            for mirror in mirrors:
                self.package_id = mirror.package.id
                components = mirrors.filter(mirror=mirror.mirror).distinct('component')
                components_array = []
                for component in components:
                    releases = components.filter(component=component.component).distinct('release')
                    releases_array = []
                    for release in releases:
                        releases_array.append( {'name': release.release.__str__(), 'version': release.version.__str__() })
                    components_array.append( {'name': component.component.__str__(), 'releases': releases_array} )
                mirrors_array.append( {'name': mirror.mirror.__str__(), 'components': components_array} )

            return { 'package': self.package, 'package_id': self.package_id, 'mirrors': mirrors_array }

class MyView(APIView):

    def get(self, request, *args, **kw):
        # Process any get params that you may need
        # If you don't need to process get params,
        # you can skip this part
        get_arg1 = request.GET.get('pkg', None)

        # Any URL parameters get passed in **kw
        myClass = Pmcra(get_arg1, *args, **kw)
        result = myClass.do_work()
        response = Response(result, status=status.HTTP_200_OK)
        return response


text:
Q: How do I use a value that is returned from a Macro Variable in another macro I have simplified this a lot so it can be repeated
%macro macro_one(dt2);
  %let var1 = &dt2;
%mend;

Then I have another macro and I want to use the output from macro one in macro 2
%macro macro_print(dt2);
  /*call macro 1*/
  %macro_one(&dt2);
  %put &var1;
%mend;

/call macro/
%macro_print('purple');

It should print purple in the logs but I get an error
I get an error though - i suspect I need to assign the macro variable from macro one when I call macro two.

A: First, I suspect you have a typo between your code and here.  Proper way to define a macro is:
%macro blah(x);
<do stuff>
%mend;

not:
%macro_blah(x);
<do stuff>
%mend;

The macro is created in %macro_one and defaults to a local scope.  You can fix this by declaring it %global.
%macro macro_one(dt2);
   %global var1;
   %let var1=&dt2;
%mend;

Also, use %put not put in %macro_two.