text:
Q: PowerShell : retrieve JSON object by field value Consider JSON in this format :
"Stuffs": [
    {
        "Name": "Darts",
        "Type": "Fun Stuff"
    },
    {
        "Name": "Clean Toilet",
        "Type": "Boring Stuff"
    }
]

In PowerShell 3, we can obtain a list of Stuffs :
$JSON = Get-Content $jsonConfigFile | Out-String | ConvertFrom-Json

Assuming we don't know the exact contents of the list, including the ordering of the objects, how can we retrieve the object(s) with a specific value for the Name field ?
Brute force, we could iterate through the list :
foreach( $Stuff in $JSON.Stuffs ) {

But I am hopeful there exists a more direct mechanism ( similar to Lync or Lambda expressions in C# ).

A: Hows about this:
$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value

which would select from json structured
{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}

This is based on this accessing values in powershell SO question
. Isn't powershell fabulous!

A: I just asked the same question here: https://stackoverflow.com/a/23062370/3532136
It has a good solution. I hope it helps ^^.
In resume, you can use this:
The Json file in my case was called jsonfile.json:
{
    "CARD_MODEL_TITLE": "OWNER'S MANUAL",
    "CARD_MODEL_SUBTITLE": "Configure your download",
    "CARD_MODEL_SELECT": "Select Model",
    "CARD_LANG_TITLE": "Select Language",
    "CARD_LANG_DEVICE_LANG": "Your device",
    "CARD_YEAR_TITLE": "Select Model Year",
    "CARD_YEAR_LATEST": "(Latest)",
    "STEPS_MODEL": "Model",
    "STEPS_LANGUAGE": "Language",
    "STEPS_YEAR": "Model Year",
    "BUTTON_BACK": "Back",
    "BUTTON_NEXT": "Next",
    "BUTTON_CLOSE": "Close"
}

Code:
$json = (Get-Content "jsonfile.json" -Raw) | ConvertFrom-Json

$json.psobject.properties.name

Output:
CARD_MODEL_TITLE
CARD_MODEL_SUBTITLE
CARD_MODEL_SELECT
CARD_LANG_TITLE
CARD_LANG_DEVICE_LANG
CARD_YEAR_TITLE
CARD_YEAR_LATEST
STEPS_MODEL
STEPS_LANGUAGE
STEPS_YEAR
BUTTON_BACK
BUTTON_NEXT
BUTTON_CLOSE

Thanks to mjolinor.

A: In regards to PowerShell 5.1 ...
Operating off the assumption that we have a file named jsonConfigFile.json with the following content from your post:
{
    "Stuffs": [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },
        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}

This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}

(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
    ForEach-Object { $json[$_.Name] = $_.Value }

$json.Stuffs will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type key's value associated with the Clean Toilet key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type

It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.

A: David Brabant's answer led me to what I needed, with this addition:
x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

A: This is my json data:
[
   {
      "name":"Test",
      "value":"TestValue"
   },
   {
      "name":"Test",
      "value":"TestValue"
   }
]

Powershell script:
$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json

foreach ($line in $data) {
     $line.name
}

A: $json = @"
{
"Stuffs":
    [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },

        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}
"@

$x = $json | ConvertFrom-Json

$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts


text:
Q: How to go about working with a Web Service Hi All below is a WebService Class which i would like to use (i wrote it). The problem is i am not quite sure how to go about using it. I have a WinForm that Connects to a DB through another instance of DataAccessObject.
The user must be able to click a button which will open the website version of the form and modify the database from there.
The Problem is i don't know how to Use The Service To Do so
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;
using System.Configuration;

/// <summary>
/// Summary description for DataManager
/// </summary>
[WebService(Namespace = "/201103578Site//Default.aspx")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment         the following line.
//[System.Web.Script.Services.ScriptService]

public class DataManager : System.Web.Services.WebService
{
    XElement[] xmlCompany = null;
    XElement[] xmlCandidate = null;
    XElement[] xmlQualification = null;

    public DataManager ()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
        DataAccessObject.DataAccessObject daoDataBase = new     DataAccessObject.DataAccessObject(ConfigurationManager.ConnectionStrings[1].ToString());
        daoDataBase.openConnection();

        xmlCompany = daoDataBase.sqlSelectCompany(new SQL.SqlImplementation(), "Select     * From Company");
        xmlCandidate = daoDataBase.sqlSelectCandidate(new SQL.SqlImplementation(),     "Select * From Candidate");
        xmlQualification = daoDataBase.sqlSelectQualification(new     SQL.SqlImplementation(), "Select * From Qualification");
        daoDataBase.closeConnection();
    }

    [WebMethod]
    public XElement[] getXmlCompany()
    {
        return xmlCompany;
    }

    [WebMethod]
    public XElement[] getXmlCandidate()
    {
        return xmlCandidate;
    }

    [WebMethod]
    public XElement[] getXmlQualification()
    {
        return xmlQualification;
    }

}

I would like to call the getXmlCompany and any of the other methods from the Company.aspx.cs file like one would any other method - if possible
Kind Regards
Markus

A: When you debug the web service, if everything is right, you will see a list of your web methods there. Now, copy the url in the browser, go to the project that need to use it, add web reference and past the url in. It will look and display your webserivice.
Further more, you can look into hosting your webservice in IIS so you don't have to run debug every time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Carrierwave Mongoid validation of file I cant figure out how to validate that carrierwave has uploaded a document to my mongoid object.
i have a Document Class
class Content::Document < Content

  mount_uploader :attachment, DocumentUploader

  field :attachable_id
  field :attachable_type
end

and an uploader:
require 'carrierwave/orm/mongoid'
class DocumentUploader < CarrierWave::Uploader::Base

  storage = :filesystem
  include CarrierWave::RMagick

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_white_list
    %w(doc docx xls xlsx ppt pptx pdf )
  end

i would like to validate that the upload exists and that it matches the white list else through a standard validation error
this is on Rails 2.3.8

A: While it's true that Carrierwave does have extensive tests, you could test for validity with something like this:
it "is valid with valid attributes" do
    file_bytes = File.open("spec/binary/avatar.png")
    valid_attrs = {:name => "foo", :description => "bar", :avatar => file_bytes}
    user = User.new(valid_attrs)
    user.should be_valid
  end

Hope that helps!

A: In general you don't need to do that since this behaviour is already tested in carrierwave specs itself.
You can test your uploaders in isolation, using Carrierwave test helpers. E.g. I would just write a spec like
attachment_uploader.extension_white_list.should =~ %w(doc docx xls xlsx ppt pptx pdf)

But if you insist on testing that I would suggest using FakeFS to stub filesystem and then check with
File.exists? document.attachment.current_path

whether attachment has been created.


text:
Q: Page Break Adjustment In Long Documents Has anyone else had trouble in relocating page breaks in a long document? In a ~45 page long document I wanted to keep certain things on the same page. The system worked on the first three or four changes although it took a rather long time on each adjustment. On the next change the program seemed to lock up in a loop. The text on the screen vanished and the program was unresponsive. The CPU meter indicated MMA was working rather hard. I had to Alt F4 to get out. I repeated the problem twice.
Other than breaking the document into small pieces does anyone have a suggestion?


text:
Q: ASP.NET - how does aspnet_isapi.dll construct page class We all know that when a request for abc.aspx is received, the aspnet_isapi.dll works on it and calls the page's processrequest method. My question is how does it create instance of page class and how does it call the page life cycle. Which pattern does it implement?
Well, all of us know that ASP.NET runtime calls the handler's ProcessRequest to start the process. My question is how does it do that. On basis of page name (abc.aspx", it creates that class of abc and calls some methods of that class. Now how does it creates object of abc, is my question.

A: Here are the stages that occur between receiving a request and sending a response.

This is the application life cycle

The Execute handler stage, where the handler (a module scoped to a
  URL) is invoked to construct the response. For .aspx files, the
  PageHandlerFactory handler is used to respond to the request. For
  static files, the native-code StaticFileModule module responds to the
  request.

This is done by the PageHandlerFactory

The PageHandlerFactory creates instances of classes that inherit from
  the Page class and implement the IHttpHandler interface. Instances are
  created dynamically to handle requests for ASP.NET files. The
  PageHandlerFactory class is the default handler factory implementation
  for ASP.NET pages.
The PageHandlerFactory class implements the IHttpHandlerFactory
  interface to provide the default HTTP handler for ASP.NET files. The
  PageHandlerFactory calls the ASP.NET compilation system to compile, if
  necessary, and return the exact type corresponding to the URL, and
  then creates an instance of that type. The page type inherits from the
  Page class and implements the IHttpHandler interface.

A: I think this is what you are looking for..
http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp

A: This sort of thing is well documented:
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

A: You can try with this code based on HttpContext.Response.Redirect
public void ProcessRequest(HttpContext context)
{
        context.Response.Write("
This is an HttpHandler Test.
");
        context.Response.Redirect("YourPage.aspx");
}


text:
Q: Difficulty proving / finding witnesses for the following Functions (Big O and Big Ω and $\Theta) I have left with some functions I can't find witenesses for proving Big O and Big Ω  and Big $\Theta$ relations.
Notice that I should prove the following using the defintion and not any complex method (i.e. limits, integrals and so....)
Here are the function I need your help / hint how to start after using the defintion
$ (n_0, c, \dots  )$:

*

*$n^5 -2\log n = \Omega(n^5)$

*$\log(n^2 +13) = \Theta(\log n)$

*If $f(n) = O (g(n))  $ then $2^{f(n)} = O(2^{g(n)})$
Notice that the 3rd one contains some "Text Math" because I couldn't put an expression in the exponent.
That's all,
Thank you in advance!

A: HINTS:
(1) Note that $\log n<n$, so $n^5-2\log n>n^5-2n$; now show that $2n\le\frac12n^5$ for $n\ge 2$.
(2) Clearly $\log n\le\log(n^2+13)$. In the other direction, $\log(n^2+13)\le\log n^3=3\log n$ for $n\ge 3$, as you can verify by proving that $n^3\ge n^2+13$ for $n\ge 3$.
(3) is false: try $f(n)=2n$ and $g(n)=n$.


text:
Q: What are some good resources for learning how to implement Scheme Macros? I've written a Scheme-ish language compiler/vm in JavaScript. http://github.com/z5h/zb-lisp
Dybvig's "Three Scheme Implementations" paper (available on my github) was hugely important in getting stuff like tail-call-optimization, call/cc and other things working.
I'm thinking about adding some type of macro support. And wondering if there are similarly awesome references for implementing macro systems.
Thanks.

A: Lisp in Small Pieces is what you need.


text:
Q: Changing order of integration in a double integral The question was to sketch the region of integration and change the order of integration.
$$\int^{3}_{0} \int^{\sqrt{9-y}}_{0} f(x,y) dxdy$$
When I sketch the region of integration I do not see a way that it is possible to change the order of integration.
My region is bounded by, $y=3$, $y=0$, $x=0$ and $x=\sqrt{9-y}$.
Any insight would help, if there is a way to do this then I guess I have it sketched wrong.
My image is below of what I drew

A: The integration is performed over the region where $0\le y\le3$ and $0\le x\le\sqrt{9-y}$. This is the region shown below

So to change the order of integration, we need to define the upper $x$ boundary by a piecewise function or write the integral as the sum of two integrals:
$$
\int_0^{\sqrt6}\int_0^3f(x,y)\,\mathrm{d}y\,\mathrm{d}x
+\int_{\sqrt6}^3\int_0^{9-x^2}f(x,y)\,\mathrm{d}y\,\mathrm{d}x
$$

A: Try to express y in terms of x, and then figure out what that means about the bounds of x, which become constants.


text:
Q: How can I control what git repository branches are included as releases in satis? We're currently using git flow to manage feature and hotfix branches in git, and satis to manage packages. Is there any way to tell satis to only list tagged branches as a release rather than listing every single branch that has been created?

A: Only tags are releases. Branches are no releases, they are moving targets, but they do exist.
You can try to create a release-only repo that does only contain your tags, but no branches, and grab the Satis metadata from there.
You could also run a cleanup script that removes any branches from the JSON data structure that you don't like.
You could simply ignore the branches, because they do not affect your workflow if you do use semantic versioning and require explicit version numbers instead of branches.


text:
Q: Enable session for complete webservice I have a web service. I have around 15 web methods in it. Now I want to use session variables. To enable session we can use WebMethodAttribute.EnableSession Property like below for each web method
[WebMethod(EnableSession=true)]
public string GetSomeDetails() {}

But instead of writing for all web methods, I want to do it in only one place. So is there any way to enable session for complete WebService.

A: I don't think there is a built in solution for this. Here is a postsharp solution.


text:
Q: Generating series numbers with adding String at middle Am writing JavaScript plugin to one of my client, in this i need to generate a series strings like "1,2,D,3,4" / "1,D,2,3,4,5,6". length can be n numbers. "D" positions are stored in a separate string like 2,4. Here, based upon this length we want to generate like below
String = 1,2,3,4,5 D Positions: 2,4
Final result should be: 1,D,2,D,3
Something i tried,
 var deletedString = "2,4"
    var Values = "1,2,3,4,5,6";
    var lengthFromValues = SplitString_ToArray(Values).length;
    var deletedArray = splitString_ToArray(deletedString);
    var temp_arr = [];
    for(var i = 1; i <= lengthFromValues; i++) {
        if(deletedArray[i-1] > 0) {
          temp_arr.push("D");
        } else temp_arr.push(i);
    }
alert(temp_arr.toString());

Note: SplitString_ToArray function is a self written function which will convert(split) string to array.
Will someone help me?

A: Check this I've changed a logic a bit. Actually you can use deletedString values to replace values in Values that you convert to array and then you just put the array back to string. jsFiddle
var deletedString = "2,4"
var Values = "1,2,3,4,5,6";
var deletedArray = SplitString_ToArray(deletedString);
var valuesArray = SplitString_ToArray(Values);
var finalLength = valuesArray.length;

for (i=0; i< deletedArray.length; i++){
    console.log(deletedArray[i]);
    var idxToReplace = parseInt(deletedArray[i]-1); // substract 1, because your indexes are 1-based
    valuesArray.splice(idxToReplace,0,'D');
}

// back to string
valuesArray = valuesArray.slice(0, finalLength);
var result = valuesArray.join();
alert(result);

function SplitString_ToArray(inString){
    var result = inString.split(',');
    console.log(result);
    return result;
}

A: Using a forEach loop this should do it:
var deletedString = "2,4";
var Values = "1,2,3,4,5,6";

var toDelete = deletedString.split(','),
    allValues = Values.split(','),
    length = allValues.length;

toDelete.sort(function(a, b) {return a - b;});

toDelete.forEach(function(position) {
    allValues.splice(parseInt(position) - 1, 0, 'D');
});

var newValues = allValues.splice(0, length).join();
alert(newValues);

A: var deletedString = "2,4"; /* Sort the values */
var Values = "1,2,3,4,5,6";

var allValues = Values.split(','),
    length = allValues.length;

deletedString.split(',').forEach(function(position) {
    allValues.splice(parseInt(position) - 1, 0, 'D');
});

var newValues = allValues.splice(0, length).join();
alert(newValues);


text:
Q: Regarding Chip Pearson's ReverseArrayInPlace function, how does a user pass an array to the input function in the first place? In an attempt to learn how to reverse a 1-D array, several Google searches point to Chip Pearson's ReverseArrayInPlace function (see here http://www.cpearson.com/excel/vbaarrays.htm).
For Ndx = LBound(InputArray) To ((UBound(InputArray) - LBound(InputArray) + 1) \ 2)
'swap the elements
Temp = InputArray(Ndx)
InputArray(Ndx) = InputArray(Ndx2)
InputArray(Ndx2) = Temp
' decrement the upper index
Ndx2 = Ndx2 - 1
Next Ndx

However, as a very novice vba coder, I am confused about two things:

*

*How does a user pass a particular range to the InputArray?

*How would a user print the reversed array to a worksheet? Would they simply print the Temp array?

A: This is the entire function (minus the part that checks the dimensions of the array).
It needs one parameter that is an array, it can also accept an optional boolean.
Public Function ReverseArrayInPlace(InputArray As Variant, _
    Optional NoAlerts As Boolean = False) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ReverseArrayInPlace
' This procedure reverses the order of an array in place -- this is, the array variable
' in the calling procedure is reversed. This works only on single-dimensional arrays
' of simple data types (String, Single, Double, Integer, Long). It will not work
' on arrays of objects. Use ReverseArrayOfObjectsInPlace to reverse an array of objects.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim Temp As Variant
Dim Ndx As Long
Dim Ndx2 As Long

'''''''''''''''''''''''''''''''''
' Set the default return value.
'''''''''''''''''''''''''''''''''
ReverseArrayInPlace = False

'''''''''''''''''''''''''''''''''
' ensure we have an array
'''''''''''''''''''''''''''''''''
If IsArray(InputArray) = False Then
    If NoAlerts = False Then
        MsgBox "The InputArray parameter is not an array."
    End If
    Exit Function
End If

Ndx2 = UBound(InputArray)
''''''''''''''''''''''''''''''''''''''
' loop from the LBound of InputArray to
' the midpoint of InputArray
''''''''''''''''''''''''''''''''''''''
For Ndx = LBound(InputArray) To ((UBound(InputArray) - LBound(InputArray) + 1) \ 2)
    'swap the elements
    Temp = InputArray(Ndx)
    InputArray(Ndx) = InputArray(Ndx2)
    InputArray(Ndx2) = Temp
    ' decrement the upper index
    Ndx2 = Ndx2 - 1
Next Ndx

''''''''''''''''''''''''''''''''''''''
' OK - Return True
''''''''''''''''''''''''''''''''''''''
ReverseArrayInPlace = True

End Function

This sub will call the reversing function.
Sub test()
    Dim arr(20) As Long
    Dim i As Long

    For i = 0 To 20

        arr(i) = i
        Debug.Print arr(i)
    Next
    Dim success As Boolean
    success = ReverseArrayInPlace(arr)
    Debug.Print success
    For i = 0 To 20
        Debug.Print arr(i)
    Next
End Sub

Since arrays are by default passed by reference the original array has been modified, no need to return it.


text:
Q: Computing the inverse of a matrix using lapack in C I would like to be able to compute the inverse of a general NxN matrix in C/C++ using lapack.
My understanding is that the way to do an inversion  in lapack is by using the dgetri function, however, I can't figure out what all of its arguments are supposed to be.
Here is the code I have:
void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);

int main(){

    double M [9] = {
        1,2,3,
        4,5,6,
        7,8,9
    };

    return 0;
}

How would you complete it to obtain the inverse of the 3x3 matrix M using dgetri_?

A: Here is a working version of the above using OpenBlas interface to LAPACKE.
Link with openblas library (LAPACKE is already contained)
#include <stdio.h>
#include "cblas.h"
#include "lapacke.h"

// inplace inverse n x n matrix A.
// matrix A is Column Major (i.e. firts line, second line ... *not* C[][] order)
// returns:
//   ret = 0 on success
//   ret < 0 illegal argument value
//   ret > 0 singular matrix

lapack_int matInv(double *A, unsigned n)
{
    int ipiv[n+1];
    lapack_int ret;

    ret =  LAPACKE_dgetrf(LAPACK_COL_MAJOR,
                          n,
                          n,
                          A,
                          n,
                          ipiv);

    if (ret !=0)
        return ret;

    ret = LAPACKE_dgetri(LAPACK_COL_MAJOR,
                       n,
                       A,
                       n,
                       ipiv);
    return ret;
}

int main()
{
    double A[] = {
        0.378589,   0.971711,   0.016087,   0.037668,   0.312398,
        0.756377,   0.345708,   0.922947,   0.846671,   0.856103,
        0.732510,   0.108942,   0.476969,   0.398254,   0.507045,
        0.162608,   0.227770,   0.533074,   0.807075,   0.180335,
        0.517006,   0.315992,   0.914848,   0.460825,   0.731980
    };

    for (int i=0; i<25; i++) {
        if ((i%5) == 0) putchar('\n');
        printf("%+12.8f ",A[i]);
    }
    putchar('\n');

    matInv(A,5);

    for (int i=0; i<25; i++) {
        if ((i%5) == 0) putchar('\n');
        printf("%+12.8f ",A[i]);
    }
    putchar('\n');
}

Example:
% g++ -I [OpenBlas path]/include/ example.cpp [OpenBlas path]/lib/libopenblas.a
% a.out

+0.37858900  +0.97171100  +0.01608700  +0.03766800  +0.31239800
+0.75637700  +0.34570800  +0.92294700  +0.84667100  +0.85610300
+0.73251000  +0.10894200  +0.47696900  +0.39825400  +0.50704500
+0.16260800  +0.22777000  +0.53307400  +0.80707500  +0.18033500
+0.51700600  +0.31599200  +0.91484800  +0.46082500  +0.73198000

+0.24335255  -2.67946180  +3.57538817  +0.83711880  +0.34704217
+1.02790497  -1.05086895  -0.07468137  +0.71041070  +0.66708313
-0.21087237  -4.47765165  +1.73958308  +1.73999641  +3.69324020
-0.14100897  +2.34977565  -0.93725915  +0.47383541  -2.15554470
-0.26329660  +6.46315378  -4.07721533  -3.37094863  -2.42580445

A: Here is the working code for computing the inverse of a matrix using lapack in C/C++:
#include <cstdio>

extern "C" {
    // LU decomoposition of a general matrix
    void dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO);

    // generate inverse of a matrix given its LU decomposition
    void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);
}

void inverse(double* A, int N)
{
    int *IPIV = new int[N];
    int LWORK = N*N;
    double *WORK = new double[LWORK];
    int INFO;

    dgetrf_(&N,&N,A,&N,IPIV,&INFO);
    dgetri_(&N,A,&N,IPIV,WORK,&LWORK,&INFO);

    delete[] IPIV;
    delete[] WORK;
}

int main(){

    double A [2*2] = {
        1,2,
        3,4
    };

    inverse(A, 2);

    printf("%f %f\n", A[0], A[1]);
    printf("%f %f\n", A[2], A[3]);

    return 0;
}

A: First, M has to be a two-dimensional array, like double M[3][3]. Your array is, mathematically speaking, a 1x9 vector, which is not invertible.

*

*N is a pointer to an int for the
order of the matrix - in this case,
N=3.

*A is a pointer to the LU
factorization of the matrix, which
you can get by running the LAPACK
routine dgetrf.

*LDA is an integer for the "leading
element" of the matrix, which lets
you pick out a subset of a bigger
matrix if you want to just invert a
little piece. If you want to invert
the whole matrix, LDA should just be
equal to N.

*IPIV is the pivot indices of the
matrix, in other words, it's a list
of instructions of what rows to swap
in order to invert the matrix. IPIV
should be generated by the LAPACK
routine  dgetrf.

*LWORK and WORK are the "workspaces"
used by LAPACK. If you are inverting
the whole matrix, LWORK should be an
int equal to N^2, and WORK should be
a double array with LWORK elements.

*INFO is just a status variable to
tell you whether the operation
completed successfully. Since not all
matrices are invertible, I would
recommend that you send this to some
sort of error-checking system. INFO=0 for successful operation, INFO=-i if the i'th argument had an incorrect input value, and INFO > 0 if the matrix is not invertible.
So, for your code, I would do something like this:
int main(){

    double M[3][3] = { {1 , 2 , 3},
                       {4 , 5 , 6},
                       {7 , 8 , 9}}
    double pivotArray[3]; //since our matrix has three rows
    int errorHandler;
    double lapackWorkspace[9];

    // dgetrf(M,N,A,LDA,IPIV,INFO) means invert LDA columns of an M by N matrix
    // called A, sending the pivot indices to IPIV, and spitting error
    // information to INFO.
    // also don't forget (like I did) that when you pass a two-dimensional array
    // to a function you need to specify the number of "rows"
    dgetrf_(3,3,M[3][],3,pivotArray[3],&errorHandler);
    //some sort of error check

    dgetri_(3,M[3][],3,pivotArray[3],9,lapackWorkspace,&errorHandler);
    //another error check

    }

A: Here is a working version of Spencer Nelson's example above. One mystery about it is that the input matrix is in row-major order, even though it appears to call the underlying fortran routine dgetri.  I am led to believe that all the underlying fortran routines require column-major order, but I am no expert on LAPACK, in fact, I'm using this example to help me learn it.  But, that one mystery aside:
The input matrix in the example is singular. LAPACK tries to tell you that by returning a 3 in the errorHandler.  I changed the 9 in that matrix to a 19, getting an errorHandler of 0 signalling success, and compared the result to that from Mathematica. The comparison was also successful and confirmed that the matrix in the example should be in row-major order, as presented.
Here is the working code:
#include <stdio.h>
#include <stddef.h>
#include <lapacke.h>

int main() {
    int N = 3;
    int NN = 9;
    double M[3][3] = { {1 , 2 , 3},
                       {4 , 5 , 6},
                       {7 , 8 , 9} };
    int pivotArray[3]; //since our matrix has three rows
    int errorHandler;
    double lapackWorkspace[9];

    // dgetrf(M,N,A,LDA,IPIV,INFO) means invert LDA columns of an M by N matrix
    // called A, sending the pivot indices to IPIV, and spitting error information
    // to INFO. also don't forget (like I did) that when you pass a two-dimensional
    // array to a function you need to specify the number of "rows"
    dgetrf_(&N, &N, M[0], &N, pivotArray, &errorHandler);
    printf ("dgetrf eh, %d, should be zero\n", errorHandler);

    dgetri_(&N, M[0], &N, pivotArray, lapackWorkspace, &NN, &errorHandler);
    printf ("dgetri eh, %d, should be zero\n", errorHandler);

    for (size_t row = 0; row < N; ++row)
    {   for (size_t col = 0; col < N; ++col)
        {   printf ("%g", M[row][col]);
            if (N-1 != col)
            {   printf (", ");   }   }
        if (N-1 != row)
        {   printf ("\n");   }   }

    return 0;   }

I built and ran it as follows on a Mac:
gcc main.c -llapacke -llapack
./a.out

I did an nm on the LAPACKE library and found the following:
liblapacke.a(lapacke_dgetri.o):
                 U _LAPACKE_dge_nancheck
0000000000000000 T _LAPACKE_dgetri
                 U _LAPACKE_dgetri_work
                 U _LAPACKE_xerbla
                 U _free
                 U _malloc

liblapacke.a(lapacke_dgetri_work.o):
                 U _LAPACKE_dge_trans
0000000000000000 T _LAPACKE_dgetri_work
                 U _LAPACKE_xerbla
                 U _dgetri_
                 U _free
                 U _malloc

and it looks like there is a LAPACKE [sic] wrapper that would presumably relieve us of having to take addresses everywhere for fortran's convenience, but I am probably not going to get around to trying it because I have a way forward.
EDIT
Here is a working version that bypasses LAPACKE [sic], using LAPACK fortran routines directly.  I do not understand why a row-major input produces correct results, but I confirmed it again in Mathematica.
#include <stdio.h>
#include <stddef.h>

int main() {
    int N = 3;
    int NN = 9;
    double M[3][3] = { {1 , 2 ,  3},
                       {4 , 5 ,  6},
                       {7 , 8 , 19} };
    int pivotArray[3]; //since our matrix has three rows
    int errorHandler;
    double lapackWorkspace[9];
    /* from http://www.netlib.no/netlib/lapack/double/dgetrf.f
      SUBROUTINE DGETRF( M, N, A, LDA, IPIV, INFO )
      *
      *  -- LAPACK routine (version 3.1) --
      *     Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd..
      *     November 2006
      *
      *     .. Scalar Arguments ..
      INTEGER            INFO, LDA, M, N
      *     ..
      *     .. Array Arguments ..
      INTEGER            IPIV( * )
      DOUBLE PRECISION   A( LDA, * )
    */

    extern void dgetrf_ (int * m, int * n, double * A, int * LDA, int * IPIV,
                         int * INFO);

    /* from http://www.netlib.no/netlib/lapack/double/dgetri.f
       SUBROUTINE DGETRI( N, A, LDA, IPIV, WORK, LWORK, INFO )
       *
       *  -- LAPACK routine (version 3.1) --
       *     Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd..
       *     November 2006
       *
       *     .. Scalar Arguments ..
       INTEGER            INFO, LDA, LWORK, N
       *     ..
       *     .. Array Arguments ..
       INTEGER            IPIV( * )
       DOUBLE PRECISION   A( LDA, * ), WORK( * )
    */

    extern void dgetri_ (int * n, double * A, int * LDA, int * IPIV,
                         double * WORK, int * LWORK, int * INFO);

    // dgetrf(M,N,A,LDA,IPIV,INFO) means invert LDA columns of an M by N matrix
    // called A, sending the pivot indices to IPIV, and spitting error information
    // to INFO. also don't forget (like I did) that when you pass a two-dimensional
    // array to a function you need to specify the number of "rows"
    dgetrf_(&N, &N, M[0], &N, pivotArray, &errorHandler);
    printf ("dgetrf eh, %d, should be zero\n", errorHandler);

    dgetri_(&N, M[0], &N, pivotArray, lapackWorkspace, &NN, &errorHandler);
    printf ("dgetri eh, %d, should be zero\n", errorHandler);

    for (size_t row = 0; row < N; ++row)
    {   for (size_t col = 0; col < N; ++col)
        {   printf ("%g", M[row][col]);
            if (N-1 != col)
            {   printf (", ");   }   }
        if (N-1 != row)
        {   printf ("\n");   }   }
    return 0;   }

built and run like this:
$ gcc foo.c -llapack
$ ./a.out
dgetrf eh, 0, should be zero
dgetri eh, 0, should be zero
-1.56667, 0.466667, 0.1
1.13333, 0.0666667, -0.2
0.1, -0.2, 0.1

EDIT
The mystery no longer appears to be a mystery.  I think the computations are being done in column-major order, as they must, but I am both inputting and printing the matrices as if they were in row-major order. I have two  bugs that cancel each other out so things look row-ish even though they're column-ish.


text:
Q: using 'printf' to return string, not print it This may sound strange, but here goes.
I like using this technique of building a string in php
printf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2());

