text:
Q: Compile fails for [Error] ld returned 1 exit status This program (which is supposed to implement a linked list) terminates when I run it, saying that id returned 1 exit status.
I think the problem is with linking. Am I doing it wrong or am I missing something?
#include<stdio.h>
#include<stdlib.h>

struct link{
    int data;
    struct link *next;
};

struct link** create(int value, struct link** head);
void print(struct link** head);

struct link** create(int value,struct link** head)
{
    struct link* newnode = (struct link*) malloc(sizeof(struct link));
    struct link* temp=*head;

    if(head==NULL)
    {
        newnode->data=value;
        newnode->next=NULL;
        *head=newnode;
    }
    else{

        while((temp->next)!=NULL)
        {
            temp=temp->next;
        }

        newnode->data=value;
        temp->next=newnode;
        newnode->next=NULL;
    }

    print(head);
    return head;
}

void print(struct link** head)
{
    struct link* temp=*head;
    while(temp!=NULL)
    {
        printf("%d------>",temp->data);
        temp=temp->next;
    }
}

int main()
{
    struct link** head=NULL;
    int choice,value;

    do{
        printf("the no. wanted to enter into the list:");
        scanf("%d", &value);
        create(value,head);

        printf("want to enter more press y or Y");

        fflush(stdin);
        scanf("%c", &choice);
    }while(choice=='y' || choice=='Y');

    getch();
}

A: Seriously?
while(choice=='y' or choice=='Y');
                  ^^

Below is correct:
while(choice=='y' || choice=='Y');
                  ^^

Note: or can be used in C++ (as noted by: abelenky)

A: change to
at main
struct link *head=NULL;

char choice;

create(value, &head);

at create
if(*head==NULL) // or if(temp==NULL)