Obviously this directly prints the results whenever the function is called, but I would like to use this technique to just build a string, and then use it later elsewhere.
Is this possible?
Thanks guys.

A: Use sprintf to do this:
$var = sprintf(__('This is %1$s, this is %2$s'), myFunction1(), myFunction2());


text:
Q: Why Git ignores ~/.ssh/id_rsa, wants ~/.ssh/id_dsa or ~/.ssh/id_ecdsa? This is the error I'm receiving:
no such identity: /home/eduan/.ssh/id_dsa: No such file or directory
no such identity: /home/eduan/.ssh/id_ecdsa: No such file or directory
Permission denied (publickey).

That's what happens when I try to push, or in this case when I do ssh -T git@github.com.
I have correctly generated the id_rsa and id_rsa.pub files.
How may I go about solving this? I'm using Arch Linux with E17 BTW.
EDIT:
Regarding the answer by @kostix, who also edited this question: Would the below work for this?
Host github.com
    IdentityFile ~/.ssh/id_rsa

It doesn't seem to work for me yet... I get the following when I push with Git:
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I made sure the repo exists, and I also updated the remote URL with git remote set-url origin git@github.com:Greduan/dotfiles.git.
I also added the SSH key to the list of accepted SSH keys in GitHub. What else should I do?

A: The SSH client tells you about id_dsa (note the "d" — it stands for DSA) while you've generated id_rsa (note the "r" which stands for RSA).
You should either generate a DSA key or tell SSH which "identity" (the private key) to use. This could be done using the IdentityFile directive under a custom Host entry in your ~/.ssh/config file for the github remote (see the ssh_config(5) manual page).
Update (2013-04-29, to make it clearer for the next reader). The essense of the problem was that the OP has wrong owner (root) on his ~/.ssh/id_rsa key, so the OpenSSH client first tried to read that key, failed, and then went on trying to read ~/.ssh/id_dsa and ~/.ssh/id_ecdsa, in turn, which also failed — this time because they simply did not exist. Having no more keys to use for pubkey authentication and no available authentication mechanisms, the SSH client failed. Those "No such identity ..." messages were actually warnings.


text:
Q: Divide data by the preceding row and create new dataframe I have a data set and I'm trying to calculate the rate of change between the rows.
My input looks like this:
foo = structure(list(date = structure(c(5L, 1L, 2L, 3L, 4L), .Label = c("10/03/2020",
"11/03/2020", "12/03/2020", "13/03/2020", "9/03/2020"), class = "factor"),
    A = c(0.60256322, 0.634543306, 0.022976661, 0.009839044,
    0.319456765), B = c(45.42320826, 57.32689951, 32.49487759,
    29.40804164, 54.33691346), C = c(5.114123914, 3.674167652,
    2.330610757, 5.510280192, 5.717950467), D = c(4.187409484,
    4.835943165, 4.340614439, 4.607468576, 3.14338155)), row.names = c(NA,
5L), class = "data.frame")

I'm trying to divide each of the following cells with the one before
eg.  [5,2] / [4,2]; [4,2] / [3,2]... etc
and I'm trying to create a new output like this:
bar = structure(list(date = structure(c(5L, 1L, 2L, 3L, 4L), .Label = c("10/03/2020",
"11/03/2020", "12/03/2020", "13/03/2020", "9/03/2020"), class = "factor"),
    A = c(0, 1.053073412, 0.03620976, 0.428219052, 32.46827283
    ), B = c(0, 1.262061878, 0.56683473, 0.90500546, 1.847688946
    ), C = c(0, 0.718435398, 0.634323465, 2.364307371, 1.037687789
    ), D = c(0, 1.154877063, 0.897573501, 1.061478424, 0.682236134
    )), row.names = c(NA, 5L), class = "data.frame")