text:
Q: How do I escape an escape character with ANTLR 4? Many languages bound a string with some sort of quote, like this:
"Rob Malda is smart."
ANTLR 4 can match such a string with a lexer rule like this:
QuotedString : '"' .*? '"';
To use certain characters within the string, they must be escaped, perhaps like this:
"Rob \"Commander Taco\" Malda is smart."
ANTLR 4 can match this string as well;
EscapedString : '"' ('\\"|.)*? '"';
(taken from p96 of The Definitive ANTLR 4 Reference)
Here's my problem:  Suppose that the character for escaping is the same character as the string delimiter.  For example:
"Rob ""Commander Taco"" Malda is smart."
(This is perfectly legal in Powershell.)
What lexer rule would match this?  I would think this would work:
EscapedString : '"' ('""'|.)*? '"';
But it doesn't.  The lexer tokenizes the escape character " as the end of string delimiter.

A: (Don't vote for this answer; vote for @Bart Kiers' answer.)
I'm offering this for completeness, as it's a small piece of a Powershell grammar.  Combining the escape logic from p76 in The Definitive ANTLR 4 Reference with Bart's answer, here are the rules necessary for lexing escaped strings in Powershell:
EscapedString
    : '"'      (Escape | '""'   | ~["])* '"'
    | '\''     (Escape | '\'\'' | ~['])* '\''
    | '\u201C' (Escape | .)*? ('\u201D' | '\u2033')   // smart quotes
    ;

fragment Escape
    : '\u0060\''    // backtick single-quote
    | '\u0060"'     // backtick double-quote
    ;

These rules handle the following four ways to escape strings in Powershell:
'Rob ''Commander Taco'' Malda is smart.'
"Rob ""Commander Taco"" Malda is smart."
'Rob `'Commander Taco`' Malda is smart.'
"Rob `"Commander Taco`" Malda is smart."

A: Negate certain characters with the ~ operator:
EscapedString : '"' ( '""' | ~["] )* '"';

or, if there can't be line breaks in your string, do:
EscapedString : '"' ( '""' | ~["\r\n] )* '"';

You don't want to use the non-greedy operator, otherwise "" would never be consumed and "a""b" would be tokenized as "a" and "b" instead of a single token.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show product attribute options product page in Magento? I am using an attribute to show an attribute value in the product page using this code:
<?php if ($_product->getProductShipping()):?>

Shipping Charges : Rs.<?php echo $_product->getProductShipping(); ?>
<?php endif;?>

It is showing Shipping Charges : Rs. 20. What is the value of this attribute? If some products have no value in this product then nothing is showing there but I want to show Free shipping if no value is there.

A: just simple if/else condition can do work for you
<?php if ($_product->getProductShipping()){?>

Shipping Charges : Rs.<?php echo $_product->getProductShipping(); ?>
<?php }else { ?>

Shipping Charges : Free Shipping
<?php } ?>

let me know if you face any problem in this code.


text:
Q: Wpf Realtime DataBinding To Listview I want to bind data (1000 record per second, i mean 25 records per 25 milisecond) to a listview and it must be ordered descending by datetime.
I have used observable collection. When i get data from the source (e.g socket), i am adding to my collection by inserting the model at the zero index of observable collection.
 observableCollection.Insert(0, model);

It is working no problem but it is using %30 cpu (intel i5). And if i open these windows 10 times, my application is getting slower. I am using virtualizing properties.
If i don't set the itemsource of the listview, cpu usage is about %0.
This is my listview:
 <ListView HorizontalAlignment="Stretch" VirtualizingStackPanel.IsVirtualizing="True"  VirtualizingStackPanel.VirtualizationMode="Recycling"   Name="listView" ScrollViewer.CanContentScroll="True" Grid.Column="0"   VerticalAlignment="Stretch"  ItemsSource="{Binding observableCollection}">
  <ListView.ItemsPanel>
    <ItemsPanelTemplate>
      <VirtualizingStackPanel></VirtualizingStackPanel>
    </ItemsPanelTemplate>
  </ListView.ItemsPanel>
  <ListView.View>

    <GridView>
      <GridViewColumn DisplayMemberBinding="{Binding ID}" Width="75"  Header="Id" />
      <GridViewColumn DisplayMemberBinding="{Binding Time}" Width="175"  Header="Time"  />
      <!-- Ten more columns -->
    </GridView>
  </ListView.View>
</ListView>

Is it correct to use listview?
How can i increase the performance?
Is there any other techniques to do this?

A: The INotifyCollectionChanged event of ObservableCollection is the bottleneck. Try to build your result list first, then to create an ObservableCollection from your list, and then assign the ObservableCollection to the ItemsSource of your control.

A: Consider a fake scroll bar by only adding the top 100 items to the list box but setting the maximum and value of a separate scroll bar to the actual data size and position. This requires more code to keep the scroll bar and list box in sync.
The amount of data and the number of updates is just too much and faking a long list might be the only solution.


text:
Q: Munin not generating graphs My clean munin install is not generating graphs, i did everything listed in this URL to debug
http://munin-monitoring.org/wiki/FAQ_no_graphs#Ijustreadtheaboveanswerandtherestillarentanygraphs
i can successfully connect via telnet to the node.
-The nodes comand display the node correctly
-The list command shows the list of plugins correctly.
-The fetch command provides an empty output!!!
i opened the munin-node.log file to see what's going on, and every entry logs (i think 1 entry for every plugin) show one of this 2 error messages (when i restart the node the error switch from one to another)
1-
Error output from threads:
2013/08/08-07:38:04 [2659]      Insecure directory in $ENV{PATH} while running with -T switch at /usr/share/perl5/Munin/Node/Service.pm line 241.
2013/08/08-07:38:04 [2659] Service 'threads' exited with status 255/0.
2-
Error output from vmstat:
2013/08/08-07:35:02 [1096]      2013/08/08-07:35:02 [1186] Died at /usr/share/perl5/Munin/Common/Timeout.pm line 66,  line 74.
i have no clue, of how to solve this.
Im using Ubuntu 12.04 and the installed munin version is the 1.4 ... since the 2.x are not available for ubuntu 12.04

Maybe someone with experience with pearl could orient me on how to edit the source to get rid of the error!!!


text:
Q: Service cannot be injected to controller in Angular.js project I am trying to create a simple single page app with Angular. I am just trying to connect a custom service to the main controller at the moment. It simply returns the length of a string to the controller.
This is from my app.js:
angular
  .module('weatherApp', [
    'ngResource',
    'ngRoute'
  ])
  .config(function ($routeProvider) {
$routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  .when('/about', {
    templateUrl: 'views/about.html',
    controller: 'AboutCtrl',
    controllerAs: 'about'
  })
  .otherwise({
    redirectTo: '/'
  });
});

This is my main controller:
angular.module('weatherApp')
  .controller('MainCtrl', ['$scope', 'weatherService', function ($scope, weatherService) {
$scope.name = weatherService.name;

$scope.$watch('name', function() {
  weatherService.name = $scope.name;
});

$log.log(weatherService.name);
$log.log(weatherService.namelength());

}]);

And this is the service:
angular.module('weatherApp')
  .service('weatherService', function () {
var self = this
this.name = 'Moscow weather';

this.namelength = function() {

  return self.name.length;

};
});

Error in the browser debugger:
Error: [$injector:unpr] Unknown provider: weatherServiceProvider <-     weatherService <- MainCtrl


text:
Q: How to change the width of the middle line in box whisker plot in ggplot2 in R? In the current version of ggplot2, the middle line in a box-whisker-plot is drawn bold compared to the other lines:
library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

I think this was not the case in some older versions. Is there a way to separately adjust the width of the middle line?

A: Poorly documented, but you can use the fatten argument in geom_boxplot
library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot(fatten = 0)

p + geom_boxplot(fatten = 4)


text:
Q: Http server security analyser and sanitizer proxy I'm looking for software that will monitor all https request coming through our proxy server.
We currently use nginx that proxies to our application servers.
Ideally, the solution will sit between nginx and the application servers.
More importantly, we're looking for the software to be able to whitelist query parameters, stripping any extra parameters from request and ordering parameters so requests can be cache more effectively.
Some other things it'd be nice to do would be to detect and reject sql injection, malicious urls, handle custom block rules, rate limiting POST requests would be nice, etc--http request sanitizer and security tool.

A: You might want to take a look at modsecurity.


text:
Q: What's wrong in Classic ASP StoredProcedure insert statement Here is the classic ASP code
Set objCommandSec = CreateObject("ADODB.Command")
        With objCommandSec
            Set .ActiveConnection = MyConn
            .CommandType = adCmdStoredProc
            .CommandText = "ReportsPDFInsert"

            .CreateParameter "@StatsID", adInteger, adParamInput
            .Parameters("@StatsID") = xStats_ID

            .CreateParameter "@MemberID", adInteger, adParamInput
            .Parameters("@MemberID") = xMemberID

            .CreateParameter "@LanguageID", adInteger, adParamInput
            .Parameters("@LanguageID") = 1  '1=EN

            .CreateParameter "@PDFFilename", adVarWChar , adParamInput
            .Parameters("@PDFFilename") = PDFFilename

            .Execute
        End With

Here is the stored procedure code
ALTER PROCEDURE [dbo].[ReportsPDFInsert]
-- Add the parameters for the stored procedure here
@StatsID INT
,@MemberID INT
,@LanguageID     INT
,@PDFFilename NVARCHAR(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
INSERT INTO [dbo].[ReportsPDF]
       ([StatsID]
       ,MemberID
       ,[LanguageID]
       ,[PDFFilename]
       ,[DateCreated])
 VALUES
       (@StatsID
       ,@MemberID
       ,@LanguageID
       ,@PDFFilename
       ,GETDATE())

END

I get error as
Error number: -2147217904
Error description: Procedure 'ReportsPDFInsert' expects parameter '@StatsID', which was not supplied.
Source: Microsoft OLE DB Provider for SQL Server
If I execute the stored procedure itself, then it is working fine.  I have similar classic asp code in other page, and that works fine as well.  yes, I made sure xStats_ID does have value.  I printed just before the .Execute and I see the value.
Please somebody shed some light.  Thanks

A: Try appending the parameters explicitly using something like this:
cmd.Parameters.Append cmd.CreateParameter("@StatsID",adInteger, adParamInput,xStats_ID)

instead of .Parameters("")
Here is another post that might help:
How to make a parametrized SQL Query on Classic ASP?

A: Only today I figured what was the problem.
I haven't included the adovbs.inc file for the constants to work.
And I don't know why it was throwing some other error message.
good reason to move away from Classic ASP [only if my boss listens]

A: Try dropping the "@" in your parameter names.


text:
Q: Parent node workspace of Matrix jobs in Jenkins When using the repo plugin in Jenkins for multi configuration jobs.
The source code is checked out once in the matrix parent workspace and then again in all the nodes where the multi configuration job spawns.
Is there a way to avoid the source code checkout on the parent node, which seems to be a duplication and unnecessary wastage of time when the same code is again going to be checked out in the matrix.

A: There is no way to avoid it. That's the way the multi-configuration job works. Your options are:

*

*Do not use multi-configuration job. You can replace it with multiple jobs or with a single job that takes a parameter or parameters and trigger all those jobs.

*Keep using multi-configuration job but minimize the downsides of the parent checkout by having enough disk space for it and/or making sure the checkout is as fast as possible. There are ways to speed up a checkout but how exactly to do it depends on which version control system you use.


text:
Q: Java array of ArrayList - strange goings on? I've been pulling my hair out with this all day. Probably a newb error of some sort, but I can't get my head around it.
It started out more complicated, but I've simplified it to:
public class Main {

    static ArrayList<Selection>[] a = new ArrayList[2];

    public static void main(String[] args) {

        // Initialise the Selection ArrayList

        for (int i=0; i < a.length; i++) {
            a[i] = new ArrayList<Selection>();
        }

        callTest();

    }

    public static void callTest () {

        a[0].add(new Selection(true));
        a[1].add(new Selection(false));

        System.out.println(a[0].get(0).getTF());
        System.out.println(a[1].get(0).getTF());
    }
}

class Selection {

    private static boolean trueFalse;

    public Selection (boolean iTF) {
        trueFalse = iTF;
    }

    public boolean getTF () {
        return trueFalse;
    }
}

Running the program will return:
false
false

instead of the expected (at least to me):
true
false

Can someone please shed some light on this? It appears that whenever the value held in a Selection object is altered, ALL the Selection objects are altered, even though they have a different object reference. Have I done something silly?

A: This is because in Selection you declare trueFalse as a static variable.  Simply change it to :
class Selection {

    //one per Selection, versus a global variable
    private boolean trueFalse;

    public Selection (boolean iTF) {
        trueFalse = iTF;
    }

}

A: Change
private static boolean trueFalse;

to
private boolean trueFalse;

That should fix it. Basically since trueFalse is static, its shared by each instance of the Selection class.

A: In class Selection you've declared trueFalse as static. That means that it's part of the class, not part of the instances, so it's shared by all the instances.

A: From The Java Tutorials:

*

*Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

This is most definitely a "newb" error.

A: It's because truefalse is static, part of the class and not part of the object. So there's only one truefalse value for all of the Selection objects, and it just gets altered every time a constructor is called. You'll want to remove the static modifier, then all should work as planned!
To avoid problems like this in future, it's best at least while you're starting out to not declare things as static like this - keep to objects where you possibly can, even when you know you're only creating one! This gets you in a nice OO mindset and reduces these types of problems. Of course, there are places where you need to use it and it's the right thing to do, but you'll learn that as you go along.


text:
Q: Azure DevOps Project Now Showing up in Visual Studio 2019 I am trying to access my Azure DevOps repo using Visual Studio 2019 from a VM. But projects were not getting listed even after login. Previously the Projects used to visible. But now it is not showing up. But I could access the repo from the Visual Studio 2019 installed in my laptop.

A: I myself fixed this issue with this reference (https://github.com/microsoft/azure-devops-tls12). All you need to do is run the script AzureDevOpsTls12Analysis.ps1 available at this location and follow the steps as shown during script execution.


text:
Q: There are $m$ distinct sets of $k$ positive integers such that no two form a fat pair, show that $m[ELMO 2015] Let $m, n, k > 1$ be positive integers.  For a set $S$ of positive integers, define $S(i,j)$ for $i<j$ to be the number of elements in $S$ strictly between $i$ and $j$.  We say two sets $(X,Y)$ are a fat pair if $$ X(i,j)\equiv Y(i,j) \pmod{n} $$ for every $i,j \in X \cap Y$.  (In particular, if $ X \cap Y<2$ then $(X,Y)$ is fat.)
If there are $m$ distinct sets of $k$ positive integers such that no two form a fat pair, show that $m<n^{k-1}$.


text:
Q: Cordova using ASP.NET WebService (.asmx) not woking I am having a trouble using cordova and .asmx as my backend code. It always returning undefined error.
Here's my jQuery code:
$('#signin').click(function (e) {
        $('#frmLogin').validate();

        $('#uid').rules('add', {
            required: true,
            messages: {
                required: 'Input your username.'
            }
        });

        $('#upassword').rules('add', {
            required: true,
            messages: {
                required: 'Input your password.'
            }
        });

        if ($('#frmLogin').valid()) {
            var credentials = {}
            credentials.username = $('#uid').val();
           credentials.password = $('#upassword').val();

            $.ajax({
                type: 'POST',
                url: 'http://localhost/WebService/WebService.asmx/Signin',
                data: JSON.stringify(credentials),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
            return false;
        }
    });

Here's my code in .asmx file
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>    <ToolboxItem(False)> _
Public Class WebService
  Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function Signin(ByVal username As String, ByVal password As String) As String
    Dim AccountStatus As String = (New Account.Membership).GetAccountStatus(username, password)

    Return AccountStatus
End Function
End Class

It should suppose to return what's inside the AccountStatus value.
UPDATE
Here's the error return in the console

rippleapi.herokuapp.com/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//localhost/WebService/WebService.asmx%3Fop%3DSignin:1 POST https://rippleapi.herokuapp.com/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//localhost/WebService/WebService.asmx%3Fop%3DSignin 500 (Internal Server Error)

UPDATE: SOLVED
I got it now. I just added
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

in web.config file
Thank you for your help.


text:
Q: How to get array of checkbox Here is my checkbox group
<input type="checkbox" name="checkGroup" id="all" value="0" >All
<input type="checkbox" name="checkGroup" id="one" value="1">One
<input type="checkbox" name="checkGroup" id="two" value="2">Two
<input type="checkbox" name="checkGroup" id="three" value="3">three

how to get array of checkbox by name "checkGroup" and then base on value set it checked / uncheck.
e.g.
In edit mode i am getting string 012 from database
then i need to set checked as All, One amd Two.
Please help thanks

A: // Help us with finding values in arrays
Array.prototype.has=function(v){
  for (i=0; i<this.length; i++) {
    if (this[i]==v) return true;
  }
  return false;
}

// Define our values
var myVals = [0,1,2];

// Check/Uncheck Accordingly
$(":checkbox[name='checkGroup']").each(function(){
  if (myVals.has($(this).val())) {
    $(this).attr("checked","checked");
  } else {
    $(this).removeAttr("checked");
  }
});

A: If you go for this approach, of returning a string of numbers not separated by any character (like "012"), you can only handle without problems up to 10 elements (0-9):
function checkItems(str) {
  var checkboxes = $("input:checkbox[name='checkGroup']");
  checkboxes.attr('checked', false); // uncheck all boxes first
  checkboxes.each(function () {
    if (str.indexOf(this.value) >=0) {
      this.checked = true;
    }
  });
}

checkItems('012'); // checks all, one, and two

Check an example here.


text:
Q: Finding a handwritten dataset with an already extracted features I want to test my clustering algorithms on data of handwritten text, so I'm searching for a dataset of handwritten text (e.g. words) with already extracted features (the goal is to test my clustering algorithms on, not to extract features). Does anyone have any information on that ?
Thanks.

A: There is a dataset of images of handwritten digits : http://yann.lecun.com/exdb/mnist/ .

A: Texmex has 128d SIFT vectors
"to evaluate the quality of approximate
nearest neighbors search algorithm on different kinds of data and varying database sizes",
but I don't know what their images are of; you could try asking the authors.


text:
Q: gedit-latex-plugin not working correctly I've installed the gedit-latex-plugin on my machine running 15.10.
When I enable the plugin, it shows the markup colouring in .tex files, but the menu option New LaTeX Document... doesn't appear, and neither do the additional menubar buttons, sidebar panels, or the menu options related to LaTeX documents, such as Build, etc.
The installed version of gedit is 3.10.4, plugin version 3.8.0-3build1.
I have the same plugin installed on a machine running 14.04 LTS, and the plugin works fine. That machine is also running gedit 3.10.4, however the plugin version is 3.8.0-1, which looks correct according to the Launchpad page, but conspicuously differs from 15.10.
Note that on both machines, the plugin was installed using sudo apt-get install gedit-latex-plugin.

A: Found that this is a known bug. See here.


text:
Q: How can I save only the time in a sqlite database? How can I save any time (format: HH:MM:SS) in my sqlite-database?
I don't need the date, only the time.

A: SQLite does not have datetime storage format
You can use different type of fields to store and functions to read value.
Try to store it as a string with desired format. It should work.

A: Both the DATE and the DATETIME SQL types are stored in SQLite as the NUMERIC type. The NUMERIC type is almost identical to an INTEGER, apart from the use of CAST. Thus there isn't a great deal of advantage in stripping the date and storing only the time, as an integer say - it won't make a difference to the underlying storage.
Keep storing DATETIME, and extract only the time of the day at your presentation layer, to display the time. To be more strict, always set the date to something constant, for example the epoch with just the time of the day added to it. Then you can use the unixepoch modifier with the SQLite date functions when necessary.
For example,
SELECT time(1092941466, 'unixepoch', 'localtime');

Will compute time given a timestamp of 1092941466 (including the date), compensate for your local timezone, and display only the time of day part:
Example output: 04:51:06

A: You can use a trigger to update your DATETIME field to contain only a Time or a Date. For an example you can create a trigger for insert of table name "logs" to refine the time and date fields like this:
CREATE TRIGGER "on_insert_logs"  AFTER INSERT ON "logs"

BEGIN
UPDATE logs SET time = time(time(), 'localtime')  WHERE id = new.id;
UPDATE logs SET date= date(date(), 'localtime')  WHERE id = new.id;

END


text:
Q: Querying hierarchical data in SQL How do you write a recursive SQL query that shows the diffrent levels of hierachical relationship as individual results?

I have a table in my database (Container) that has a hierarchical relationship with itself (any container can have many inner containers). I'm trying to create a view that shows each container with all of its outers (not just its immediate outer) along with how many levels deep the inner container is. For example:
If my Container table had the following records in it:

*

*Id: 1 outerId: null

*Id: 2    outerId: 1

*Id: 3    outerId: 1

*Id: 4    outerId: 2

*Id: 5 outerid: 4

I would want the view to show:

*

*innerId: 2  outerId:1   lvl:1

*innerId: 3  outerId:1   lvl:1

*innerId: 4  outerId:1   lvl:2

*innerId: 4  outerId:2   lvl:1

*innerId: 5   outerId:1         lvl:3

*innerId: 5   outerId:2         lvl:2

*innerId: 5   outerId:4         lvl:4

NOT

*

*Id: 2     Path: 1

*Id: 3     Path: 1

*Id: 4     Path: 1,2

*Id: 5     Path: 1,2,4

Basically, I want to be able to find out what inner containers are inside of a specific container by executing: select innerId from v_MyView where outerId = @outer_id  and find out what containers a specific container is in by executing: select outerId from v_MyView where innerId = @inner_id
Update
I'm using SQL Server 2012, and I'm pretty familer with recursive CTEs. The issue that I am having is not that I don't know how to write a recursive CTE, but rather that the I need the output to be in multiple rows rather than a concatinated field in the view.
This is what I already have:
with MYCTE as
(
    select
         Id,
         Cast(null as varchar(max)) as cntr_path,
         0 as lvl
      from Container
      where Container.outerId is null
    union all
    select
        Container.Id,
        IsNull(cntr_path + ',','') + '[' + cast(Container.outerId as varchar(max)) + ']',
        lvl + 1
      from Container join MYCTE
        on Container.outerId = MYCTE.Id
)
select * from MYCTE where cntr_path is not null

but this produces only one row per inner container. What I am wanting is one row per inner container per outer container
I guess the best way to describe the view that I want is as a "linking table" that links every outer container with every one of their inners - with both the "outerId" and the "innerId" acting like foreign keys (both pointing to Id in Container).

A: If you are using SQL Server, then check out this Microsoft link.  It details Recursive Common Table Expressions in great detail.
In Oracle, here is a link that describes Hierarchical Queries.
MySQL hierarchical queries.
The examples given in the articles will give you the necessary stepping stones to resolve your issue.

A: After sleeping on it for a bit, I realized that I had misidentified the anchor of my recursive CTE. Rather than the outermost containers being my anchor (as in my updated example), the anchor should be every container with an outer:
select
     Id as InnerId,
     Container.outerId as OuterId
     1 as lvl
  from Container

which makes the recursive portion of my CTE:
union all
select
    MYCTE.InnerId,
    Container.OuterId
    lvl + 1
  from Container join MYCTE
    on Container.Id = MYCTE.OuterId
  where Container.OuterId is not null


text:
Q: different encoding problem when using knit and running chunk I am reading csv files that has the character ý  which seems to cause a problem prompting the message:
Error in type.convert.default(data[[i]], as.is = as.is[i], dec = dec,  :
invalid multibyte string at ''
I have managed to overcome this by adding the function: Sys.setlocale("LC_ALL", "C").
Yet, this does not work when I press "knit". Then I get the same error message as above.
I have managed to overcome this by adding an fileEncoding "latin1" for each csv file.
But now when I don't knit, just run the chunk, it doesn't work!
I get an eroor "invalid input found on input connection- filename- EOF within quoted string".
So I need to keep adding and deleting the fileEncoding...
Can anyone help?


text:
Q: conda-build complains incorrectly that dependency is not included in meta.yaml I am trying to build a Python module (wsamdata) as a conda package. conda-build fails with the error message (full output: https://pastebin.com/sKXNEcB6)
RuntimeError: Setuptools downloading is disabled in conda build.
Be sure to add all dependencies in the meta.yaml  url=https://pypi.org/simple/click/

click is a dependency, and therefore I have included it in my meta.yaml (see following), so I am a bit confused to see this message.
package:
  name: wsamdata
  version: 0.6.0
source:
  git_rev: v0.6.0
  git_url: https://github.com/kinverarity1/wsamdata
requirements:
  build:
    - python
    - pip
    - setuptools
    - numpy
    - pandas
    - geopandas
    - sqlparse
    - click
    - cx_Oracle
    - pillow
    - sqlalchemy
    - python-sa-gwdata>=0.5.4
    - lasio
  run:
    - python
    - numpy
    - pandas
    - geopandas
    - sqlparse
    - click
    - cx_Oracle
    - pillow
    - sqlalchemy
    - python-sa-gwdata>=0.5.4
    - lasio

Obviously click is also included under install_requires=[...] in the wsamdata package's setup.py file:
from setuptools import setup

setup(
    name="wsamdata",
    version="0.6.0",
    packages=["wsamdata"],
    install_requires=[
        "python-sa-gwdata>=0.5.4",
        "pandas",
        "geopandas",
        "sqlparse",
        "click",
        "cx_Oracle",
        "pillow",
        "numpy",
        "sqlalchemy",
        "lasio",
    ]
)

I cannot share the source for wsamdata, so I understand this is not a reproducible example, but I am stuck and am wondering if I am missing something obvious. I've been able to successfully use conda-build on this machine to build a conda package for python-sa-gwdata.
I have found other similar questions, but they related to conda skeleton setups which produced meta.yaml files with missing requirements. I have instead written this meta.yaml from scratch.
My .condarc file:
channels:
  - kinverarity
  - conda-forge
  - defaults
ssl_verify: true
auto_update_conda: true
always_yes: true
show_channel_urls: true
create_default_packages:
  - pip
  - black
pip_interop_enabled: true
anaconda_upload: false

A: In case anyone stumbles upon this, I had the same problem and resolved it using
--single-version-externally-managed --record=record.txt
options at the pip install command, as suggested in the anaconda cloud documentation
If you are using build.sh or bld.bat, try:
$PYTHON setup.py install --single-version-externally-managed --record=record.txt

or
"%PYTHON%" setup.py install --single-version-externally-managed --record=record.txt

, respectively.
Alternatively, you can add this to your meta.yaml:
build:
  script: {{ PYTHON }} setup.py install --single-version-externally-managed --record=record.txt

or, if you are using conda skeleton, for packages already exist in pypi.org:
build:
  script: {{ PYTHON }} -m pip install . --single-version-externally-managed --record=record.txt --no-deps --ignore-installed --no-cache-dir -vvv

A: I had this problem as well and it was rooted in conflicting version information in the setup.py/requirements.txt files compared to the meta.yaml files.  Look there and make sure any version specs are identical.  I was guided to this thanks to the ML post here:
https://groups.google.com/a/continuum.io/forum/#!msg/anaconda/dELRaivwdMg/5IWgDcdqAwAJ


text:
Q: Set alamofire cookies permenantly I am using Alamofire for my requests and I get cookies in some of them, everything works fine when I launch the app and use it but when I kill the app and reopen the cookies are not there anymore. I searched a lot and found this but none of the answers helped.
I try to save the cookies after each request and load them before sending request as below:
    func saveCookies(response: DataResponse<Any>) {
    let headerFields = response.response?.allHeaderFields as! [String: String]
    let url = response.response?.url
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
    var cookieArray = [[HTTPCookiePropertyKey: Any]]()
    for cookie in cookies {
        cookieArray.append(cookie.properties!)
    }
    UserDefaults.standard.set(cookieArray, forKey: "savedCookies")
    UserDefaults.standard.synchronize()
}

func loadCookies() {
    guard let cookieArray = UserDefaults.standard.array(forKey: "savedCookies") as? [[HTTPCookiePropertyKey: Any]] else { return }
    for cookieProperties in cookieArray {
        if let cookie = HTTPCookie(properties: cookieProperties) {
            HTTPCookieStorage.shared.setCookie(cookie)
        }
    }
}

But still when I kill the app, I can't get the data.

A: Try to save your cookies in UserDefaults like this:
var authToken: String {
    get {
        return defaults.value(forKey: TOKEN_KEY) as! String
    }
    set {
        defaults.set(newValue, forKey: TOKEN_KEY)
    }
}


text:
Q: HTML input type="submit" doubles row height in table I have a HTML table where some rows have a button like this:
  <td >
    <form action="..." method="GET">
      <input type="submit" value="..."/>
    </form>
  </td>

The rows with the input have about twice the height of other rows that have otherwise similar data. When I remove the just the input, the row height goes back to normal. I have the same behavior in Firefox and IE.
Is there any way I can have normal row height AND the <input/> button?

A: The <form> tag adds some white space by default in most browsers. That's likely the problem. Try adding the following to your cascading style sheet:
form {
    padding: 0;
    margin: 0;
    display: inline;
}

Failing that, we can "brute force" some other options in:
input {
    margin: 0;
    display: inline;
}
td {
    padding: 0;
}

(Of course, substituting more specific selectors if possible.)
If even that doesn't work, try using a tool like Firebug to identify where else the space could be coming from.


text:
Q: How to get the filters on a route in laravel I need to know which filters are applied to a specific oute. I've been reading through the api of laravel and I found that there is a method called getBeforeFilters() in the Route class.
getBeforeFilters()
I don't understand very well how this class works but what I thought about is that I needed to instantiate the Route class to use this function.
If this is correct how can I instantiate it - what parameters do I need to provide and what functions do I need to call-
If not then how can use it

Note: I tried to look for a constructor function in the Route class to
  know how to instantiate it but I couldn't find any

A: This is how you use it:
$filters = Route::current()->beforeFilters();

If you want to search for a route you have access to them all:
foreach(Route::getRoutes() as $route)
{
    echo 'host';
    var_dump($route->domain());

    echo 'uri';
    var_dump($uri);

    echo 'name';
    var_dump($route->getName());

    echo 'action';
    var_dump($route->getActionName());

    echo 'before filters';
    var_dump($route->beforeFilters());

    echo 'after filters';
    var_dump($route->afterFilters());
}

A: You can run php artisan routes from the command line to get a list of all the routes and their filters.


text:
Q: Actions on Google: Request contains an invalid argument I have a Google Assistant app already in production, which gives First Aid treatment procedures whenever someone is in need. I built this app with Dialogflow. It was running well for the past few months, but now whenever I call something after the app's first statement, it gives me this error:
Request contains an invalid argument.
The query pattern 'Where can I get `$SchemaOrg_Number:ordinal aid information?'
contains an undefined parameter` (name: 'ordinal' type: 'SchemaOrg_Number').

This error comes when I try to implement my app from Dialogflow to Google Assistant, and from the error message, it is not clear that exactly which part of the program is faulty. I have no idea where to go from here and I'd love your help. Thanks a tonne!
Here's my Dialogflow Screen
Here's the AoG Simulator Screen where the error happened

A: This error must have occurred due to the incorrect phrases in the Actions of your app. To check this go to Actions tab from the AOG console. Check every intent for any error. Also, check that the parameter used in the query must be defined below the phrases.
Actions menu screenshot
Parameters screenshot


text:
Q: Syntax error in SQL for create a table C# Hallo ladies and gentlemen
I am strugling with what I think should be a easy solution but can't find it
Basically I am creating a table through SQL and there is a problem with the SQL when I run it.
Here is my code:
OleDbCommand cmd = new OleDbCommand
(@"CREATE TABLE " + ClientID + "
(Transaction_ID       INT PRIMARY KEY NOT NULL,
Transaction           CHAR(255),
Date                  DATE,
Transaction_Amount    INT,
Balance               INT,
Deposited             INT,
Withdrew              INT,
Loan                  INT,
Applied               INT,
Approved              INT,
Payment_Monthly       INT,
Monthly_Income        INT)", mydb);
Now I tested my SQL statement to found out which part of my SQL gives the error and I have found when I remove the fieldsTransaction and Date it works. If I remove only one of them it still crashes. I even tried to change data types like CHAR(255) to VARCHAR(255) also DATE to INT.
To be honest I can't seem to find the problem.
Please help
Thank you for your time.
PS: ClientID is a combination of three numbers and three letters with a hashtag for example. 123#ABC

A: Those two column names are reserved words in SQL. Enclosing them in square brackets will solve your problem:
[Transaction] CHAR(255),
[Date] DATE,

Keep in mind that any time you access these fields in dynamic SQL or stored procedures, you will have to use the square brackets as well, i.e.
SELECT * FROM ClientTable WHERE [Transaction] = 'A'


text:
Q: StringBuilder OutOfMemoryException I have a StringBuilder that appends all the pixel in an image, this amount being extremely large. Every time I run my program, everything goes well, but once I change a pixel color (ArGB) I get a OutOfMemoryException at the spot where I clear the StringBuilder. The problem is that I need to create an instance of StreamWriter then add my text to it THEN set the file path.| My current code it:
StringBuilder PixelFile = new StringBuilder("", 5000);
Private void Render()
{
//One second run, I get an OutOfMemoryException
PixelFile.Clear();
//This is in a for but cut it out for reverence.
PixelFile.Append(ArGBFormat);
}

I do not know what is causing this. I have tried PixelFile.Length = 0; and PixelFile.Capacity = 0;

A: OutOfMemory probably means you're building the string too big for StringBuilder, which is designed to handle a very different type of operation.
While I'm at a loss for how to make StringBuilder work, let me point you at a more intuitive implementation that will be less likely to fail.
You can read and write from a file using direct binary through the BinaryReader and BinaryWriter classes. This can also save you a lot of effort since you can make sure you're serializing bytes instead of character strings or entire words.
If you absolutely must use plaintext, consider the StreamReader and StreamWriter classes directly, as they won't throw exceptions for size. Remember, streams are intended for this sort of operation, StringBuilder is not, so Streams are far more likely to work with far less effort on your part.
EDIT:

When the maximum capacity is reached, no further memory can be allocated for the StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.

Therefore, this is a limitation of the StringBuilder class and cannot be overcome with your current implementation.
EDIT: Additional implementation
In addition to StreamWriters which can write directly to files, you can also use the MemoryStream class to pipe information to memory instead of disk. Be aware this could lead to slow performance of the program, and I recommend instead trying to refactor the process to only need to perform a stream once.
That being said, it is still possible.
var mem = new MemoryStream();
var memWriter = new StreamWriter(mem);
// TODO: use memWriter.Write as per StreamWriter
mem.Position = 0;    // This ensures you are copying your stream from the beginning

// TODO: Show your file save dialog
var fileStream = new StreamWriter(fileNameFromDialog);
mem.CopyTo(fileWriter);    // Perform the copy


text:
Q: Showing that $\Bbb R^2/\Bbb Z^2$ is homeomorphic to $S^1 × S^1.$
Show that $\Bbb R^2/\Bbb Z^2$ is homeomorphic to $S^1 × S^1.$

$\textbf {My Attempt} :$ Consider the map $p : \mathbb R^2 \longrightarrow S^1 \times S^1$ defined by $p(x,y) = (e ^{2 \pi i x}, e^{2 \pi i y}),$ $(x,y) \in \mathbb R^2.$ Then it is easy to see that $p$ is continuous and surjective. Also $$p^{-1} \{ (e^{2 \pi i x}, e^{2 \pi i y}) \} = \{(x + m, y + n)\ |\ m, n \in \mathbb Z \}$$ which is the orbit of $(x,y)$ under the action of $\mathbb Z^2$ on $\mathbb R^2.$ Hence by universal property of quotient topology $p$ will induce a bijective continuous map $q : \mathbb R^2 / \mathbb Z^2 \longrightarrow S^1 \times S^1.$ Since $[x,y] = [x - [x], y - [y]]$ it follows that $\mathbb R^2 / \mathbb Z^2 = [0,1]^2/\mathbb Z^2.$ Since $[0,1]^2$ is compact it follows that $\mathbb R^2/ \mathbb Z^2$ is also compact. Hence $q$ is a homeomorphism.
Is my attempt correct? I think I need also to show that the map from $\mathbb R^2$ to $\mathbb R^2 / \mathbb Z^2$ is a quotient map. Then we can take the composition $$[0,1]^2 \hookrightarrow \mathbb R^2 \xrightarrow{\text {quotient map}} \mathbb R^2 / \mathbb Z^2$$ Isn't it so? Could anybody give me some suggestion regarding this?
Thanks for reading.

A: This is the same question as Prove that $\Bbb{R}^2/\Bbb{Z}^2\approx S^1\times S^1$ .
Your approach is correct, but it needs a little clarification. First observe that writing $\Bbb R^2/\Bbb Z^2$ is somewhat ambiguous: It could denote

*

*the quotient set from $\Bbb R^2$ by collapsing the subspace $\Bbb Z^2$ to a point.

*the quotient group whose elements are the cosets $(x,y) + \Bbb Z^2$.
Here we definitely need interpretation 2. Via the quotient homomorphism $p : \Bbb R^2 \to \Bbb R^2/\Bbb Z^2$ this set is given the quotient topology. You have correctly shown that you get a continuous bijection  $q : \mathbb R^2 / \mathbb Z^2 \longrightarrow S^1 \times S^1$. This is even an isomorphism of groups, but that is irrelevant.
I think the equation $\mathbb R^2 / \mathbb Z^2 = [0,1]^2/\mathbb Z^2$ is misleading. What you mean is certainly $p([0,1]^2) = \mathbb R^2 / \mathbb Z^2$. This is true and proves that $\mathbb R^2 / \mathbb Z^2$ is compact.


text:
Q: Can I use multiple URLs in the URL field of KeePass? I am using KeePass version 2.19. What I would like to do is have more than just one URL address associated with a given user name and password.
The entry for a given website might look something like this...
Title
google

User Name
email

Password
pass

URL
https://accounts.google.com/ServiceLogin?hl=en&continue=https://www.google.com/
https://accounts.google.com/ServiceLogin?hl=sv&continue=https://www.google.com/
https://accounts.google.com/ServiceLogin?hl=de&continue=https://www.google.com/

As you can see the ?hl=en changes into ?hl=sv and then to ?hl=de for the three different languages in which I wish to view the Google log-in page.
But this of course could be something completely different, like different web services from the same provider like YouTube and Gmail by Google. Very much like SE where you have several websites but only use one user name and password.
I imagine something along the lines of having multiple entries for one and the same website, where KeePass would actually prompt you to choose which one you want to use. So you have several user names and passwords that use the same URL. But is it possible to have several URLs using the same user name and password, so that KeePass asks me "to which of the following three URLs do you want to auto-log into with this password"?

A: Switch to KeePassXC.  As of the 2.5.0 release, this now works as you would expect.

The new Browser Integration entry settings page has a list view with any additional URL's. These URL's are added to the entry attributes with KP2A_URL_, which means those are directly compatible with Keepass2Android.

A: The answer from Oliver Salzburg is very good.
Complementing it, if you already have an entry and want to link another entry, go to the entry, properties, then tools, insert field reference and link to the type you need.
See an example here:

A: If you want to use multiple URLs in order to Auto-Type when you are on those URLs, you don't need to create copies with field references; they can be added in the Auto-Type settings.

If you use KeePass as a sort of bookmark manager for login pages, so you open URLs from KeePass and then login, rather than browsing to the login page in your browser and use KeePass's auto-type, then indeed creating multiple entries is what you want. (Your usage of full URL https://accounts.google.com/ServiceLogin?hl=en&continue=https://www.google.com/ rather than just https://accounts.google.com/ seems to suggest this.) Otherwise, this answer, with one entry per account matching multiple URLs might be a cleaner solution.

If you use KeePass with no plugins, then you presumably use a plugin/extension on the browser instead, i.e. a URL in Title Bar extension to add the current URL to the browser's window title, with either of these KeePass settings enabled:

*

*An entry matches if its URL is contained in the target window title

*An entry matches if the host component of its URL is contained in the target window title

In the case where the desired multiple URLs are exactly as described in the question, with the same domain name, the solution is simple, either use the domain (https://accounts.google.com/) as the URL, or check the second setting above.
But if you don't want to do either of these, or if the different URLs that you want to match are on different domains, then they can be added in the Auto-Type settings. For example, you have an entry with https://superuser.com/ as the URL. You want to use the same account on https://stackoverflow.com/. Then go to the Entry's Auto-Type settings, click "Add" at "Use custom sequences for specific windows:"

Enter *https://stackoverflow.com/* in "Target window", and leave the second setting at "Use default keystroke sequence of the entry", unless this particular page requires a different auto-type pattern.

(Normally Title/URL can match if contained anywhere in a window's title, putting asterisks on both sides of the second URL replicates this behavior.)
Regular expressions are supported, so if you want to match all Stack Exchange sites, you can use //https://[a-z]*\.?stackexchange\.com/.*// as a third URL, which matches https://stackexchange.com/anypath as well as https://subdomain.stackexchange.com/anypath. (You could also use *stackexchange.com/* without using regular expressions; but this would also match https://evilsite.com/phishing/stackexchange.com/)

If you don't use a browser extension to add the URL in window title, you use a KeePass plugin to match URLs, like I do, e.g. WebAutoType (Website). Then, the process of adding a second URL is similar, in the Auto-Type settings, but it is added explicitly as a URL:

This time, an asterisk is only needed at the end (https://stackoverflow.com/*), as it compares it explicitly to the address in the browser. If you want to match specifically to a single page rather than a domain, no asterisk is needed.
Again, regular expressions are supported, so you can use //https://[a-z]*\.?stackexchange\.com/.*//. But since v6.1 (2019-06-15), WebAutoType has intelligent URL field matching, whereby:

Rather than just starts-with, it will now try and match any URL that has the URL field value as a base, now including sub-domains.

This is specifically for the URL field, not other custom Auto-Type settings you add. So you can just use https://stackexchange.com/ in the entry's URL field, and https://superuser.com/* and https://stackoverflow.com/* as the second and third URLs, thus matching all Stack Exchange sites without needing regular expressions.

A: You can create a copy of a password entry:

And then only use references for username and password in the new entry:

Then, adjust the URL in the new entry.

A: A friendly approach with GUI oriented users in mind is using a KeePassRPC Plugin & Kee Browser extension The Kee browser extension is currently available for Firefox and Chrome, I've also tested it successfully on MS-Edge.
HOWTO:
Install KeePassRPC: It will add a 'Kee' tab in your entries and supplement its properties there:
screenshot of the added 'kee' tab in KeePass
You will find "URLs" within this tab. Add any number of secondary URLs here:
screenshot of the 'Kee'/URL tab with an example filled out
The Kee browser add-in will source these properties and propose to fill in your credentials whenever a primary or secondary URL is matched:
example of an autofilled form at superuser.com
Benefit of the approach is, that the setup will work without regex or technical knowledge on the user side. The Functionally becomes available whenever KeePassRPC + Kee browser extension is installed.


text:
Q: ruby building hash from url In Ruby, what is an efficient way to construct a Hash from a request path like:
/1/resource/23/subresource/34

into a hash that looks like this:
{'1' => { 'resource' => { '23' => 'subresource' => { '34' => {} } } }

Thanks

A: path = "/1/resource/23/subresource/34"
path.scan(/[^\/]+/).inject(hash = {}) { |h,e| h[e] = {} }

hash
=> {"1"=>{"resource"=>{"23"=>{"subresource"=>{"34"=>{}}}}}}

A: A recursive solution seems like the simplest thing to do. This isn't the prettiest, but it works:
def hashify(string)
  k,v = string.gsub(/^\//, '').split('/', 2)
  { k => v.nil? ? {} : hashify(v) }
end

There may be edge cases it doesn't handle correctly (probably are) but it satisfies the example you've given.


text:
Q: css masonry grid transfer border to the next column I have a masonry grid to display products and in some cases the first item's border move to the next column. It doesn't happen always and I can't find the reason for this to happen.
Link to the page:
http://en.naaman.b24online.com/b2c-products/tsb-163746/
Thanks.

A: One solution would be to create a wrapper around each box, so the box with border is inside and cant be breaked

A: OK. I found that the height of row of the pins (defined as #columns) is too short. I added the height for the different screen sizes and it seem to work.
Not sure why the row is not taking it's full height.


text:
Q: SQL join count and select query I have two tables, one is a list of 'gangs' and one is a list of 'gang_members' the gang_members.gang_id refers to the gang.id they are in, I know how to count all the members in one gang, but I need to join the following queries into one:
SELECT * FROM gangs LIMIT 8
SELECT count(gang_id) FROM gangs_members WHERE gang_id = <GANG ID>

I think this is possible, I could do it in a loop while it's going through the gangs but that would be inefficient

A: SELECT A.*, B.RC
FROM gangs A
LEFT JOIN (SELECT gang_id, COUNT(*) AS RC FROM gangs_members GROUP BY gang_id) B ON A.gang_id=B.gang_id

A: Probably something like this
SELECT count(gang_id)
FROM gangs_members
WHERE gang_id IN (SELECT gang_id FROM gangs LIMIT 8)


text:
Q: REST api, GET and timezone as param or header? What would be correct/preferred REST api design to fetch data that depends on timezone?
I was thinking about simply adding timezone as an URL param, so:
$ curl www.api.example.com/data?timezone="Europe/Amsterdam"

But someone suggested to use custom header for that in similar manner like github does:
$ curl -H "X-Time-Zone: Europe/Amsterdam" www.api.example.com/data

https://developer.github.com/v3/#using-the-time-zone-header
I wonder what are benefits of using header here instead of param? Is there any design pattern behind such decision?

A: It's entirely up to you, whether you wish to accept an input parameter in the path, querystring, header, or content body.
However, one could argue that a header makes sense when it is not the primary concern of the api you're calling.  For example, if your api was specifically to retrieve the properties of a time zone, then I would recommend passing it on the url, either on the querystring as you suggested in your question, or on the path (www.api.example.com/timezone/europe/amsterdam).
Also note that the example you gave that uses the parameter in a header is a POST call.  Though it's not prohibited, it usually doesn't make a lot of sense to pass querystring parameters in a POST.  By passing the time zone as a header, the body of the message can focus on what is being posted.


text:
Q: A variational principle for amenable groups Update: If somebody is interested, in Sec. 3, Theorem 3.5, of http://arxiv.org/abs/1203.2301 the variational principle for amenable groups such that every conjugacy class is finite is proved.
Let $G$ be a countable amenable group, $f\in \ell^\infty(G)$. Denote by $L,R$ respectively the set of all right-, left-invariant means. Denote by $P$ the set of all finitely additive probability measures on $G$.
There is some evidence coming from Game Theory that the following conjecture holds:

Conjecture: For all $\lambda\in L$, the functional $\mu\in P\rightarrow\int\int f(xy)d\mu(x)d\lambda(y)$ attains its maximum in some $\rho\in R$.

Notice that this functional is not weak*-continuous, so it is not clear even that the maximum should exist.
Thanks in advance for any help,
Valerio

A: Here I propose a proof showing that the conjecture above holds at least for one left-invariant mean.
Denote by $L$ and $R$ respectively the set of all left-, right-invariant means on $G$. Denote by $P$ the set of all finitely additive probability measures on $G$.
Theorem: There is $\lambda\in L$ such that the functional $\mu\in P\rightarrow\int\int f(xy)d\mu(x)d\lambda(y)$ attains its maximum in some $\rho\in R$.
Proof: By Theorem 3 (and discussion below) of Heath-Sudderth, On a theorem of De Finetti, oddsmaking and game theory, Ann. Math. Stat. (1972), vol. 43, No. 6, 2072-2077, the following equality holds:
$$
\inf_{\nu\in P}\sup_{\mu\in P}\int\int f(xy)d\mu(x)d\nu(y)=\sup_{\mu\in P}\inf_{\nu\in P}\int\int f(xy)d\mu(x)d\nu(y)
$$
Denote by $L$ this common value. Fix $\epsilon_1,\epsilon_2>0$. The RHS tells us that
(1) there is $\mu\in P$ such that $\int f(xy)d\mu(x)\geq L-\epsilon_1$, for all $y\in G$.
The LHS tells us that
(2) there is $\nu\in P$ such that $\sup_{\mu\in P}\int\int f(xy)d\mu(x)d\nu(y)\leq L+\epsilon_2$.
Let $F_n$ be a right-Folner sequence for $G$ and define $\nu_n(A)=\frac{1}{|F_n|}\sum_{g\in F_n}\nu(gA)$. It is straightforward to prove that $\nu_n$ still verifies property 2 and so does any weak* limit, which is a left-invariant mean. Denote by $\nu_{\epsilon_2}$ this left-invariant mean. Now, let $\epsilon_2$ go to zero and let $\lambda$ be any weak*-limit of the net $\nu_{\epsilon_2}$. Hence $\lambda\in L$ and it verifies the following property
(2 bis) $\int\int f(xy)d\mu(x)d\lambda(y)\leq L$, for all $\mu\in P$.
Now, let us get back to property 1, and uniformize $\mu$ as above but using a left-Folner sequence. In this way, any weak*-limit is right-invariant and still verifies property 1. So, we have gotten the following property:
(1 bis) There is $\rho_{\epsilon_1}\in R$ such that $\int f(xy)d\rho_\epsilon(x)\geq L-\varepsilon_1$ (contantly in $y$).
Now, the set of real numbers of the shape $\int f(xy)d\rho(x)$, for some $\rho\in R$, is compact and so, by 1 bis, there is $\rho\in R$ such that $\int f(xy)d\rho(x)=L$. Now, using 2 bis, it follows that our functional, for that particular $\lambda\in L$, attains indeed its maximum in $\rho\in R$, as claimed.


text:
Q: 'talking about' vs 'talk about' I came across the following sentence on the internet:
"When we are talking about possession, relationships, illnesses and characteristics of people or things we can use either have or have got."
Is it correct to say "When we are talking about [...]"?
In my opinion the simple present (to talk about sth.) seems more appropriate.


text:
Q: GIL in Python 3.1 Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration

A: The GIL will not affect your code which does not use python objects. In Numpy, we release the GIL for computational code (linear algebra calls, etc...), and the underlying code can use multithreading freely (in fact, those are generally 3rd party libraries which do not know anything about python)

A: The GIL is a good thing.
Just make your C++ application release the GIL while it is doing its multithreaded work. Python code will continue to run in the other threads, unspoiled. Only acquire the GIL when you have to touch python objects.

A: GIL is still there in CPython 3.1; the Unladen Swallow projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by the time the 2.y version is considered to be done. For now, multiprocessing (instead of threading) remains the way of choice for using multiple cores in CPython (IronPython and Jython are fine too, but they don't support Python 3 currently, nor do they make C++ integration all that easy either;-).

A: Significant changes will occur in the GIL for Python 3.2. Take a look at the What's New for Python 3.2, and the thread that initiated it in the mailing list.
While the changes don't signify the end of the GIL, they herald potentially enormous performance gains.
Update

*

*The general performance gains with the new GIL in 3.2 by Antoine Pitrou were negligible, and instead focused on improving contention issues that arise in certain corner cases.

*An admirable effort by David Beazley was made to implement a scheduler to significantly improve performance when CPU and IO bound threads are mixed, which was unfortunately shot down.

*The Unladen Swallow work was proposed for merging in Python 3.3, but this has been withdrawn due to lack of results in that project. PyPy is now the preferred project and is currently requesting funding to add Python3k support. There's very little chance that PyPy will become the default at present.

Efforts have been made for the last 15 years to remove the GIL from CPython but for the foreseeable future it is here to stay.

A: I guess there will always be a GIL.
The reason is performance. Making all the low level access thread safe - means putting a mutex around each hash operation etc. is heavy. Remember that a simple statement like
self.foo(self.bar, 3, val)

Might already have at least 3 (if val is a global) hashtable lookups at the moment and maybe even much more if the method cache is not hot (depending on the inheritance depth of the class)
It's expensive - that's why Java dropped the idea and introduced hashtables which do not use a monitor call to get rid of its "Java Is Slow" trademark.

A: As I understand it the "brainfuck" scheduler will replace the GIL from python 3.2
BFS bainfuck scheduler

A: If the GIL is getting in the way, just use the multiprocessing module. It spawns new processes but uses the threading model and (most of the) api. In other words, you can do process-based parallelism in a thread-like way.


text:
Q: Is it possible to add custom shipping address in order email templates in custom module OrderSender.php
Here i want to add custom shipping address in order Email templates
  programmatically using
  magento/module-sales/Model/Order/Email/Sender/OrderSender.php i.e.
  overriding this file in custom module.If Anyone have idea please guide
  me.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Sales\Model\Order\Email\Sender;

use Magento\Payment\Helper\Data as PaymentHelper;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Email\Container\OrderIdentity;
use Magento\Sales\Model\Order\Email\Container\Template;
use Magento\Sales\Model\Order\Email\Sender;
use Magento\Sales\Model\ResourceModel\Order as OrderResource;
use Magento\Sales\Model\Order\Address\Renderer;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\DataObject;

/**
 * Class OrderSender
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class OrderSender extends Sender
{
    /**
     * @var PaymentHelper
     */
    protected $paymentHelper;

    /**
     * @var OrderResource
     */
    protected $orderResource;

    /**
     * Global configuration storage.
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $globalConfig;

    /**
     * @var Renderer
     */
    protected $addressRenderer;

    /**
     * Application Event Dispatcher
     *
     * @var ManagerInterface
     */
    protected $eventManager;

    /**
     * @param Template $templateContainer
     * @param OrderIdentity $identityContainer
     * @param Order\Email\SenderBuilderFactory $senderBuilderFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param PaymentHelper $paymentHelper
     * @param OrderResource $orderResource
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $globalConfig
     * @param Renderer $addressRenderer
     * @param ManagerInterface $eventManager
     */
    public function __construct(
        Template $templateContainer,
        OrderIdentity $identityContainer,
        \Magento\Sales\Model\Order\Email\SenderBuilderFactory $senderBuilderFactory,
        \Psr\Log\LoggerInterface $logger,
        Renderer $addressRenderer,
        PaymentHelper $paymentHelper,
        OrderResource $orderResource,
        \Magento\Framework\App\Config\ScopeConfigInterface $globalConfig,
        ManagerInterface $eventManager
    ) {
        parent::__construct($templateContainer, $identityContainer, $senderBuilderFactory, $logger, $addressRenderer);
        $this->paymentHelper = $paymentHelper;
        $this->orderResource = $orderResource;
        $this->globalConfig = $globalConfig;
        $this->addressRenderer = $addressRenderer;
        $this->eventManager = $eventManager;
    }

    /**
     * Sends order email to the customer.
     *
     * Email will be sent immediately in two cases:
     *
     * - if asynchronous email sending is disabled in global settings
     * - if $forceSyncMode parameter is set to TRUE
     *
     * Otherwise, email will be sent later during running of
     * corresponding cron job.
     *
     * @param Order $order
     * @param bool $forceSyncMode
     * @return bool
     */
    public function send(Order $order, $forceSyncMode = false)
    {
        $order->setSendEmail(true);

        if (!$this->globalConfig->getValue('sales_email/general/async_sending') || $forceSyncMode) {
            if ($this->checkAndSend($order)) {
                $order->setEmailSent(true);
                $this->orderResource->saveAttribute($order, ['send_email', 'email_sent']);
                return true;
            }
        } else {
            $order->setEmailSent(null);
            $this->orderResource->saveAttribute($order, 'email_sent');
        }

        $this->orderResource->saveAttribute($order, 'send_email');

        return false;
    }

    /**
     * Prepare email template with variables
     *
     * @param Order $order
     * @return void
     */
    protected function prepareTemplate(Order $order)
    {
        $transport = [
            'order' => $order,
            'billing' => $order->getBillingAddress(),
            'payment_html' => $this->getPaymentHtml($order),
            'store' => $order->getStore(),
            'formattedShippingAddress' => $this->getFormattedShippingAddress($order),
            'formattedBillingAddress' => $this->getFormattedBillingAddress($order),
        ];
        $transportObject = new DataObject($transport);

        /**
         * Event argument `transport` is @deprecated. Use `transportObject` instead.
         */
        $this->eventManager->dispatch(
            'email_order_set_template_vars_before',
            ['sender' => $this, 'transport' => $transportObject, 'transportObject' => $transportObject]
        );

        $this->templateContainer->setTemplateVars($transportObject->getData());

        parent::prepareTemplate($order);
    }

    /**
     * Get payment info block as html
     *
     * @param Order $order
     * @return string
     */
    protected function getPaymentHtml(Order $order)
    {
        return $this->paymentHelper->getInfoBlockHtml(
            $order->getPayment(),
            $this->identityContainer->getStore()->getStoreId()
        );
    }
}


text:
Q: Listview upload control I have a listview which has insert capabilities, one of the fields is an image field, how can I add an upload control to upload an image and store the file path, into the the database.
Alternatively I could have the file upload outside of the layout control then update the textbox in the layout with the file path.
Thanks

A: Just put the FileUpload control into the ItemTemplate of your ListView.  Then you need to handle the appropriate event and use the FileUploadControl.FileName value to save the path to the DB.


text:
Q: Pods don't communicate between each other when on different nodes (EKS) we have an EKS cluster with 4 nodes and 10 microservices (at this moment) on it. We used to have 2 nodes and didn't see much problems, but since increasing to 4, things have "randomly" stopped working. I believe that the pod of a node can not talk to another node of the cluster.
We have randomly "service unavailable" when the pods are not on the same node. When on the same node, it's all good. We use http://service.namespace:port in appsettings.
I thought Kubernetes would resolve this automatically? We have an EKS v1.12. Thanks
PS: We tried to "telnet IP port" and it worked from one of the pod. When we do http://service.namespace:port, it doesn't resolve.

A: If the services are in the same namespace you can use http://servicename:port
If they are in different namespaces then you can use FQDN http://servicename.namespace.svc.cluster.local:port


text:
Q: How to return the replicated data instead of boolean in laravel I'm trying to replicate() eloquent data in laravel, and also return the replicated data instead of bool() data.
When I do this
$transaction = Transaction::find(1);

$transaction2 = $transaction->replicate()->fill(['status' => 1]);

$transaction2 = $transaction2->save();

return $transaction2;

This code returns true. How can I return the replicated data?

A: The result is happening because you are setting the $transaction2 to the save() result just before your return here $transaction2 = $transaction2->save();.
This will override $transaction2 with the value of ->save(), which returns true or false whether it successfully saved or not.
Change your code like this, and it will do as you intend.
$transaction = Transaction::find(1);

$transaction2 = $transaction->replicate()->fill(['status' => 1]);

$transaction2->save();

return $transaction2;


text:
Q: Change Ribbon tab text I need to change the Document Library ribbon tab. I tried to change the text using javascript in master page. But it changes on first load only. When ribbon tab is clicked, text againi changed to default value. Please suggest any idea.
Is it possible to change the content inside upload page? When i click on Add Document link, upload page is loaded. I need to customize the contents.


text:
Q: Using anonymous runnable class code goes in deadlock state but with lambda it works fine I am trying to find out the cause behind below mentioned code. Here if I create Thread using anonymous inner class it goes into deadlock state but with lambda expressions it works fine. I tried to find the reason behind this behavior but I could not.
public class ThreadCreationTest {

    static {
        new ThreadCreationTest();
    }

    private void call() {
        System.out.println("Hello guys!!!");
    }

    public ThreadCreationTest() {

        // when we use this thread it goes in deadlock kind of state
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                call();
            }
        });

        // This one works fine.
        Thread thread = new Thread(() -> call());

        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String... args) {
        System.out.println("Code finished...");
    }
}

with lambda expression output :
Hello guys!!!
Code finished...

with anonymous class :
code goes into deadlock state

A: Decompiling with javap the inner class shows the following for the run method:
public void run();
  descriptor: ()V
  flags: ACC_PUBLIC
  Code:
    stack=1, locals=1, args_size=1
       0: aload_0
       1: getfield      #12                 // Field this$0:Ltest/ThreadCreationTest;
       4: invokestatic  #22                 // Method test/ThreadCreationTest.access$0:(Ltest/ThreadCreationTest;)V
       7: return
    LineNumberTable:
      line 31: 0
      line 32: 7
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0       8     0  this   Ltest/ThreadCreationTest$1;

Notice that there is a static synthetic method access$0 which in turn calls the private method call. The synthetic method is created because call is private and as far as the JVM is concerned, the inner class is just a different class (compiled as ThreadCreationTest$1), which cannot access call.
static void access$0(test.ThreadCreationTest);
  descriptor: (Ltest/ThreadCreationTest;)V
  flags: ACC_STATIC, ACC_SYNTHETIC
  Code:
    stack=1, locals=1, args_size=1
       0: aload_0
       1: invokespecial #68                 // Method call:()V
       4: return
    LineNumberTable:
      line 51: 0
    LocalVariableTable:
      Start  Length  Slot  Name   Signature

Since the synthetic method is static, it is waiting for the static initializer to finish. However, the static initializer is waiting for the thread to finish, hence causing a deadlock.
On the other hand, the lambda version does not rely on an inner class. The bytecode of the constructor relies on an invokedynamic instruction (instruction #9) using MethodHandles:
public test.ThreadCreationTest();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=3, locals=3, args_size=1
         0: aload_0
         1: invokespecial #13                 // Method java/lang/Object."<init>":()V
         4: new           #14                 // class java/lang/Thread
         7: dup
         8: aload_0
         9: invokedynamic #19,  0             // InvokeDynamic #0:run:(Ltest/ThreadCreationTest;)Ljava/lang/Runnable;
        14: invokespecial #20                 // Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
        17: astore_1
        18: aload_1
        19: invokevirtual #23                 // Method java/lang/Thread.start:()V
        22: aload_1
        23: invokevirtual #26                 // Method java/lang/Thread.join:()V
        26: goto          36
        29: astore_2
        30: invokestatic  #29                 // Method java/lang/Thread.currentThread:()Ljava/lang/Thread;
        33: invokevirtual #33                 // Method java/lang/Thread.interrupt:()V
        36: return


text:
Q: "DPInst.exe not supported on current OS" I have an installer that installs the USB serial drivers from FTDI. However on some computers (all of them running Russian Windows XP so it may be some language issue) the installation fails. I have tried to repeat it using a clean Russian Windows XP Professional SP3, but there it works so it's not a clear cut language issue.
The dpinst.log file says:
`INFO:   04/18/2013 14:05:34
INFO:   Product Version 2.1.0.0.
INFO:   Version: 6.1.7601 Service Pack 1
INFO:   Platform ID: 2 (NT)
INFO:   Service Pack: 1.0
INFO:   Suite: 0x0100, Product Type: 1
INFO:   Architecture: X86.
INFO:   Interactive Windows Station
INFO:   Command Line: '"D:\Something\DPInst32.exe" '
INFO:   DPInst is a multi-lingual binary.
INFO:   ****************************************
INFO:   Current working directory: 'D:\Something\Drivers'
INFO:   Running on path 'D:\Something\Drivers'
INFO:   No valid 'dpinst.xml' file provided.
ERROR:  DPInst.exe not supported on current OS.
INFO:   Returning with code 0x80000000`
It is correct that I don't use a dpinst.xml file, but that should not be necessary. Or?
In the installer I run dpinst (32 or 64 depending on OS) with the switches /c /q /sa /sw but it's probably irrelevant since double clicking dpinst32.exe also gives an error. The dpinst version is 2.1

A: I have faced the same issue on Russion Win7x64 (the package was working perfectly on English Win7x64).
There are two versions of DPInst in WDK (redist\DIFx\DPInst folder): English (EngMui subfolder) and multilanguage (MultiLin subfolder). suddenly, it seems that the multilanguage version has problems with localized Windows.
I've replaced my original multilanguage DPInst.exe with the English one, and it solved the problem. English version was working fine on Russian Windows.


text:
Q: Microservices - What is the exact difference between service discovery and Service Gateway? I read the articles like : What is the difference between an API-Gateway and an Edge Service?, but still not clear on what's the exact difference between the service discovery (say Eureka) and Service Gateway (Zuul) ? Any pointers?

A: The differences is more understandable if you focus in responsabilities of both Zuul and Eureka. As you can see below each one has specific tasks. Thats the main differences.

A: The Services gateway (a.k.a. API gateway) is receiving requests from the clients. It is the (single) service that the clients see. But it doesn't know by itself how to do what the clients want so it must forward the request to another service. It inspects the URL and extracts the name of the service that will actually serve the request, the backend service. That backend service may be located on a different machine. It may have a dynamic address or port, that may change from time to time, from different reasons (nodes fail, new nodes are added to the network etc).
So, the gateway doesn't know where to forward the request. This is the job of the Service-discovery service (Eureka). Eureka knows on which node is located and at which address and port every service is listening for requests. The gateway is asking Eureka where it can find the backend service (by sending it only its name). After Eureka is responding, the gateway is forwarding the request to that address.

A: API Gateway
In Api Gateway we have to register services with its URL and matching patterns
like this:
 id: order-service
    uri: http://localhost:9003/
    predicates:
      - Path=/order/**

But the problem here is we can have multiple instances on different ports. Like this
 uri: http://localhost:9003/
 uri: http://localhost:9004/
 uri: http://localhost:9005/

In this case, a gateway will fail to route to other instances.
Service Discovery
In case of service discovery, we will have to register client services to service discovery (which is another service). Like this
 eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
     defaultZone: http://localhost:8761/eureka/

Now all clients will register to service discovery automatically so even if there are multiple instances service register will take care of it.

A: Service Gateway operates at Network layer 7 (HTTP) and Service discovery operates at Network Layer 4 to be precise.
Zuul works at Layer 7 and Eureka works at Layer 4
Please refer to Kong Gateway which provides a uniform solution


text:
Q: Reusing activerecord scopes on has many through associations Say I have a few activerecord models in my rails 3.1 project that look like this:
class Component < ActiveRecord::Base
    has_many :bugs
end

class Bug < ActiveRecord::Base
    belongs_to :component
    belongs_to :project

    scope :open, where(:open => true)
    scope :closed, where(:open => false)
end

class Project < ActiveRecord::Base
    has_many :bugs
    has_many :components_with_bugs, :through => :bugs, :conditions => ["bugs.open = ?", true]
end

In Short: I have a has_many through association (components_with_bugs) where I want to scope the "through" model. At present I'm doing this by duplicating the code for the scope.
Is there any way to define this has many through association (components_with_bugs) such that I can reuse the Bug.open scope on the through model, while still loading the components in a single database query? (I'm imagining something like :conditions => Bug.open)

A: Rails 4 answer
Given you have:
class Component < ActiveRecord::Base
  has_many :bugs
end

class Bug < ActiveRecord::Base
  belongs_to :component
  belongs_to :project

  scope :open,   ->{ where( open: true) }
  scope :closed, ->{ where( open: false) }
end

You have two possibilities:
class Project < ActiveRecord::Base
  has_many :bugs

  # you can use an explicitly named scope
  has_many :components_with_bugs, -> { merge( Bug.open ) }, through: :bugs, source: 'component'

  # or you can define an association extension method
  has_many :components, through: :bugs do
    def with_open_bugs
      merge( Bug.open )
    end
  end
end

Calling projet.components_with_bugs or project.components.with_open_bugs will fire the same sql query:
SELECT "components".* FROM "components"
INNER JOIN "bugs" ON "components"."id" = "bugs"."component_id"
WHERE "bugs"."project_id" = ? AND "bugs"."open" = 't'  [["project_id", 1]]

Which one is better to use depends on your application. But if you need to use many scopes on the same association, I guess association extensions could be clearer.
The real magic is done with merge which allows you to, as the name says, merge conditions of another ActiveRecord::Relation. In this case, it is responsible for adding AND "bugs"."open" = 't' in the sql query.

A: The http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html specifies

:conditions Specify the conditions that the associated object must meet in order to be included as a WHERE SQL fragment, such as authorized = 1.

Hence you can do it as:
class Project < ActiveRecord::Base
  has_many :bugs
  has_many :components_with_bugs, :through => :bugs do
    def open
      where("bugs.open = ?", true)
    end
  end
end

EDIT:
You can't specify another model's scope as a condition. In your case, they way you have it implemented is right. You can implement it another way as
has_many :components_with_bugs, :through => :bugs # in this case, no need to use the relation.

def open_bugs
  self.bugs.openn # openn is the scope in bug. Don't use name 'open'. It's a private method of Array.
end

A: Apart from your scopes , write the default scope as:
default_scope where(:open => true) in your "through" model Bug.
class Bug < ActiveRecord::Base
      belongs_to :component
      belongs_to :project
      default_scope where(:open => true)
      scope :open, where(:open => true)
      scope :closed, where(:open => false)
end

And in the Project model remove :conditions => ["bugs.open = ?", true]
class Project < ActiveRecord::Base
      has_many :bugs
      has_many :components_with_bugs, :through => :bugs
end
I think the above will work for you.

A: Try using the following.
has_many :components_with_bugs, :through => :bugs do
      Bug.open
end

A: Can't you use something like this ?
has_many :components_with_bugs, :through => :bugs, :conditions => Bug.open.where_values

I haven't tested it, just proposing an path for investigation


text:
Q: Prob. 9, Sec. 3.9 in Erwin Kreyszig's INTRODUCTORY FUNCTIONAL ANALYSIS WITH APPLICATIONS: Finite-dimensional range and the form of images Let $H$ be a Hilbert space, and let $T \colon H \to H$ be a bounded linear operator. Then how to show the following?
The range of $T$ is finite-dimensional if and only if $T$ can be represented in the form
$$Tx = \sum_{j=1}^n \langle x, v_j \rangle w_j \ \ \ [ v_j, w_j \in H].$$
My effort:
Supppose that $\dim \mathscr{R}(T) = n$, and let $\{ e_1, \ldots, e_n \}$ be an orthonormal basis for $\mathscr{R}(T)$. Then, for every $x \in H$, we have
$$Tx = \sum_{j=1}^n \langle Tx, e_j \rangle e_j = \sum_{j=1}^n \langle x, T^* e_j \rangle e_j,$$
where $T^*$ denotes the Hilbert adjoint operator of $T$. So we can take $w_j \colon= e_j$ and $v_j \colon= T^* e_j$.
Is this reasoning correct?
If so, then how to show the converse? Doest the above representation mean that the same $v_j$s and $w_j$s will be used for every $x \in H$? If so, then range of $T$ is spanned by the finitely many elements $w_1, \ldots, w_n$ and is clearly finite-dimensional.

A: The reasoning is correct. For the second one: yes, the same $v_i$'s and $w_i$'s will be used for any $x$, and as you pointed out this means that $\Im(T)$ is spanned by the $w_i$'s.

A: The reasonning seems correct to me. Note that the adjoint $T^*$ is well defined and independant of $x$. Thus the vectors $v_j, w_j$ that you find are well defined and do not depend on the $x$ you choose.
Thus for the second part, it suffices to observe that the range is finite dimensional because it is spanned by a finite number of vectors (that do not depend upon $x$, otherwise the result would be empty).


text:
Q: Instabot Posts Images but Not Captions I'm building a bot that fetches images from the Unsplash API, and then reposts them on Instagram. Each image comes with a caption that is generated using the function getQuote(). The issue I am facing is that the captions do not get uploaded. I have tried isolating the problem by putting simple string instead of getting the data from a function, but to no avail, as Instabot does not post the caption on Instagram.
Below is the upload function:
def upload(path):
bot.upload_photo(path, caption="Follow for more!")
toast.show_toast("Notification",str(num)+" images are uploaded",duration=300,threaded=True)
print(str(num)+" images are uploaded")
print("----------------------------------")
try:
    os.remove(os.path.join(os.getcwd(), path+""))
except:
    os.remove(os.path.join(os.getcwd(), path+".REMOVE_ME"))

The last 4 lines delete the already uploaded images.
In an ideal scenario the bot.upload would have a caption=getQuote()
Yesterday, while testing how fast the bot can upload(the captions worked back then), Instagram cut my access, but today I can still upload images, but without captions. Going on Instagram and manually changing captions is possible, so I doubt some server-side ban. If I just create a print statement calling the function getQuote - I get an adequate response, which means that the quotes are successfully loaded from the quotes.json file.
Below is my entire code:
    from instabot import Bot
    from skimage.io import imread_collection
    from glob import glob
    from win10toast import ToastNotifier
    import random
    import json
    import os
    import urllib.request
    import time
    import requests
    import smtplib
    import smtplib
    from tkinter import *
    from fake_useragent import UserAgent
    ua = UserAgent()

    num=0
    window = Tk()
    window.title("Photos Uploaded")
    window.iconbitmap("Instagram/Instagram.ico")
    lbl = Label(window, text=num, font=("Arial Bold", 100))
    lbl.grid(column=0, row=0)
    window.update()
    #This functions checks if the site is up
    def url_ok(url):
        r = requests.head(url)
        return r.status_code == 200

    #Below functions sends emails
    def sendMessage(Num):
        gmail_user = ''
        gmail_password = ''
        sent_from = gmail_user
        to = ['']
        subject = 'Upload Count'
        body = "Upload Count"
        email_text = Num
        try:
            server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            server.ehlo()
            server.login(gmail_user, gmail_password)
            server.sendmail(sent_from, to, email_text)
            server.close()
        except:
            print("Could not send a push-notification!")

    with open("Instagram/NumberOfImagesUploaded.txt", "r") as f:
       num = int(float(f.read()))
    #This functions loads the number of already uploaded images from a file
    def ChangeNum(n):
        num=n
        with open("Instagram/NumberOfImagesUploaded.txt", "w") as f:
            f.write(str(int(n)))

    links=[]
    r=''
    with open(os.path.abspath("Instagram/Data/links.txt"), 'r') as filehandle:
        for line in filehandle:
            currentPlace = line[:-1]
            links.append(currentPlace)
    print("Started at: " +time.ctime()+" with a list of "+str(len(links))+" links.")
#This functions gets images from the API
def GetImage():
        r = requests.get('https://source.unsplash.com/featured/3840x2160')
        while r.url == "https://images.unsplash.com/source-404?fit=crop&fm=jpg&h=800&q=60&w=1200":
            print("API requests are over capita! Waiting one hour. Continuing at "+str(time.ctime(time.time() + 3600)+"..."))
            time.sleep(3600)
            print("Trying again... "+time.ctime())
            r = requests.get('https://source.unsplash.com/featured/3840x2160')
        try:
            urllib.request.urlretrieve(str(r.url), os.path.abspath("Instagram/media")+"\\"+str(random.randrange(1,10000))+".jpg")
        except:
            print("API requests are over capita! Waiting in 10 hours. Continuing at "+str(time.ctime(time.time() + 36000)+"..."))
            time.sleep(36000)
            urllib.request.urlretrieve(str(r.url), os.path.abspath("Instagram/media")+"\\"+str(random.randrange(1,10000))+".jpg")
        while r.url in links:
            r = requests.get('https://source.unsplash.com/featured/3840x2160')

        links.append(r.url)
        with open(os.path.abspath("Instagram/Data/links.txt"), 'w') as filehandle:
            for listitem in links:
                filehandle.write('%s\n' % listitem)
    GetImage()
    print("Backup image loaded at: " +time.ctime())
    toast = ToastNotifier()
    col_dir =os.path.abspath("Instagram/media")+"\\"+("*.jpg")
    col = glob(col_dir)
    print(col_dir)
    with open(os.path.abspath("Instagram/Data/quotes.json")) as f:
      data = json.load(f)

    def getQuote():
        quote = random.choice(data)
        return ('"'+quote['text']+'" - '+quote['author']+" \n\n Follow us for more! \n \n #photography #travelphotography #naturephotography #streetphotography #foodphotography #portraitphotography #photographylovers #landscapephotography #weddingphotography #blackandwhitephotography #filmphotography #canonphotography #fashionphotography #mobilephotography #photographyislife #nikonphotography #photographyeveryday #photographylover #photographysouls #architecturephotography #photographyislifee #wildlifephotography #nightphotography #iphonephotography #macrophotography #urbanphotography #bnwphotography #analogphotography #dogphotography #photographylife")
    print(getQuote())
    bot = Bot()
    bot.login(username = "",  password = "")
    def upload(path):
        bot.upload_photo(path, caption="Follow for more!")
        toast.show_toast("Notification",str(num)+" images are uploaded",duration=300,threaded=True)
        print(str(num)+" images are uploaded")
        print("----------------------------------")
        try:
            os.remove(os.path.join(os.getcwd(), path+""))
        except:
            os.remove(os.path.join(os.getcwd(), path+".REMOVE_ME"))
    while True:
        GetImage()
        col = glob(col_dir)
        ranTime=random.randrange(1800,3600)
        print("Images in stack: "+str(col))
        print("Waiting 30 to 60 minutes. Resuming at "+str(time.ctime(time.time() + ranTime)))
        #time.sleep(ranTime)
        print("Upload sequence has begun...")
        lbl.configure(text=num)
        window.update()
        if num % 50 == 0:
            sendMessage(str(num)+" images uploaded.")
        for i in col:
            num+=1
            lbl.configure(text=num)
            window.update()
            ChangeNum(num)
            upload(i)
            imageDir = os.listdir(os.getcwd())
            for item in imageDir:
                if item.endswith(".REMOVE_ME"):
                    os.remove(os.path.join(os.getcwd(), item))

Here is an image of my file structure

How to make the bot start uploading the images with captions?

A: For starters, it's important to know the limits on Instagram captions! The maximum caption length is 2,200 characters (which is pretty darn long!). You can also use up to 30 hashtags. So just satisfy 2 criteria's:

*

*Caption length should be less than 2200 characters

*Caption should have less than 30 hashtags


text:
Q: how to pass byte[] parameter using json to wcf data services I have one Data Service.Using Json how can pass byte[] parameter to the one of the method in Data Services?

A: As per http://www.odata.org/developers/protocols/json-format, JSON uses literal forms of EDM types.  The EDM type is Edm.Binary, with literal form binary'...'


text:
Q: Most appropriate way to redirect page after successful POST request in Django I have build a view and a form in Django1.5. If the POST request is successful (based on some values I set) then I need the page to redirect to another URL which is created simultaneously.
Otherwise, if the POST was not successful I need to stay on the same page. Right now I have solved the problem as following but I am quite sure this is not the best way to do it:
This is a part of my view:
def layer_create(request, template='layers/layer_create.html'):
    if request.method == 'GET':
       ....
    elif request.method == 'POST':
       out = {}
       ...
       new_table = 'something that comes from the form'
       if form.is_valid():
         ...
         try:
           ...
           out['success'] = True
         except:
           ...
           out['success'] = False
         finally:
           if out['success']:
            status_code = 200
             # THIS IS THE PART WHICH I THINK I CAN IMPROVE
            template = '/something/workspace:' + new_table + '/metadata'

       else: # if form not valid
         out['success'] = False
        return render_to_response(template, RequestContext(request, {'form': form}))

This part of the code:
    template = '/something/workspace:' + new_table + '/metadata'

seems very ugly to me. But as I am quite new in Django I am not sure how to approach this matter.

A: A side note first about Django 1.5 - you're highly advised to upgrade to a supported version like 1.8.
Redirecting
For redirecting you can use the redirect shortcut. (Or HttpResponseRedirect)
from django.shortcuts import redirect
# out of a view context
return redirect('/url/to/redirect/to/')

Building URLs
Indeed - as you did mention, your attempt with template = '/something/workspace:' + new_table + '/metadata' is not the cleanest way :)
Django provides a really nice way with the URL dispatcher.
A complete solution here would go too far (or definitely would require more detailed information about your project structure) - I would recommend you to dive into the Django URL dispatcher.
In short you would do something like:
# app/urls.py
urlpatterns = [
    #...
    url(r'^workspace/(?P<id>[0-9]+)/metadata/$', views.workspace_detail, name='workspace-detail-metadata'),
    #...
]

Then you are able to reverse your URL patterns:
from django.core.urlresolvers import reverse
url = reverse('workspace-detail-metadata', kwargs={'id': 123})
# would result in:
# .../workspace/123/metadata/

A: After all, I have used the "reverse" method as follows:
layer = 'geonode:' + new_table
return HttpResponseRedirect(
   reverse(
       'layer_metadata',
        args=(
             layer,
         )))

Where my urls.py file includes:
url(r'^(?P<layername>[^/]*)/metadata$', 'layer_metadata', name="layer_metadata"),

As described here this is the most appropriate way to do it.


text:
Q: How to parse the sentence: " I'm the same person I was before I made the series that I am now. " The sentence is from the VOA Learning English Program:

"Well actually, the fame is there -- it just takes a different form. I
  mean, you know, you, you think of our show being prime time, but when
  I come out here and I meet people, they're just as excited as I was
  during Batman days. So, it's not that the people change. Maybe, you
  know, the, the perception is different, but it, honestly, nothing has
  changed – I'm the same person I was before I made the series that I am
  now."

My understanding is :
I am the same person that I was before I made the series and I am the same person that I am now.
How to parse this sentence ?

A: The sentence is talking about one person, but speaking of that person as if it were two people.
A sentence similar to this one is often heard when talking about someone who entered into sudden riches; for example:

I am the same person now as I was before I won the lottery.

That's a way of saying, "Money hasn't changed me," or "Money hasn't changed who I am."
In contrast, we have this one:

I am not the same person I was before I went to prison that I am now.

This time, the speaker is saying that he has changed in some way (for the better, we hope).
Now, back to your sentence:

I'm the same person I was before I made the series that I am now.

The meaning might be a little clearer if it were written as:

I'm the same person now as I was before I made the series.

The following isn't a true "parsing," but it may help you parse the original sentence:

The (person I was before I made the series) and (the person I am now) are the same person.

A: The sentence is ungrammatical. Or rather, it is grammatical but with semantics that is nosense.  These two are grammatical and sound:

I was same person that I am now.
I am the same person (that) I was before I made the series.

In the sentence being considered, the complementized clause "that I am now" is dangling. It looks like "the series that I am now" which is grammatical, but semantically, it is nonsense.
A way to change the sentence so that it incorporates "that I am now" and has sound semantics is as follows:

The person that I am now is the same person that I was before I made the series.

An example of a semantically sound sentence which is closely parallel to yours, in terms of syntax, but with a different meaning, is this:

I am quite a different person from what I was before I created the person that I am now.

This works because "the person that I am now" is sensible, unlike "the series that I am now".


text:
Q: Knockout/Select2: Triggering select2 to update based on an observable option updating When upgrading from Knockout.js 2.x to 3.x, I've noticed this not working: I have a screen where I have a <select> depending on an observable array of observables, and I wrap the <select> with a Select2 wrapper.
Now, it used to be that when one of the option observables was updated, the select would update. And that is still the case. But I can't get the Select2 binding to update properly at the same time.
I'm using the binding handlers recommended by the Select2 Github page:
ko.bindingHandlers["select2"] = {
    after: ["options", "value", "selectedOptions"],
    init: function (element, valueAccessor) {
        $(element).select2(ko.unwrap(valueAccessor()));

        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).select2("destroy");
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        //trying various methods to register interest with dependency checking
        //var allBindings = allBindingsAccessor();
        //if (allBindings.options) { allBindings.options(); }
        //if (allBindings.value) { allBindings.value(); }
        //if (allBindings.selectedOptions) { allBindings.selectedOptions(); }
        $(element).trigger("change");
    }
};
(function () {
    var updateOptions = ko.bindingHandlers["options"]["update"];
    ko.bindingHandlers["options"]["update"] = function (element) {
        var ret = updateOptions.apply(null, arguments);
        var $el = $(element);
        if ($el.data("select2")) { $el.trigger("change"); }
        return ret;
    }
})();
(function () {
    var updateSelectedOptions = ko.bindingHandlers["selectedOptions"]["update"];
    ko.bindingHandlers["selectedOptions"]["update"] = function (element) {
        var ret = updateSelectedOptions.apply(null, arguments);
        var $el = $(element);
        if ($el.data("select2")) { $el.trigger("change"); }
        return ret;
    }
})();

Below is an example. You'll notice that when you change the value of one of the inputs that represent the items in the select, it doesn't update the Select2 to match (but it does update the backing select).
http://jsfiddle.net/mrmills/MfttX/1/

A: It seems to work fine when you add the optionsValue: 'choice':
<select data-bind="options: choices,
                   optionsText: 'choice',
                   optionsValue: 'choice',
                   select2: {}"></select>

See fiddle