I'm sure there's a better way than finding the length of the column and looping through.  Can anyone point me in the right direction?

A: You cans use mutate_if or mutate_at from dplyr package.
library(dplyr)

foo %>%
    mutate_if(!grepl("date", names(.)), function(x) x/lag(x))

OR
foo %>%
    mutate_at(vars(-date), function(x) x/lag(x))

A: In base R,  we can use head and tail to divide data.
foo[-1] <- lapply(foo[-1], function(x) c(0, tail(x, -1)/head(x, -1)))
foo

#        date           A         B         C         D
#1  9/03/2020  0.00000000 0.0000000 0.0000000 0.0000000
#2 10/03/2020  1.05307341 1.2620619 0.7184354 1.1548771
#3 11/03/2020  0.03620976 0.5668347 0.6343235 0.8975735
#4 12/03/2020  0.42821905 0.9050055 2.3643074 1.0614784
#5 13/03/2020 32.46827283 1.8476889 1.0376878 0.6822361

A: Another tidyverse approach.
library(tidyverse)

bar <- foo %>%
  mutate_if(is.double, ~ replace_na(./lag(.), replace = 0))

bar

#>         date           A         B         C         D
#> 1  9/03/2020  0.00000000 0.0000000 0.0000000 0.0000000
#> 2 10/03/2020  1.05307341 1.2620619 0.7184354 1.1548771
#> 3 11/03/2020  0.03620976 0.5668347 0.6343235 0.8975735
#> 4 12/03/2020  0.42821905 0.9050055 2.3643074 1.0614784
#> 5 13/03/2020 32.46827283 1.8476889 1.0376878 0.6822361


text:
Q: Integer solutions to $a^{2014} +2015\cdot b! = 2014^{2015}$
How many  solutions are there for $a^{2014} +2015\cdot b! = 2014^{2015}$, with $a,b$ positive integers?

This is another contest problem that I got from my friend.
Can anybody  help me  find the answer? Or  give me a hint to solve this problem?
Thanks

A: Taking this equation mod $2015$ yields $a^{2014} \equiv -1 \pmod{2015}$.
Since $2015 = 5 \cdot 13 \cdot 31$, we get the following:
$a^{2014} \equiv -1 \pmod{5}$
$a^{2014} \equiv -1 \pmod{13}$
$a^{2014} \equiv -1 \pmod{31}$
By Fermat's Little Theorem, $a^{31} \equiv a \pmod{31}$. Hence, $a^4 \equiv a^{2014} \equiv -1 \pmod{31}$.
We can check that $-1$ is not a quadratic residue $\pmod{31}$. Thus, there is no residue $a^2$ such that $(a^2)^2 = a^4 \equiv -1 \pmod{31}$. Therefore, there are no solutions to the original equation.

A: Here's a line of attack that leaves you the task of checking only finitely many cases.
The idea is to check divisibility by powers of two. I use the notation $\nu(m)$ to denote
the exponent of the highest power of two that divides a positive integer $m$, so e.g. $\nu(80)=\nu(16\cdot5)=4$, because $2^4=16$.
You have probably seen (or can prove it as an exercise) that
$$
\nu(m!)=\sum_{i=1}^{\lceil \log_2m\rceil} \lfloor\frac m {2^i}\rfloor.\qquad(*)
$$
Also $\nu(mn)=\nu(m)+\nu(n)$, and consequently $\nu(m^n)=n\nu(m)$. Furthermore, if $\nu(a)\neq\nu(b)$ then $\nu(a+b)=\min\{\nu(a),\nu(b)\}$. This latter property is known as non-Archimedean triangle inequality. Let's call it NATI for short.
Here we see that $\nu(2014^{2015})=2015\cdot\nu(2014)=2015$ because $2014$ is even, but not divisibile by four.
Let us first consider the possibility that $a$ is odd. Then so is $a^{2014}$, so $2015\cdot b!$ must be odd. This is possible only, if $b!$ is odd, so we must have $b=0$
or $b=1$ for otherwise $b!$ is even. Check, whether there is matching $a$.
Let us then turn our attention to the possibility that $a$ is even. We first assume that $a$ is not divisible by four or, equivalently, that $\nu(a)=1$. In that case $\nu(a^{2014})=2014$. Because $\nu(2014^{2015})=2015$, NATI restricts the choice of $b$ to those numbers that have $2014=\nu(2015\cdot b!)=\nu(b!)$. Formula $(*)$ comes in handy. I give you the extra bit $\nu(2022!)=2014$. There are very few other possibilities for $b$, because $\nu(b!)$ is a (non-strictly) increasing function of $b$.
Finally, if $\nu(a)>1$, then $\nu(a^{2014})\ge2\cdot2014$, which is greater than $2015$. In this cases NATI forces $\nu(b!)=2015$. This again severely limits the possibilities for $b$.

A: Not the whole solution, but enough to get going.
We have that $\displaystyle a^{2014}+b!\equiv 0 \pmod{2014}$

*

*If $b\geq 53$, then $\displaystyle a^{2014}\equiv 0 \pmod{2014}$.

Since $2014=2\times19\times53$, this implies $\displaystyle a\equiv 0 \pmod{2014}$
Hence $a=2014k$ for some positive $k$
Plugging this in yields $\displaystyle 2014^{2014}k^{2014}+2015  b!=2014^{2015}$
Hence $2014^{2014}(2014-k^{2014})=2015  b!$
The RHS being positive, so is the LHS, and thefore $2014\geq k^{2014}$, which forces $k=1$
Therefore $a=2014$. Furthermore, $2014^{2014}(2013)=2015  b!$ is clearly a contradiction.

*

*Thus, $b\leq 52$

A: Hint $ $  If $\,n\,$ is odd,  and $\ a^{n-1}\! + n b = (n-1)^{2j+1} $  then every prime $\,p\,$ dividing $\,n\,$ is $\,\equiv 1\pmod 4 $
since $\ n\!-\!1 = 2k,\,$ so $\, {\rm mod}\ p\!:\ (a^k)^2 \equiv\, -1,\ $ so by Euler or reciprocity, $ $ we infer $\ p\equiv 1\pmod 4$


text:
Q: Signature Pad Xamarin.Forms Saving signature as a file I am a beginner in Xamarin.
I tried to write a simple app to save the signature with the help of Signature Pad.
A piece of code from MainPage.xaml
<controls:SignaturePadView x:Name="SignaturePAD"
                           Grid.Row="1"
                           StrokeColor="Black"
                           StrokeWidth="3"
                           BackgroundColor="Gray"
                           CaptionTextColor="Black"
                           PromptTextColor="Black"
                           SignatureLineColor="Black"
                           CaptionText="Podpis odbiorcy">
</controls:SignaturePadView>

<Button Grid.Row="2"
        x:Name="SaveButton"
        Text="Potwierdź"
        Clicked="SaveSignature"/>

and a fragment from MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    public async void SaveSignature(object sender, EventArgs e)
    {
        Stream image = await SignaturePAD.GetImageStreamAsync(SignatureImageFormat.Png);

    }

}

And my question is how can I save it into the my phone gallery?
I will be grateful for any help

A: the SignaturePad returns a stream - so you can write it to a file using normal C# I/O, like FileStream
Stream image = await SignaturePAD.GetImageStreamAsync(SignatureImageFormat.Png);

using (FileStream file = new FileStream(file_path, FileMode.Create, System.IO.FileAccess.Write))
{
  image.CopyTo(file);
}

A: You might be able to find a plugin somewhere that would do this for you, but I would convert the stream to a byte[] like so:
using (image)
using (var memoryStream = new MemoryStream())
{
    await image.CopyToAsync(memoryStream);
    var picture = memoryStream.ToArray();
}

Then convert the byte[] to the native picture on each platform.
For Android use:
BitmapFactory.DecodeByteArray(picture, 0, picture.Length);

And for iOS use:
var nsData = NSData.FromArray(picture);
var uiImage = UIImage.LoadFromData(nsData);

Then you would need to add the image to the underlying gallery. Here is an example of how to achieve something like that on iOS: https://developer.xamarin.com/recipes/ios/media/video_and_photos/save_photo_to_album_with_metadata/
For Android, this post might help: Xamarin.Forms Android save image to gallery


text:
Q: SH72867 with I2C I am using 'SH72867(Renesas)' connect with 'EEPROM(24LC04B)' . In the customer's document at 'address 0xF0 of EEPROM  have data 0x5555', But when I reading from this address always return '0xFFFF' and same with other address.
I can't  write to EEPROM too.
I used I2C sample of Renesas but not run.
Do you have any suggestion about setting up I2C?
Sorry for my bad English and no clear explanation.
Any help apprciated,
Thanks

A: Verify the common issues:

*

*Data and clock are connected properly.

*Pull up resistor on clock and data connected to VCC.

*Loop the I2C read request, connect scope and verify that I2C signals are OK. In addition check the ACK bit.

*Verify clock is lower then 400kHz.

*When using code examples, they usually fit to specific board. Verify that the code example configuration is the same as your board.

*Some MCU may have more then one I2C pinout options. The code example might use I2C module that connected to diffrent pins.


text:
Q: Rename files on Ubuntu Terminal I would like to rename my file C6Y5DACXX-2-ID01_1_sequence.fastq to C6Y5DACXX-2-ID01_sequence_1.fastq
I am running a program that requires the input of the fastq files to be _1.fastq and _2.fastq
Kindly assist.

A: You use command mv filename new_filename
Here is my terminal for your filenames:
marko@DevLaptop:~/test$ touch C6Y5DACXX-2-ID01_1_sequence.fastq
marko@DevLaptop:~/test$ ls
C6Y5DACXX-2-ID01_1_sequence.fastq
marko@DevLaptop:~/test$ mv C6Y5DACXX-2-ID01_1_sequence.fastq C6Y5DACXX-2-ID01_sequence_1.fastq
marko@DevLaptop:~/test$ ls
C6Y5DACXX-2-ID01_sequence_1.fastq

And to replace all 1_sequence to sequence_1 you can use
rename 's/1_sequence/sequence_1/' *.fastq

A: you can rename like this
mv "name.txt" "new_name.txt"

you can change the file format like this
mv "name.txt" "new_name.php"

A: You can simply rename the file using mv command.Though mv command is used to move the contents of a folder to other destination,but when the arguments are files then it starts to behave differently i.e it renames.
mv stack.css stackOverflow.css

The name stack.css will be changed to stackOverflow.css


text:
Q: Numerical evaluation of KL divergence for SDE Consider the SDE
$$
dX_t = v(X_t)dt + dW_t
$$
where $W_t$ is a standard Brownian motion. Girsanov's theorem tells us that the Radon-Nikodym derivative of the measure $\mathbb{P}_v$ of $X_t$ with respect to the measure $\mathbb{P}_0$ of $W_t$ is
$$
  \frac{d\mathbb{P}_v}{d\mathbb{P}_0}=\exp\left(\int v(X_t)dX_t - \frac{1}{2}\int |v(X_t)|^2 dt\right).
$$
This allows the computation of the Kullback–Leibler divergence from
$$
D_{\text{KL}}\left(\mathbb{P}_v \middle\| \mathbb{P}_v\right) = \operatorname{E}_{\mathbb{P}_v} \left[\log\left(\frac{d\mathbb{P}_v}{d\mathbb{P}_v}\right)\right].
$$
I think a default approach to a numerical evaluation of the KL would be via a Monte Carlo estimate from a numerical integration of the SDE. I'd like to know:

Are there numerical schemes that specifically target the calculation of RN derivative or KL divergence?


text:
Q: Java native SQL query to display all values when an input param is null I have the following DAO method:
public String getSomeTable(final String param1) {
    String sqlString = "select * from table where name ilike ?";
    Query query = this.getEntityManager().createNativeQuery(sqlString);

    query.setParameter(1, "%param1%");
}

If param1 is null or empty then I want to select all entries from the table. What is the correct way to do this? I am currently using the following:
public String getSomeTable(final String param1) {
    String sqlString = "select * from table where name = ?";
    Query query = this.getEntityManager().createNativeQuery(sqlString);

    if(param1 == null)
        query.setParameter(1, "%%");
    else
        query.setParameter(1, "%param1%");
}

But this is not scalable. I have datatypes like integer, date, etc. I want to know if there is a way to skip checking for that parameter if it is null.
I was planning to use COALESCE(?, CASE WHEN ? = '' THEN '%%' ELSE '%?%') but I think ? can be used only once for a particular parameter. The next one > I write is linked to second param.

A: On SQL Server, I use something like this, perhaps you can translate it to postgres:
DECLARE @variable INT = NULL;

SELECT *
FROM sysobjects
WHERE
(1 = CASE WHEN @variable IS NULL THEN 1 ELSE 2 END)
OR
(id LIKE @variable);


text:
Q: How we can open apple watch settings when clicked a button? I made an independent watch app, for getting data from healthkit, and users can edit permission to allow them to collect some health data.
Do we have any method to open apple watch settings when clicking a button?


text:
Q: Macdonald's "Symmetric Functions and Hall Polynomials" Section 1.5 Example 9 I'm trying to follow Example 9 in Section 1.5 of Macdonald's book "Symmetric Functions and Hall Polynomials". I have trouble with understanding some points.
Before stating my question, I will first explain the example briefly. If $R$ is a root system, then the Weyl denominator formula for $R$ is
$$\sum_{w\in W}\varepsilon(w)e^{w\rho}=\prod_{\alpha\in R^{+}}(e^{\alpha/2}-e^{-\alpha/2}),$$
where $W$ is the Weyl group of $R$, $R^{+}$ is the set of positive roots (relative to some base), $\rho$ is the half-sum of the positive roots and $\varepsilon(w)$ is the sign of $w\in W$. The goal of the example is to express the products
$$\prod_{i<j} (1-x_{i}x_{j}),\quad\prod_{i}(1-x_{i})\prod_{i<j}(1-x_{i}x_{j}),\quad\prod_{i}(1-x_{i}^{2})\prod_{i<j}(1-x_{i}x_{j})$$
as linear combinations of Schur functions using the Weyl denominator formula for root systems of types $D_{n}, B_{n}, C_{n}$, respectively. More precisely,
\begin{align*}
\prod_{i<j}(1-x_{i}x_{j})&=\sum_{\pi}(-1)^{|\pi|/2}s_{\pi}(x_{1},\ldots,x_{n})\\
\prod_{i}(1-x_{i}^{2})\prod_{i<j}(1-x_{i}x_{j})&=\sum_{\mu}(-1)^{|\mu|/2}s_{\mu}(x_{1},\ldots,x_{n})\\
\prod_{i}(1-x_{i})\prod_{i<j}(1-x_{i}x_{j})&=\sum_{\nu}(-1)^{(|\nu|+p(\nu))/2}s_{\nu}(x_{1},\ldots,x_{n}),
\end{align*}
where the first sum ranges over all partitions $\pi=(\alpha_{1}-1,\ldots,\alpha_{p}-1\mid\alpha_{1},\ldots,\alpha_{p})$ with $\alpha_{1}\leq n-1$, the second sum ranges over all partitions $\mu=(\alpha_{1}+1,\ldots,\alpha_{p}+1\mid\alpha_{1},\ldots,\alpha_{p})$ with $\alpha_{1}\leq n-1$, the third sum ranges over all self-conjugate partitions $\nu=(\alpha_{1},\ldots,\alpha_{p}\mid\alpha_{1},\ldots,\alpha_{p})$ with $\alpha_{1}\leq n-1$ and $p(\nu)=p$.
Now I'm ready to state my question. Here I will just consider the first product. Let $\epsilon_{1},\ldots,\epsilon_{n}$ be the standard basis for $\mathbb{R}^{n}$. The root system $R=D_{n}$ is given by
$$\{\pm(\epsilon_{i}\pm\epsilon_{j}):i\neq j\},$$
and the subset
$$\Delta=\{\epsilon_{1}-\epsilon_{2},\epsilon_{2}-\epsilon_{3},\ldots,\epsilon_{n-1}-\epsilon_{n},\epsilon_{n-1}+\epsilon_{n}\}$$
is a base. Then
\begin{align*}
R^{+}&=\{\epsilon_{i}\pm\epsilon_{j}:1\leq i<j\leq n\},\\
\rho&=(n-1)\epsilon_{1}+(n-2)\epsilon_{2}+\cdots+\epsilon_{n-1}.
\end{align*}
On the other hand, the reflection $\sigma_{\epsilon_{i}-\epsilon_{i+1}}$ in the orthogonal complement of $\epsilon_{i}-\epsilon_{i+1}$ switches $\epsilon_{i}$ with $\epsilon_{i+1}$, and $\sigma_{\epsilon_{i}+\epsilon_{i+1}}$ switches $\epsilon_{i}$ to $-\epsilon_{j}$ and $\epsilon_{j}$ to $-\epsilon_{i}$. Thus the Weyl group $W$ can be identified with the group of all elements that permute $n$ elements as well as switching an even number of their signs, hence isomorphic to $S_{n}\ltimes\mathbb{Z}_{2}^{n-1}$. If we replace $e^{-\epsilon_{i}}$ by $x_{i}$, the right-hand side of the denominator formula becomes:
\begin{align*}
\prod_{\alpha\in R^{+}}(e^{\alpha/2}-e^{-\alpha/2})&=e^{\rho}\prod_{\alpha\in R^{+}}(1-e^{-\alpha})\\
&=x_{1}^{-(n-1)}x_{2}^{-(n-2)}\cdots x_{n-1}^{-1}\prod_{i<j}(1-x_{i}x_{j})\left(1-\frac{x_{i}}{x_{j}}\right)\\
&=(x_{1}\cdots x_{n})^{-(n-1)}\prod_{i<j}(1-x_{i}x_{j})\left(x_{j}-x_{i}\right).
\end{align*}
The product $\prod_{i<j}(1-x_{i}x_{j})$ is the product we are interested in and the product $\prod_{i<j}(x_{j}-x_{i})$ is involved in the definition of Schur function. So it remains to relate the left-hand side of the denominator formula to the partitions $\pi=(\alpha_{1}-1,\ldots,\alpha_{p}-1\mid\alpha_{1},\ldots,\alpha_{p})$ with $\alpha_{1}\leq n-1$. But I have no idea. If someone has any idea, please let me know. Thank you for reading.


text:
Q: how to set width div from begin to end of a browser width in html I want to create a menu in html with a black background color so I set width of a div with 1360 px but it does not cover all over the page. Please help me to solve this. Thanks.

CSS:
*{
    border:0;
    margin:0;
    padding:0;
}
body {
    background-color:#ffffff;

    margin:0;

    direction:rtl;
}
#menu{
    background-color:#3d3d3d;
    height:70px;
    width:100%;
}
#text_menu{
    height:50px;
    width:100%;
    float:right;
    margin-right:5px;
}
#text_menu ul{
    list-style:none;
    margin-top:10px;
}
 #text_menu ul li{
    display:inline-block;
    text-decoration:none;
}
 #text_menu ul li a{
     text-decoration:none;
     padding:5px;
     color:#fff;
     transition:all ease-out .4s;
     -moz-transition:all ease-out .4s;
      -webkit-transition:all ease-out .4s;
       -o-transition:all ease-out .4s;

 }
 #text_menu ul li:hover a{
     height:50px;
     width:100%;
     color:#b6ff00;
 }
 #header{
     align-content:center;
     height:464px;
     width:80%;
     background-image:url(../images/1.jpg);
     background-repeat:no-repeat;
 }

Html :

content

content

content

content

content

A: Set the body margin to 0
Then set the width of your menu to 100%

A: Just do this with your menu
HTML:

CSS:
.menu {
    margin: 0;
    width: 100%;
}

If you are putting this menu inside another div, then make sure that it also has a width of 100%, else this will not work.


text:
Q: How to make this python currency quote application using API work? I made two different projects. One using tkinter to make GUI and the other one I was learning to use customtkinter. In this project I'm trying to combine the dollar, euro and bitcoin quote code with what I learned doing GUI using customtkinter. I don't exactly know how to get this to run right now. I've read the customtkinter documentation but I couldn't find the answer. If you can help me I will be grateful haha
import customtkinter
import requests

customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

root = customtkinter.CTk()
root.geometry("500x350")
root.title("Cotacao Krettina")

def pegar_cotacoes():
requisicao = requests.get('https://economia.awesomeapi.com.br/json/last/USD-BRL,EUR-BRL,BTC-BRL')

    requisicao_dic = requisicao.json()

    cotacao_dolar = requisicao_dic ['USDBRL']['bid']
    cotacao_euro = requisicao_dic ['EURBRL']['bid']
    cotacao_bitcoin = requisicao_dic ['BTCBRL']['bid']

    texto = f'''
    Dolar: {cotacao_dolar}
    Euro: {cotacao_euro}
    Bitcoin: {cotacao_bitcoin}'''

    texto_cotacoes["text"] = texto

frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)

button = customtkinter.CTkButton(master=frame, text="Cotar!", command=pegar_cotacoes)
button.pack(pady=12, padx=10)

texto_cotacoes = customtkinter.CTkLabel(master=root, width=120, height=25, corner_radius=8)
texto_cotacoes.pack(pady=12, padx=10)

root.mainloop()\


text:
Q: what is the use of manual bootstrapping in Angularjs I read in an article that the Angular JS application can be Manually Bootstrapped.What is the meaning of Manually Bootstrapping the Angular application and how is it done?

A: If you need to have more control over the initialization process, you can use a manual bootstrapping method instead.
Please go through the below code.
  <!doctype html>
<html>
<body>
  <div ng-controller="MyController">
    Hello {{greetMe}}!
  </div>
  <script src="http://code.angularjs.org/snapshot/angular.js"></script>

  <script>
    angular.module('myApp', [])
      .controller('MyController', ['$scope', function ($scope) {
        $scope.greetMe = 'World';
      }]);

    angular.element(function() {
      angular.bootstrap(document, ['myApp']);
    });
  </script>
</body>
</html>


text:
Q: OnNavigatedTo is not invoked when navigating to a view in module I'm new to Prism and trying to make a simple modular app with it (see the full code).
I'm actually trying to pass a parameter to a view, so in the ModuleAViewViewModel of the ModuleAView I'm implementing INavigationAware, this way:
public class ModuleAViewViewModel : BindableBase, INavigationAware
{
    private int passedId;

    public int PassedId
    {
        get => passedId;
        set => SetProperty(ref passedId, value);
    }

    // In the following 3 methods, a breakpoint never gets hit.

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
    }

    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        PassedId = (int)navigationContext.Parameters["Id"];
    }
}

This is the corresponding ModuleAView.
<UserControl x:Class="ModularSample1.Modules.ModuleA.Views.ModuleAView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ModularSample1.Modules.ModuleA.Views"
             xmlns:viewmodels="clr-namespace:ModularSample1.Modules.ModuleA.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <viewmodels:ModuleAViewViewModel x:Key="moduleAViewModel"/>
    </UserControl.Resources>
    <Grid DataContext="{StaticResource moduleAViewModel}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock
            Grid.Row="1"
            Text="{Binding PassedId, StringFormat='Passed Id: {0}'}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            FontSize="34"/>
    </Grid>
</UserControl>

And the ViewModel that actually navigates to that view looks like this:
public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager regionManager;

    public MainWindowViewModel(IRegionManager regionManager, IModuleManager moduleManager)
    {
        this.regionManager = regionManager;

        moduleManager.Run();
        Modules = moduleManager.Modules.ToList();
    }

    private List<IModuleInfo> modules;
    private IModuleInfo selectedModule;

    public List<IModuleInfo> Modules
    {
        get => modules;
        set => SetProperty(ref modules, value);
    }

    public IModuleInfo SelectedModule
    {
        get => selectedModule;
        set
        {
            if (SetProperty(ref selectedModule, value))
            {
                var Id = new Random().Next(1, 12);
                var navigationParameters = new NavigationParameters
                {
                    { "Id", Id }
                };

                regionManager.RequestNavigate(
                    "SelectedModuleRegion",
                    $"{selectedModule.ModuleName}View",
                    navigationParameters);
            }
        }
    }
}

What I'm missing here?

A: You define the view model for your ModuleAView in its Resources and set it on a child Grid via reference. Prism looks for the DataContext on the view itself to call a view model that implements INavigationAware, not a child control, so it does not find your view model. From the documentation:

During navigation, Prism checks to see whether the view implements the INavigationAware interface; if it does, it calls the required methods during navigation. Prism also checks to see whether the object set as the view's DataContext implements this interface; if it does, it calls the required methods during navigation.

In order to make it work, set the data context directly on the ModuleAView and remove it from Grid.
<UserControl x:Class="ModularSample1.Modules.ModuleA.Views.ModuleAView"
             ...>
    <UserControl.DataContext>
        <viewmodels:ModuleAViewViewModel/>
    </UserControl.DataContext>
    <Grid>
        <!-- ...grid definitions. -->
    </Grid>
</UserControl>

A better alternative is to remove setting the data context manually completely from your ModuleAView and register your ModuleAView directly with ModuleAViewViewModel. Prism's navigation service will automatically resolve the view model during navigation and assign it as data context.
containerRegistry.RegisterForNavigation<ModuleAView, ModuleAViewViewModel>();

You can even simplify this, by following the naming conventions for views and view models regarding the ViewModelLocator, which will be used in navigation to resolve view models for views.

*

*ViewModels are in the same assembly as the view types

*ViewModels are in a .ViewModels child namespace

*Views are in a .Views child namespace

*ViewModel names correspond with view names and end with "ViewModel.
You violate the last rule, so renaming ModuleAViewViewModel to ModuleAViewModel and just removing the manual setting of the data context will enable Prism to automatically find the corresponding view model for the view that you registered with RegisterForNavigation.
containerRegistry.RegisterForNavigation<ModuleAView>();


text:
Q: creating more than one variable with for loop on python I want to create multiple variables with what I get from the list.
cm_aaa = TRYModule()
app_label='aaa'
schema_aaa=cm_aaa.get_schema(app_label, db_type)
cm_aaa.connect(app_label, db_type)
cur_aaa=cm_aaa.conn.cursor()

cm_bbb=TRYModule()
app_label='bbb'
schema_bbb=cm_bbb.get_schema(app_label, db_type)
cm_bbb.connect(app_label, db_type)
cur_bbb=cm_bbb.conn.cursor()

I want to make the database connection repetitions I made above with the for loop from the list below.
system_name=['aaa','bbb','ccc','ddd','eee']

A: It seems like you could benefit from creating a class. Consider having a read of some basics of object oriented programming in python.
In your case, something like this could be used:
class MyClass:
    def __init__(self, app_label, db_type):
        self.cm = TRYModule()
        self.app_label = app_label
        self.db_type = db_type
        self.schema = self.cm.get_schema(self.app_label, self.db_type)
        self.cm.connect(self.app_label, self.db_type)
        self.cur = self.cm.conn.cursor()

system_name = ['aaa','bbb','ccc','ddd','eee']

my_systems = [MyClass(label, db_type) for label in system_name]

Then, if you need to access any of the systems on the list my_systems you reference it via its index, for instance, if you want to access cursor of the first system you can do my_systems[0].cur.
Alternatively, you could create separate variables for each of the systems, such as:
aaa = MyClass('aaa', db_type)
bbb = MyClass('bbb', db_type)
ccc = MyClass('ccc', db_type)

In this case, to access an attribute of one of the objects, you can do aaa.cur, for instance.


text:
Q: Standard way to embed version into Python package? Is there a standard way to associate version string with a Python package in such way that I could do the following?
import foo
print(foo.version)

I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py.

A: Also worth noting is that as well as __version__ being a semi-std. in python so is __version_info__ which is a tuple, in the simple cases you can just do something like:
__version__ = '1.2.3'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])

...and you can get the __version__ string from a file, or whatever.

A: There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner

*

*Embed the version in setup.py and have setup.py generate a module (e.g. version.py) containing only version info,  that's imported by your package, or

*The reverse: put the version info in your package itself, and import that to set the version in  setup.py

A: arrow handles it in an interesting way.
Now (since 2e5031b)
In arrow/__init__.py:
__version__ = 'x.y.z'

In setup.py:
from arrow import __version__

setup(
    name='arrow',
    version=__version__,
    # [...]
)

Before
In arrow/__init__.py:
__version__ = 'x.y.z'
VERSION = __version__

In setup.py:
def grep(attrname):
    pattern = r"{0}\W*=\W*'([^']+)'".format(attrname)
    strval, = re.findall(pattern, file_text)
    return strval

file_text = read(fpath('arrow/__init__.py'))

setup(
    name='arrow',
    version=grep('__version__'),
    # [...]
)

A: I also saw another style:
>>> django.VERSION
(1, 1, 0, 'final', 0)

A: Using setuptools and pbr
There is not a standard way to manage version, but the standard way to manage your packages is setuptools.
The best solution I've found overall for managing version is to use setuptools with the pbr extension.  This is now my standard way of managing version.
Setting up your project for full packaging may be overkill for simple projects, but if you need to manage version, you are probably at the right level to just set everything up. Doing so also makes your package releasable at PyPi so everyone can download and use it with Pip.
PBR moves most metadata out of the setup.py tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).
When using Git for VCS/SCM, this setup is even better, as it will pull in a lot of the metadata from Git so that your repo can be your primary source of truth for some of the metadata, including version, authors, changelogs, etc. For version specifically, it will create a version string for the current commit based on git tags in the repo.

*

*PyPA - Packaging Python Packages with SetupTools - Tutorial

*PBR latest build usage documentation - How to setup an 8-line setup.py and a setup.cfg file with the metadata.

As PBR will pull version, author, changelog and other info directly from your git repo, so some of the metadata in setup.cfg can be left out and auto generated whenever a distribution is created for your package (using setup.py)

Get the current version in real-time
setuptools will pull the latest info in real-time using setup.py:
python setup.py --version

This will pull the latest version either from the setup.cfg file, or from the git repo, based on the latest commit that was made and tags that exist in the repo. This command doesn't update the version in a distribution though.

Updating the version metadata
When you create a distribution with setup.py (i.e. py setup.py sdist, for example), then all the current info will be extracted and stored in the distribution. This essentially runs the setup.py --version command and then stores that version info into the package.egg-info folder in a set of files that store distribution metadata.

Note on process to update version meta-data:
If you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process).
If you are using git, and you don't need to create a source or binary distribution (using python setup.py sdist or one of the python setup.py bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python setup.py install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command.
Note that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard "release process" to get the metadata updated locally before release, and any package you upload to PyPi.org or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)

Accessing the version from a script
You can access the metadata from the current build within Python scripts in the package itself. For version, for example, there are several ways to do this I have found so far:
## This one is a new built-in as of Python 3.8.0 should become the standard
from importlib.metadata import version

v0 = version("mypackage")
print('v0 {}'.format(v0))

## I don't like this one because the version method is hidden
import pkg_resources  # part of setuptools

v1 = pkg_resources.require("mypackage")[0].version
print('v1 {}'.format(v1))

# Probably best for pre v3.8.0 - the output without .version is just a longer string with
# both the package name, a space, and the version string
import pkg_resources  # part of setuptools

v2 = pkg_resources.get_distribution('mypackage').version
print('v2 {}'.format(v2))

## This one seems to be slower, and with pyinstaller makes the exe a lot bigger
from pbr.version import VersionInfo

v3 = VersionInfo('mypackage').release_string()
print('v3 {}'.format(v3))

You can put one of these directly in your __init__.py for the package to extract the version info as follows, similar to some other answers:
__all__ = (
    '__version__',
    'my_package_name'
)

import pkg_resources  # part of setuptools

__version__ = pkg_resources.get_distribution("mypackage").version

A: After several hours of trying to find the simplest reliable solution, here are the parts:
create a version.py file INSIDE the folder of your package "/mypackage":
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '1.2.7'

in setup.py:
exec(open('mypackage/version.py').read())
setup(
    name='mypackage',
    version=__version__,

in the main folder init.py:
from .version import __version__

The exec() function runs the script outside of any imports, since setup.py is run before the module can be imported. You still only need to manage the version number in one file in one place, but unfortunately it is not in setup.py. (that's the downside, but having no import bugs is the upside)

A: pbr with bump2version
This solution was derived from this article
The use case - python GUI package distributed via PyInstaller. Needs to show version info.
Here is the structure of the project packagex
packagex
├── packagex
│   ├── __init__.py
│   ├── main.py
│   └── _version.py
├── packagex.spec
├── LICENSE
├── README.md
├── .bumpversion.cfg
├── requirements.txt
├── setup.cfg
└── setup.py

where setup.py is
# setup.py
import os

import setuptools

about = {}
with open("packagex/_version.py") as f:
    exec(f.read(), about)

os.environ["PBR_VERSION"] = about["__version__"]

setuptools.setup(
    setup_requires=["pbr"],
    pbr=True,
    version=about["__version__"],
)

packagex/_version.py contains just
__version__ = "0.0.1"

and packagex/__init__.py
from ._version import __version__

and for .bumpversion.cfg
[bumpversion]
current_version = 0.0.1
commit = False
tag = False
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\-(?P<release>[a-z]+)(?P<build>\d+))?
serialize =
    {major}.{minor}.{patch}-{release}{build}
    {major}.{minor}.{patch}

[bumpversion:part:release]
optional_value = prod
first_value = dev
values =
    dev
    prod

[bumpversion:file:packagex/_version.py]

A: Per the deferred [STOP PRESS: rejected] PEP 396 (Module Version Numbers), there is a proposed way to do this. It describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet:

*When a module (or package) includes a version number, the version SHOULD be available in the __version__ attribute.

*For modules which live inside a namespace package, the module SHOULD include the __version__ attribute. The namespace package itself SHOULD NOT include its own __version__ attribute.

*The __version__ attribute's value SHOULD be a string.

A: There is a slightly simpler alternative to some of the other answers:
__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)

(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using str().)
Of course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int() and str() can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)
This is, of course, my own view, and I would gladly like others' input on using a numerical tuple.

As shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing __version_info__ (or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.

A: I prefer to read the package version from installation environment.
This is my src/foo/_version.py:
from pkg_resources import get_distribution

__version__ = get_distribution('foo').version

Makesure foo is always already installed, that's why a src/ layer is required to prevent foo imported without installation.
In the setup.py, I use setuptools-scm to generate the version automatically.

Update in 2022.7.5:
There is another way, which is my faviourate now. Use setuptools-scm to generate a _version.py file.
setup(
    ...
    use_scm_version={
        'write_to':
        'src/foo/_version.py',
        'write_to_template':
        '"""Generated version file."""\n'
        '__version__ = "{version}"\n',
    },
)

A: Not directly an answer to your question, but you should consider naming it __version__, not version.
This is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.
Usually, __version__ is a string, but sometimes it's also a float or tuple.
As mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:

Module Level Dunder Names
Module level "dunders" (i.e. names with two leading and two trailing
underscores) such as __all__, __author__, __version__, etc.
should be placed after the module docstring but before any import
statements except from __future__ imports.

You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).

A: I use a single _version.py file as the "once cannonical place" to store version information:

*

*It provides a __version__ attribute.

*It provides the standard metadata version. Therefore it will be detected by pkg_resources or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).

*It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.)

*There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions.
Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in myniftyapp/_version.py. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like:
__version__ = "3.6.5"

And so your setup.py opens the file and parses it, with code like:
import re
VERSIONFILE="myniftyapp/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
    verstr = mo.group(1)
else:
    raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))

Then your setup.py passes that string as the value of the "version" argument to setup(), thus satisfying feature 2.
To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from myniftyapp/__init__.py like this:
from _version import __version__

Here is an example of this technique that I've been using for years.
The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation.
Here is example code of importing the version.
If you see anything wrong with this approach, please let me know.

A: Many of these solutions here ignore git version tags which still means you have to track version in multiple places (bad). I approached this with the following goals:

*

*Derive all python version references from a tag in the git repo

*Automate git tag/push and setup.py upload steps with a single command that takes no inputs.

How it works:

*

*From a make release command, the last tagged version in the git repo is found and incremented. The tag is pushed back to origin.

*The Makefile stores the version in src/_version.py where it will be read by setup.py and also included in the release. Do not check _version.py into source control!

*setup.py command reads the new version string from package.__version__.
Details:
Makefile
# remove optional 'v' and trailing hash "v1.0-N-HASH" -> "v1.0-N"
git_describe_ver = $(shell git describe --tags | sed -E -e 's/^v//' -e 's/(.*)-.*/\1/')
git_tag_ver      = $(shell git describe --abbrev=0)
next_patch_ver = $(shell python versionbump.py --patch $(call git_tag_ver))
next_minor_ver = $(shell python versionbump.py --minor $(call git_tag_ver))
next_major_ver = $(shell python versionbump.py --major $(call git_tag_ver))

.PHONY: ${MODULE}/_version.py
${MODULE}/_version.py:
    echo '__version__ = "$(call git_describe_ver)"' > $@

.PHONY: release
release: test lint mypy
    git tag -a $(call next_patch_ver)
    $(MAKE) ${MODULE}/_version.py
    python setup.py check sdist upload # (legacy "upload" method)
    # twine upload dist/*  (preferred method)
    git push origin master --tags

The release target always increments the 3rd version digit, but you can use the next_minor_ver or next_major_ver to increment the other digits. The commands rely on the versionbump.py script that is checked into the root of the repo
versionbump.py
"""An auto-increment tool for version strings."""

import sys
import unittest

import click
from click.testing import CliRunner  # type: ignore

__version__ = '0.1'

MIN_DIGITS = 2
MAX_DIGITS = 3

@click.command()
@click.argument('version')
@click.option('--major', 'bump_idx', flag_value=0, help='Increment major number.')
@click.option('--minor', 'bump_idx', flag_value=1, help='Increment minor number.')
@click.option('--patch', 'bump_idx', flag_value=2, default=True, help='Increment patch number.')
def cli(version: str, bump_idx: int) -> None:
    """Bumps a MAJOR.MINOR.PATCH version string at the specified index location or 'patch' digit. An
    optional 'v' prefix is allowed and will be included in the output if found."""
    prefix = version[0] if version[0].isalpha() else ''
    digits = version.lower().lstrip('v').split('.')

    if len(digits) > MAX_DIGITS:
        click.secho('ERROR: Too many digits', fg='red', err=True)
        sys.exit(1)

    digits = (digits + ['0'] * MAX_DIGITS)[:MAX_DIGITS]  # Extend total digits to max.
    digits[bump_idx] = str(int(digits[bump_idx]) + 1)  # Increment the desired digit.

    # Zero rightmost digits after bump position.
    for i in range(bump_idx + 1, MAX_DIGITS):
        digits[i] = '0'
    digits = digits[:max(MIN_DIGITS, bump_idx + 1)]  # Trim rightmost digits.
    click.echo(prefix + '.'.join(digits), nl=False)

if __name__ == '__main__':
    cli()  # pylint: disable=no-value-for-parameter

This does the heavy lifting how to process and increment the version number from git.
__init__.py
The my_module/_version.py file is imported into my_module/__init__.py. Put any static install config here that you want distributed with your module.
from ._version import __version__
__author__ = ''
__email__ = ''

setup.py
The last step is to read the version info from the my_module module.
from setuptools import setup, find_packages

pkg_vars  = {}

with open("{MODULE}/_version.py") as fp:
    exec(fp.read(), pkg_vars)

setup(
    version=pkg_vars['__version__'],
    ...
    ...
)

Of course, for all of this to work you'll have to have at least one version tag in your repo to start.
git tag -a v0.0.1

A: I use a JSON file in the package dir. This fits Zooko's requirements.
Inside pkg_dir/pkg_info.json:
{"version": "0.1.0"}

Inside setup.py:
from distutils.core import setup
import json

with open('pkg_dir/pkg_info.json') as fp:
    _info = json.load(fp)

setup(
    version=_info['version'],
    ...
    )

Inside pkg_dir/__init__.py:
import json
from os.path import dirname

with open(dirname(__file__) + '/pkg_info.json') as fp:
    _info = json.load(fp)

__version__ = _info['version']

I also put other information in pkg_info.json, like author. I
like to use JSON because I can automate management of metadata.

A: Rewritten 2017-05
After 13+ years of writing Python code and managing various packages, I came to the conclusion that DIY is maybe not the best approach.
I started using the pbr package for dealing with versioning in my packages. If you are using git as your SCM, this will fit into your workflow like magic, saving your weeks of work (you will be surprised about how complex the issue can be).
As of today, pbr has 12M mongthly downloads, and reaching this level didn't include any dirty tricks. It was only one thing -- fixing a common packaging problem in a very simple way.
pbr can do more of the package maintenance burden, and is not limited to versioning, but it does not force you to adopt all its benefits.
So to give you an idea about how it looks to adopt pbr in one commit have a look switching packaging to pbr
Probably you would observed that the version is not stored at all in the repository. PBR does detect it from Git branches and tags.
No need to worry about what happens when you do not have a git repository because pbr does "compile" and cache the version when you package or install the applications, so there is no runtime dependency on git.
Old solution
Here is the best solution I've seen so far and it also explains why:
Inside yourpackage/version.py:
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '0.12'

Inside yourpackage/__init__.py:
from .version import __version__

Inside setup.py:
exec(open('yourpackage/version.py').read())
setup(
    ...
    version=__version__,
    ...

If you know another approach that seems to be better let me know.

A: Lots of work toward uniform versioning and in support of conventions has been completed since this question was first asked. Palatable options are now detailed in the Python Packaging User Guide. Also noteworthy is that version number schemes are relatively strict in Python per PEP 440, and so keeping things sane is critical if your package will be released to the Cheese Shop.
Here's a shortened breakdown of versioning options:

*

*Read the file in setup.py (setuptools) and get the version.

*Use an external build tool (to update both __init__.py as well as source control), e.g. bump2version, changes or zest.releaser.

*Set the value to a __version__ global variable in a specific module.

*Place the value in a simple VERSION text file for both setup.py and code to read.

*Set the value via a setup.py release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.)

*Set the value to __version__ in sample/__init__.py and import sample in setup.py.

*Use setuptools_scm to extract versioning from source control so that it's the canonical reference, not code.

NOTE that (7) might be the most modern approach (build metadata is independent of code, published by automation). Also NOTE that if setup is used for package release that a simple python3 setup.py --version will report the version directly.

A: *

*Create a file named by _version.txt in the same folder as __init__.py and write version as a single line:

0.8.2

*Read this infomation from file _version.txt in __init__.py:

    import os
    def get_version():
        with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), "_version.txt")) as f:
            return f.read().strip()
    __version__ = get_version()

A: I described a standard and modern way here, relying on setuptools_scm.
This pattern has worked successfully for dozens of published packages over the past years, so I can warmly recommend it.
Note that you do not need the getversion package to implement this pattern. It just happens that the getversion documentation hosts this tip.

A: Using setuptools and pyproject.toml
Setuptools now offers a way to dynamically get version in pyproject.toml
Reproducing the example here, you can create something like the following in your pyproject.toml
# ...
[project]
name = "my_package"
dynamic = ["version"]
# ...
[tool.setuptools.dynamic]
version = {attr = "my_package.__version__"}

A: For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration has a make_svn_version_py() method that embeds the revision number inside package.__svn_version__ in the variable version .

A: If you use CVS (or RCS) and want a quick solution, you can use:
__version__ = "$Revision: 1.1 $"[11:-2]
__version_info__ = tuple([int(s) for s in __version__.split(".")])

(Of course, the revision number will be substituted for you by CVS.)
This gives you a print-friendly version and a version info that you can use to check that the module you are importing has at least the expected version:
import my_module
assert my_module.__version_info__ >= (1, 1)

A: *

*Use a version.py file only with __version__ = <VERSION> param in the file. In the setup.py file import the __version__ param and put it's value in the setup.py file like this:
version=__version__

*Another way is to use just a setup.py file with version=<CURRENT_VERSION> - the CURRENT_VERSION is hardcoded.

Since we don't want to manually change the version in the file every time we create a new tag (ready to release a new package version), we can use the following..
I highly recommend bumpversion package. I've been using it for years to bump a version.
start by adding version=<VERSION> to your setup.py file if you don't have it already.
You should use a short script like this every time you bump a version:
bumpversion (patch|minor|major) - choose only one option
git push
git push --tags

Then add one file per repo called: .bumpversion.cfg:
[bumpversion]
current_version = <CURRENT_TAG>
commit = True
tag = True
tag_name = {new_version}
[bumpversion:file:<RELATIVE_PATH_TO_SETUP_FILE>]

Note:

*

*You can use __version__ parameter under version.py file like it was suggested in other posts and update the bumpversion file like this:
[bumpversion:file:<RELATIVE_PATH_TO_VERSION_FILE>]

*You must git commit or git reset everything in your repo, otherwise you'll get a dirty repo error.

*Make sure that your virtual environment includes the package of bumpversion, without it it will not work.


text:
Q: What type of variable is most appropriate for this task? I am currently creating a class for a small project and ran into an interesting scenario that I haven't really dealt with before.
My program will just display information about certain items in a game. The category I'm having issues with is the costs of the item. For instance, the item cost can be:

*

*100 Silver and 300 Stone

*500 Copper, 300 Stone, and 2 Rare Metal

*175 Gold

The cost could be any of those, meaning it could only cost one type of 'currency' or could cost up to three different kinds of 'currency'. Also, each type of currency would contain a picture of it. So 100 Silver and 300 Stone would look something like: 100(Int) Silver(image) and 300(Int) Stone(Image)
So seeing as there could be multiple types of currency and images, would one store it in an array? Or another type of variable?
Just looking for someone to shed light on the issue. If it needs to be explained with a sample of the class, I can do so.
EDIT
Although my explanation lacked clarity, I received many good responses. In fact, quite a few are suitable to be the correct answer. I appreciate all the responses and have upvoted each of you who had helpful feedback.
Thank you everyone!!!

A: You can create a very simple class Cost
public class Cost {
    int amount;
    String currency;

    public Cost(int amount, String currency) {
        this.amount = amount;
        this.currency = currency;
    }
}

and then implement the cost as an ArrayList
List<Cost> cost = new ArrayList<Cost>();
cost.add (new Cost(100, "Gold"));

This is simple enough while retaining flexibility to add new currencies

An example with an enum:
public class Cost {
    private int amount;
    private Currency currency;

    public Cost(int amount, Currency currency) {
        this.amount = amount;
        this.currency = currency;
    }
    public enum Currency {
        GOLD { public String toString() { return "gold"; } },
        SILVER { public String toString() { return "silver"; } },
        COPPER { public String toString() { return "copper"; } },
        STONE { public String toString() { return "stone"; } },
        RARE_METAL { public String toString() { return "rare"; } }
    }

    public String getImageName() {
        return new String(currency.toString()+".png");
    }

    public int getAmount() {
    return amount;
    }

    public String getCurrency() {
        return currency.toString();
    }
}

List<Cost> costs = new ArrayList<Cost>();
cost.add (new Cost(100, Cost.Currency.GOLD));
cost.add (new Cost(200, Cost.Currency.COPPER));

for (Cost cost: costs) {
    ImageIcon icon = createImageIcon(cost(i).getImageName());
    JLabel label1 = new JLabel(cost(i).getAmount(), icon, JLabel.CENTER);
}

A: Java's an object-oriented language; why not have an Item or Commodity class that encapsulates the behavior that you want instead of relying on primitives?  You'll hide complexity from clients by encapsulating it into the class.
If you have several Currency instances, you can also encapsulate conversions between them rather than embed constants all over your code.  If you change conversions, you'll only have to do it in one place.

A: Also, and this is important so I'm putting it at the top, even though it's an edit.
Don't include pictures in anything with this You should only have pictures on the user interface. In theory, you could run the game from a command prompt just typing your commands. "Buy sword" "sell junk" "attack goblin" etc. When you start incorporating your UI and "business logic" you find yourself having a very difficult time separating the two when it comes time to fix stuff.
I would have something like this
class Cost {
    // use the builder pattern - it makes it VERY easy to add new currency types
    // without breaking existing types
    // it does make it more difficult to remove types, but you would have to
    // modify everywhere a type that used a removed currency anyway, so it's no
    // ADDITIONAL work there.
    class Builder {
        private int copper;
        private int silver;
        private int gold;

        public Builder copper(int cu) { this.copper = cu; return this; }
        public Builder silver(int ag) { this.silver = ag; return this; }
        public Builder gold(int au) { this.gold = au; return this; }

        public Cost complete() {
            return new Cost(this);
        }

    }
    public final int copper;
    public final int silver;
    public final int gold;
    // other costs;

    private Cost(CostBuilder cb) {
        this.copper = cb.copper;
        this.silver = cb.silver;
        this.gold = cb.gold;
    }

}

class Item {
    String name;
    // other stuff

    private Set<Cost> costs;

    public Set<Cost> getCosts() {
        return java.util.Collections.unmodifiableSet(costs);
    }
}

use the code like this:
Cost allGold = new Cost.Builder().gold(175).complete();
Cost goldAndSilver = new Cost.Builder().silver(50).gold(50).complete();
Cost allMaterials = new Cost.Builder().gold(10).silver(30).copper(100).complete();

Set<Cost> costs = new HashSet<Cost>();
costs.add(allGold);
costs.add(goldAndsilver);
costs.add(allMaterials);

Item swordOf1000Truths = new Item("Sword of 1000 truths",costs);

and later you can do this
// assume player found allGold by quering for what costs he could use
if(player.canAfford(allGold)) {
    player.spend(allGold);
    player.addItem(swordOf1000Truths);
}

A: In the code I would just store the cost of the item as a single value (int or double).  Then when you display the cost have some class that translates the internal value into whatever currency you want to show.
No need to carry around an array of values if all the values are essentially the same.

A: No built in type of variable is appropriate, so you need to make Classes that represent your concepts. At least Cost should be a class and maybe also currency, but an Enum might do for that.

A: I would probably go for an enum to represent the various types of currencies.  Something like this:
public enum Currency {
    GOLD("gold"),
    SILVER("silver"),
    COPPER("copper"),
    STONE("stone");

    private String displayName;

    private Currency(String displayName) {
        this.displayName = displayName;
    }

    public String toString() {
        return displayName;
    }
}

Here the enum actually has a field to store a user-friendly display name for the currency; this isn't necessary--I just threw it in to make the output pretty later on in my example.  It could also store a corresponding image filename (or even an actual image) but that might be better left up to whatever UI you're using rather than putting it in the model here.
Your item needs just one Map to store its costs:
private Map<Currency, Integer> costs;

A rough example of how to use it:
Item vorpalSword = new Item();
vorpalSword.getCosts().put(Currency.GOLD, 100);
vorpalSword.getCosts().put(Currency.STONE, 300);

StringBuilder costOutput = new StringBuilder();
for(Map.Entry<Currency, Integer> cost : vorpalSword.getCosts().entrySet()) {
    costOutput.append(cost.getValue() + " " + cost.getKey() + " ");
}
System.out.println(costOutput.toString());


text:
Q: Create list of objects for use by ObjectListView [python] I'm new to classes and to the python module ObjectListView.
I wish to create a text-editable window using ObjectListView, but the example I'm basing my work on requires the objects which each define text entries of a multi-columned row, should be accessible in a list such as this:

names = [MyClass("James", "Cameron"),
             MyClass("Samantha", "Jones")]

(Note that quotation marks only bookend the first name and surnames of each entry).
I currently hold my names in a standard dictionary which is in this format:

namesDict = { "James":"Cameron",
                      "Samantha":"Jones"}

My attempt to convert my dictionary into the format required is here:
namesDict = { "James":"Cameron","Samantha":"Jones"}
out = []
for key in namesDict:
out.append("MyClass(\""+key+"\",\""+namesDict[key]+"\")")
print(out)

My code leaves me with the following product, which is all good EXCEPT for the single quotation marks around each entry in the list:

['MyClass("James","Cameron")','MyClass("Samantha","Jones")']

I'm not sure how to get rid of these single quotes. I'm also assuming that there may be a standard technique to make objects from dictionaries which I'm simply not aware of?

A: The quote marks indicate that you're dealing with string literals, as that's what you've passed to the out list. Assuming your MyClass constructor takes two arguments, you can add an instance to your list like:
out.append(MyClass(key, namesDict[key])

However, this won't print the way you expect, it will use the object.__str__ which returns object.__repr__():
<__main__.MyClass object at 0x000002571A58B400>

You can override this in your class:
class MyClass:
    def __init__(self, first, last):
        self.first = first
        self.last = last
    def __str__(self):
        return self.__class__.__name__ + '("' + '","'.join([str(v) for k,v in vars(self).items()]) + '")'

And then the instances of MyClass will be printed neatly:
>>> m = MyClass('James','Cameron')
>>> print(m)
MyClass("James", "Cameron")