text:
Q: Derivative of Lagrangian with respect to velocity My question revolves around this lecture notes on page $109$ equation $(5.1.10)$.
Let's stick to $\mathbb{R}^3$ and consider  a particle in $3$-space with position vector $\mathbf{x} = (x, y, z)$. Denote its velocity by $\mathbf{v} = \dot{\mathbf{x}} = (\dot{x}, \dot{y}, \dot{z}).$
Basically, we have the Lagrangian describing the particle:
\begin{equation}
L = -mc^2 \sqrt{1 - \frac{v^2}{c^2}},
\end{equation}
where $m$ is the mass of the particle, $c$ is the speed of light constant and $v = |\mathbf{v}| = \sqrt{\dot{x}^2 + \dot{y}^2 + \dot{z}^2}$ is the speed of the particle. Then the author derived in the notes:
\begin{equation}
\frac{\partial L}{\partial \mathbf{v}} = -mc^2\left(-\frac{\mathbf{v}}{c^2}\right)\frac{1}{\sqrt{1 - v^2/c^2}} = \frac{m \mathbf{v}}{\sqrt{1 - v^2/c^2}}.
\end{equation}
My question is, how did the author get the first equality in the derivation?
I know that I can just do it by computing this:
\begin{equation}
\frac{\partial L}{\partial \mathbf{v}} = \left(\frac{\partial L}{\partial \dot{x}}, \frac{\partial L}{\partial \dot{y}}, \frac{\partial L}{\partial \dot{z}}\right).
\end{equation}
But my question is more specific: how did the author get the first equality that fast? Is there a trick I'm missing here?

A: Component-wise, $\boldsymbol{p}=\partial L/\partial \boldsymbol{v}$ means $p_i=\partial L/\partial v_i$ for $i=1,2,3$. Then e.g.
\begin{equation}
\frac{\partial L}{\partial v_1} = \cdots = \gamma mv_1\,,
\end{equation}
yields the first momentum component. Notice that the differentiation is exactly the same for $i=2,3$. So you can imagine taking a shortcut by doing all three derivatives at the same time: write $v^2\rightarrow \boldsymbol{v}^2$, then perform the derivative w.r.t. $\boldsymbol{v}$ like it's a scalar.

A: Use the chain rule and the fact that $v^2 = \mathbf v\cdot\mathbf v$ whence
$$\frac{\partial v^2}{\partial\mathbf v} = 2 \mathbf v.$$


text:
Q: Unable to get a factorial function to work in C I cannot get the following code to work.
#include <stdio.h>

// I am not sure whethere I should void here or not.
int main() {
    // when the first bug is solved, I put here arg[0]. It should be
    // similar command line parameter as args[0] in Java.
    int a=3;
    int b;
    b = factorial(a);

    // bug seems to be here, since the %1i seems to work only in fprintf
    printf("%1i", b);
    return 0;
}

int factorial(int x) {
    int i;
    for(i=1; i<x; i++)
        x *= i;
    return x;
}

How can you get the code to work?

A: AInitak gave the right answer, but I want to add that one way you can find the bug in your code is to print out the values of i and x in the factorial loop.
int factorial(int x) {
    int i;
    for(i=1; i<x; i++)
    {
        x *= i;
        printf("%d, %d\n", i, x);
    }
    return x;
}

This gives you the output
1, 3
2, 6
3, 18
4, 72
5, 360
6, 2160
7, 15120
8, 120960
9, 1088640
10, 10886400
11, 119750400
12, 1437004800
13, 1501193216
14, -458131456
-458131456

This makes it easier to see what's going wrong.  The loop doesn't stop where you expect it to for the reasons AInitak explained.

A: It's bad style in C to leave out void when defining or declaring a function. So put it in
int main(void)

While it doesn't change anything about the number of parameters the function has (the function has zero parameters without that void either), it will declare the function as one that accepts only zero arguments, while it won't tell anything about the amount and types of accepted arguments when you omit the void. However, both versions with and without void are correct.
Read this answer about that matter too.

A: #include<stdio.h>

#include<stdlib.h>

int main(int c,char *v[])

{

    int x,y;

    int *num;

    if(c==1)

    {

    printf("Usage : programName : number");

    return 0;

    }

    num=(int *)malloc(sizeof(int));

    *num=atoi(v[1]);

    x=1;y=1;

    while(x<=*num)

    {

    y=y*x;

    x++;

    }

    printf("Factorial of %d is %d ",*num,y);

    free(num);

    return 0;

}

A: You're modifying your loop terminating variable (x) inside the loop.  Currently your code blows up after a few iterations, when x overflows the range of a 32 bit integer and then becomes negative and very large, hence terminating the loop.
It should be:
int factorial(int n) {
    int i, x = 1;
    for (i = 2; i <= n; ++i) {
        x *= i;
    }
    return x;
}

Better yet, you should use long instead of int for the variable x and the return value, because n! gets very large very quickly.

A: What error message do you get?
First off, declare your function factorial before main. Also, pay attention to correct indentation. Your declaration of function main is correct, by the way.

A: I would suggest to use also double or unsigned long for factorial computation in order to be able to compute the greater value of the factorial function.
double fact( double n)
{
   if ( n == 1)
        return 1;
   return n*(fact(n-1));
}

A: A more elegant non-recursive function.
#include<stdio.h>
long long int fact(long long int);

long long int fact(long long int n){
    long long int num = 1;
    long long int fi = 0;
    for(long long int i=2;i<=n;i++){
        for(long long int j=1;j<=i;j++){
            fi += num;
        }
        num = fi;
        fi = 0;
    }
return num;
}
int main(){
    long long int n;
    scanf("%lld",&n);
    printf("%lld\n",fact(n));
return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Autodesk-Forge bucket system: New versioning I am wondering of what is the best practise for handling new version of the same model in the Data Management API Bucket system
Currently, I have one bucket per user and the files with same name overwrites the existing model when doing a svf/svf2 conversion.
In order to handle model versioning in be the best manner, should I :

*

*create one bucket per file converted

or

*continue with one bucket per user.

If 1): is there a limitation of number of buckets which is possible to create?
else 2): How do I get the translation to accept an bucketKey different than the file name? (As it is now, the uploaded file need to be the filename to get the translation going.)
In advance, cheers for the assistance.

A: In order to translate a file, you do not have to keep the original file name, but you do need to keep the file extension (e.g. *.rvt), so that the Model Derivative service knows which translator to use. So you could just create files with different names: perhaps add a suffix like "_v1" etc or generate random names and keep track of which file is what version of what model in a database. Up to you.
There is no limit on number of buckets, but it might be an overkill to have a separate one for each file.


text:
Q: Getting AngularJS Error: "[$rootScope:inprog] $digest already in progress" without a manual $apply Other posts on this error always include someone trying to $apply without using a safe apply, but that's not the case in my example. My function IS successfully returning the data I requested from the API, but I can't clean this bug and it's driving me nuts.
Every time before the .success is called in my $http function I get "Error: [$rootScope:inprog] $digest already in progress" in the console. Below are my controller and service. Thanks!
Here's my service including a function to post an $http call with a payload:
Services.service( 'CoolService', ['$q', '$rootScope', '$http', 'Auth', function($q, $rootScope, $http, Auth){
var service = {
    create: function(payload){
        var deferred = $q.defer();
        $http({
            'url': '/api/endpoint/',
            'dataType':'json',
            'method': 'POST',
            data: payload
        }).success(function(data,status, headers, config){
            deferred.resolve(data);

        })
        .error(function(data, status, headers, config){
            deferred.reject("Error in request.");
        });
        return deferred.promise;
        }
    }
    return service;
}]);

And here's my controller which calls the service:
controllers.controller('CoolCtrl',['$scope', '$modal', '$log','CoolService', function($scope, $modal, $log, CoolService){
    getCoolData = function (input_data) {
        CoolService.create(input_data).then(function(results){
            new_cool = results.results;
        }, function(error){
        console.log("there was an error getting new cool data");
        });
    };
    var payload = {
        user_id: data1,
        cool_id: data2,
    }
    var new_cool_data = getCoolData(payload);
    console.log(new_cool_data);
}]);

The log below var new_cool_data gets called before the async operation, but new_cool does get assigned inside the .then statement within getCoolData.
Any help getting rid of this bug or making it not crappy in general would be greatly appreciated!
Here's the whole error:
https://gist.github.com/thedore17/bcac9aec781ef9ba535b

A: Add this little method and call it inplace of apply()
function CheckScopeBeforeApply() {
    if(!$scope.$$phase) {
         $scope.$apply();
    }
};

A: This solve the issue for me. Just add it one time, it you don't need to change you code any more:
https://github.com/angular/angular.js/issues/10083#issuecomment-145967719
.config(function($provide) {
  // Workaround for https://github.com/angular/angular.js/issues/10083
  $provide.decorator('$rootScope', ['$delegate', '$exceptionHandler',
    function($delegate, $exceptionHandler) {
      var proto = Object.getPrototypeOf($delegate);
      var originalDigest = proto.$digest, originalApply = proto.$apply;
      proto.$digest = function() {
        if ($delegate.$$phase === '$digest' || $delegate.$$phase === '$apply') return;
        originalDigest.call(this);
      };
      proto.$apply = function(fn) {
        if ($delegate.$$phase === '$digest' || $delegate.$$phase === '$apply') {
          try {
            this.$eval(fn);
          } catch(e) {
            $exceptionHandler(e);
          }
        } else {
          originalApply.call(this, fn);
        }
      };
      return $delegate;
    }
  ]);
})

A: I used alternate solution by putting $scope.$apply() in timeout like this and it worked...
setTimeout(function(){
  $scope.$apply();
},1);

I think it is just because, angular's apply lifecycle was already running and my manual $apply has interrupted it.

A: There's an easier solution:
$scope.$evalAsync(function() {
    // Code here
});

Or simply:
$scope.$evalAsync();

This avoids the problems caused by $scope.$apply(), though it should be noted that it won't run immediately (that's part of the reason you won't get the inprog error). I use this instead of $scope.$apply() and it has saved me from so much trouble.
See: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$evalAsync


text:
Q: How to Find the object of The ListItem in ListBox in Windows Phone7 I have a ListBox, here i am binding IList Like (Cities).
I want an event like OnItemDataBound in .NET in Windows Phone7.
Like when every city was binded (if 10 cities are this event will fire 10 times) this event will fire so that i have to do some more calculations on this event. In this event i have to find the object binded to the ListItem so that i can make some calculations. Is there any event in WP7 similar OnItemDataBound in .NET.
<ListBox Loaded="lstFlights_Loaded" Height="635" x:Name="lstFlights"
                         ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="1">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Border CornerRadius="10" Margin="10">
                                <Border.Background>
                                    <ImageBrush ImageSource="../Images/rowbg.png"></ImageBrush>
                                </Border.Background>
//Some data here
     </Border>

                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

i am binding the data like below:
lstFlights.ItemsSource = objCities;

on Binding every city i want an event to populate some list items(like: i want to change the textblock text,etc) according to the City that binded to ListItem. To do this I need an event like OnItemDataBound in WP7. And I have list picker like below:

On SelectionChanged event also i want to change the list items.
And one more thing IList(objCities) is coming from the Service so I can't change that Object
so if i want to change any TextBlock in List Box i have do FindName and i have to assign calculated value for every city binded.

A: There is an CollectionChanged event in ObservableCollection collection for new elements added/removed.
ListBox provides some methods for accessing ListBoxItem. You can see them in list.ItemContainerGenerator class.
You can use it together to achieve needed results.
There is short example that shows how to make a red foreground to newly added items in some conditions (even or not):
ObservableCollection<string> items = new ObservableCollection<string>();

    public MainPage()
    {
        InitializeComponent();

        items.CollectionChanged += (s, e) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (e.NewItems != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        ListBoxItem listitem = (ListBoxItem)list.ItemContainerGenerator.ContainerFromItem(item);
                        if (DateTime.Parse(listitem.Content.ToString()).Second % 2 == 0)
                        {
                            listitem.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                        }
                    }
                }
            });
        };
        list.ItemsSource = items;
    }

    private void AddButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        items.Add(DateTime.Now.ToLongTimeString());
    }

    private void RemoveButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Random rnd = new Random();
        if (items.Count > 0)
        {
            int index = rnd.Next(0, items.Count);
            items.RemoveAt(index);
        }
    }
}

A: How about using the ItemsChanged event of your ListBox's ItemContainerGenerator instead?
this.myListBox.ItemContainerGenerator.ItemsChanged += new System.Windows.Controls.Primitives.ItemsChangedEventHandler(ItemContainerGenerator_ItemsChanged);

void ItemContainerGenerator_ItemsChanged(object sender, System.Windows.Controls.Primitives.ItemsChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    ...


text:
Q: Traverse a binary tree using dfs, stopping at a given point (in Python) I'm learning about some basic computer science concepts. As a demo, I'm creating a script in Python that will perform various functions on a binary tree. I've been able to successfully program most of these functions, except for one specific one.
For a binary tree created from an array of integers, I would like to do a depth first search for an integer, and return the path that was taken through the tree up until that integer was found as an array (with the last number in that array being the number that was being searched for). As soon as the first match for that integer is found, I want to stop traversing the tree.
For example, for an inorder dfs of array [3,2,4,1,4,6,8,5] for integer 4, it should return [1,2,3,4]
For integer 5 it should return [1,2,3,4,4,5] etc.
Here is my code:
class Node:
    def __init__(self,value):
        self.value=value
        self.left=None
        self.right=None

    def getValue(self):
        return self.value

def buildTree(array):
    print("building tree....")
    root=Node(array[0])
    del(array[0])
    for a in array:
        insert(root,Node(a))
    print("building complete")
    return root

def insert(root,node):
    if root is None:
        root = node
    else:
        if root.value < node.value:
            if root.right is None:
                root.right = node
            else:
                insert(root.right, node)
        else:
            if root.left is None:
                root.left = node
            else:
                insert(root.left, node)

def depthFirstSearch(root,target,results,subSearch):
#0:preorder
#1:inorder
#2:postorder
    if root!=None:

        if subSearch==0:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

        depthFirstSearch(root.left,target,results,subSearch)

        if subSearch==1:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

        depthFirstSearch(root.right,target,results,subSearch)

        if subSearch==2:
            results.append(root.getValue())
            if root.getValue()==target:
                return results

    return results

if __name__ == '__main__':
    #stuff that gets our arguments
    #...
    array=[3,2,4,1,4,6,8,5] #we would actually get this as an argument, but using this for example array
    target=4 #example target
    subSearch=1 #using inorder traversal for this example

    root=buildTree(array)
    results=[]
    results=depthFirstSearch(root,target,results,subSearch)
    print(results) #expected:[1,2,3,4]

A: Okay this is easy, just use an Additional variable flag and then your function becomes
def depthFirstSearch(root,target,results,subSearch, flag = 0):
#0:preorder
#1:inorder
#2:postorder
    if root!=None:

        if subSearch==0:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

        results, flag =depthFirstSearch(root.left,target,results,subSearch)
        if flag == 1:
            return results, flag
        if subSearch==1:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

        results, flag = depthFirstSearch(root.right,target,results,subSearch)
        if flag == 1:
            return results, flag

        if subSearch==2:
            results.append(root.getValue())
            if root.getValue()==target:
                return results, 1

    return results, flag

Here Flag changes to one and that is propagated as the function stack shrinks, keeping them after each recursive calls takes care of this.
Also in main function, the function call becomes
results, _=depthFirstSearch(root,target,results,subSearch)

Since flag = 0 is present in function definition you just need to discard the second variable, you can even use that to check if the element was found in the tree rather than just printing the whole tree if element is not present.
If you have any doubts or concerns, comment below.


text:
Q: Looping over NodeList Java I have the following code:
https://code.sololearn.com/c9RLoBhB7Mua
public class Program {

    public static String frontLeft1 = "";
    public static String frontLeft2 = "";

    public static String frontRight1 = "";
    public static String frontRight2 = "";

    public static String rearLeft1 = "";
    public static String rearLeft2 = "";

    public static String rearRight1 = "";
    public static String rearRight2 = "";

    public static void main(String[] args) {

        try {
        String xml = "<DiagnosticResult><REGISTRATION>123123</REGISTRATION><RESULT OBJECT=\"WHEEL_ALIGNMENT\" METHOD=\"MANUFACTURER_SPECIFIC\">
<TITLE>Tire Inspection Axle 1</TITLE><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_1\" LOC=\"LEFT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">1/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_2\" LOC=\"LEFT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">2/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_1\" LOC=\"RIGHT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">3/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_2\" LOC=\"RIGHT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">4/32</VALUE></MEAS>

<MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_1\" LOC=\"LEFT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">5.199</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">5/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_2\" LOC=\"LEFT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"2/32\" RESULT=\"1\">6/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_1\" LOC=\"RIGHT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"4/32\" RESULT=\"1\">7/32</VALUE></MEAS><MEAS OBJECT=\"TREAD_DEPTH_DISPLAY_2\" LOC=\"RIGHT\"><TITLE>Tread Depth Point</TITLE><VALUE UNIT=\"mm\" RESULT=\"0\">4.491</VALUE><VALUE TYPE=\"DISP\" UNIT=\"finch\" LOWLIM1=\"2/32\" LOWLIM2=\"1/32\" RESULT=\"1\">8/32</VALUE></MEAS>
</RESULT></DiagnosticResult>";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setNamespaceAware(true);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document document = dBuilder.newDocument();
        document = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));

        NodeList nodeListMeas = document.getElementsByTagName("MEAS");
        NodeList nodeListSection = document.getElementsByTagName("SECTION");

        for (int i = 0; i < nodeListSection.getLength(); i++) {
            Element sectionElement = (Element) nodeListSection.item(i);
            if (sectionElement.getAttribute("AXLE").equals("1")) {
                for (int j = 0; j < nodeListMeas.getLength(); j++) {
                    Element measElement = (Element) nodeListMeas.item(j);
                    Node node = nodeListMeas.item(j);
                    if (measElement.getAttribute("OBJECT").equals("TREAD_DEPTH_DISPLAY_1")) {
                        NodeList childNodeList = measElement.getElementsByTagName("VALUE");
                        Element childElement = (Element) childNodeList.item(1);
                        if (measElement.getAttribute("LOC").equals("LEFT")) {
                            frontLeft1 = childElement.getTextContent();
                        } else if (measElement.getAttribute("LOC").equals("RIGHT")) {
                            frontRight1 = childElement.getTextContent();
                        }
                    }
                    if (measElement.getAttribute("OBJECT").equals("TREAD_DEPTH_DISPLAY_2")) {
                        NodeList childNodeList = measElement.getElementsByTagName("VALUE");
                        Element childElement = (Element) childNodeList.item(1);
                        if (measElement.getAttribute("LOC").equals("LEFT")) {
                            frontLeft2 = childElement.getTextContent();
                        } else if (measElement.getAttribute("LOC").equals("RIGHT")) {
                            frontRight2 = childElement.getTextContent();
                        }
                    }

                 }
            } else if (sectionElement.getAttribute("AXLE").equals("2")) {
                for (int j = 0; j < nodeListMeas.getLength(); j++) {
                    Element measElement = (Element) nodeListMeas.item(j);
                    Node node = nodeListMeas.item(j);
                    if (measElement.getAttribute("OBJECT").equals("TREAD_DEPTH_DISPLAY_1")) {
                        NodeList childNodeList = measElement.getElementsByTagName("VALUE");
                        Element childElement = (Element) childNodeList.item(1);
                        if (measElement.getAttribute("LOC").equals("LEFT")) {
                            rearLeft1 = childElement.getTextContent();
                        } else if (measElement.getAttribute("LOC").equals("RIGHT")) {
                            rearRight1 = childElement.getTextContent();
                        }
                    }
                    if (measElement.getAttribute("OBJECT").equals("TREAD_DEPTH_DISPLAY_2")) {
                        NodeList childNodeList = measElement.getElementsByTagName("VALUE");
                        Element childElement = (Element) childNodeList.item(1);
                        if (measElement.getAttribute("LOC").equals("LEFT")) {
                            rearLeft2 = childElement.getTextContent();
                        } else if (measElement.getAttribute("LOC").equals("RIGHT")) {
                            rearRight2 = childElement.getTextContent();
                        }
                    }

                }
            }
        }

        System.out.println(frontLeft1);
        System.out.println(frontLeft2);
        System.out.println(frontRight1);
        System.out.println(frontRight2);
        System.out.println(rearLeft1);
        System.out.println(rearLeft2);
        System.out.println(rearRight1);
        System.out.println(rearRight2);

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

The issue I am having is that the variables are being overwritten.
Output should be:
1/32
2/32
3/32
4/32
5/32
6/32
7/32
8/32

But right now it is:
5/32
6/32
7/32
8/32
5/32
6/32
7/32
8/32

I am clearly missing something in the loop, but I can't figure out what is exactly.
I am iterating over AXLE 1 and then I think I am doing the same over AXLE 2, but it looks like AXLE 2 writes over AXLE 1.
XML:
<DiagnosticResult>

      <TITLE>Tire Inspection Axle 1</TITLE>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_1" LOC="LEFT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">4.491</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">1/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_2" LOC="LEFT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">5.871</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">2/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_1" LOC="RIGHT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">5.694</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">3/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_2" LOC="RIGHT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">4.821</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">4/32</VALUE>
      </MEAS>

      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_1" LOC="LEFT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">5.199</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">5/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_2" LOC="LEFT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">6.052</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">6/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_1" LOC="RIGHT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">5.270</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">7/32</VALUE>
      </MEAS>
      <MEAS OBJECT="TREAD_DEPTH_DISPLAY_2" LOC="RIGHT">
         <TITLE>Tread Depth Point</TITLE>
         <VALUE UNIT="mm" RESULT="0">5.249</VALUE>
         <VALUE TYPE="DISP" UNIT="finch" LOWLIM1="2/32" LOWLIM2="4/32" RESULT="1">8/32</VALUE>
      </MEAS>

</DiagnosticResult>

A: You retrieve "MEAS" tags for the whole document.
    NodeList nodeListMeas = document.getElementsByTagName("MEAS");

You can move this line and edit it to limit the search to one section at a time instead :
    for (int i = 0; i < nodeListSection.getLength(); i++) {
        Element sectionElement = (Element) nodeListSection.item(i);
        NodeList nodeListMeas = sectionElement.getElementsByTagName("MEAS");

A: Ultimately, the issue is that one needs to do the following instead, within each loop, rather than on the line before line 33 (NodeList nodeListSection = document.getElementsByTagName("SECTION");)
    NodeList nodeListMeas = sectionElement.getElementsByTagName("MEAS");

Also, please note that I'm still getting the NodeList in question, but am getting it from the corresponding 'sectionElement' instead.


text:
Q: Asp.net Web Api I was going through some code to learn how to Consume a web API.
public async Task<List<TodoItem>> RefreshDataAsync ()
{

  // RestUrl = http://developer.xamarin.com:8081/api/todoitems/
  var uri = new Uri (string.Format (Constants.RestUrl, string.Empty));
  var response = await client.GetAsync (uri);
  if (response.IsSuccessStatusCode) {
      var content = await response.Content.ReadAsStringAsync ();
      Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
  }
}

I found this code.All i want to know is why we use Async and Await.
As i observed Await is mandatory in method body when function is encapsulated as Async keyword.

A: It depends on your application. For GUI apps, it keeps the user interface from freezing and allows this thread to do other things while the call is being made. For apis, it can allow for scalability if you have blocking IO operations. Here is a similar question with some great explanations: Why should I create async WebAPI operations instead of sync ones?


text:
Q: Creating path of nodes If I should have an array, and I want to MERGE all the element in the array into a path of nodes so that when given the relationship name, the nodes will be created if they do not already exist and then joined underneath each other in which the last element in the array will be the leaf node. How do I write this in CYPHER?

A: I am not entirely sure if I understand you correctly, but if you want to transform an array of elements into a sequential path of nodes use the following query:
WITH [1,2,3,4,5] as start
UNWIND start as a
MERGE (l:Label{id:a})
WITH collect(l) as array
    FOREACH(i in RANGE(0, length(array)-2) |
       FOREACH(element1 in [array[i]] |
           FOREACH(element2 in [array[i+1]] |
    MERGE (element1)-[:NEXT]->(element2))))

A: Tomaž's answer is correct, and the way to do this with Cypher alone.
As a supplement to this, if you have APOC Procedures installed, you can use a procedure to perform this linking for you.
Using Tomaž's query with slight modification:
WITH [1,2,3,4,5] as start
UNWIND start as a
MERGE (l:Label{id:a})
WITH collect(l) as array
CALL apoc.nodes.link(array, 'NEXT')
RETURN true // since we can't end the query on a procedure call


text:
Q: Add a new unique ObjectId to each document in collection I have an existing collection users where the _id field is a string instead of an ObjectId.
Is there a query that can update all documents in the collection and add a unique ObjectId for each document to using a new field called UID?

A: You can generate a new ObjectId using new ObjectId() in the shell.
db.users.find().forEach(function(doc){
    doc.UID = new ObjectId();
    db.users.save(doc);
})


text:
Q: How to do PCA and SVM for classification in python I am doing classification, and I have a list with two sizes like this;
Data=[list1,list2]

list1 is 1000*784 size. It means that 1000 images the have been reshaped from 28*28 size into 784.
list2 is 1000*1 size. It shows the label that each images is belonged to.
With the below code, I applied PCA:
from matplotlib.mlab import PCA
results = PCA(Data[0])

the output is like this:
Out[40]: <matplotlib.mlab.PCA instance at 0x7f301d58c638>

now, I want to use SVM as classifier.
I should add the labels. So I have the new data like this for SVm:
newData=[results,Data[1]]

I do not know how use SVM here.

A: from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn import cross_validation

Data=[list1,list2]
X = Data[0]
y = Data[1]
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.4, random_state=0)
pca = PCA(n_components=2)# adjust yourself
pca.fit(X_train)
X_t_train = pca.transform(X_train)
X_t_test = pca.transform(X_test)
clf = SVC()
clf.fit(X_t_train, y_train)
print 'score', clf.score(X_t_test, y_test)
print 'pred label', clf.predict(X_t_test)

Here is an tested code on another dataset.
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn import cross_validation

iris = datasets.load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.4, random_state=0)
pca = PCA(n_components=2)# adjust yourself
pca.fit(X_train)
X_t_train = pca.transform(X_train)
X_t_test = pca.transform(X_test)
clf = SVC()
clf.fit(X_t_train, y_train)
print 'score', clf.score(X_t_test, y_test)
print 'pred label', clf.predict(X_t_test)

Based on these references:

*

*http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

*http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

*http://scikit-learn.org/stable/modules/cross_validation.html

A: I think what you are looking for is http://scikit-learn.org/. It's a python library where you'll find PCA, SVM and other cool algorithms for Machine Learning. It has a good tutorial, but I recommend you follow this guy's http://www.astroml.org/sklearn_tutorial/general_concepts.html . For your particular question, the SVM page of scikit-learn should suffice http://scikit-learn.org/stable/modules/svm.html.


text: Q: Coin operated anti alien vehicle cannon in a movie or show? I vaguely remember seeing a Men in Black styled movie where two guys were sitting in an "anti alien artillery gun vehicle" and had to insert coins into the vehicle to fire the gun. I also remember they didn't quite kill one and had to go over to the spaceship and when they went into it, there was a whole boxing ring fight scene. It's a little Independence Day-ish.


text:
Q: Inverse Kinematics in Arkit I have Scenekit model with 4 joints.

When I use it in SCNView with the code below and change the position of the parent node (Joint) I can see it animated according to the joints.
  private lazy var scene: SCNScene = {

        let scene = SCNScene(named: "art.scnassets/ears")!

        return scene
    }()

in viewDidLoad
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()

        cameraNode.position = SCNVector3(x: 0, y: 0, z: 5)

        rootNode.addChildNode(cameraNode)

        scnView.scene = scene
        scnView.allowsCameraControl = true
        scnView.backgroundColor = .white

        let joint = contentNode!.childNode(withName: "Joint", recursively: true)!
        var ik:SCNIKConstraint = .inverseKinematicsConstraint(chainRootNode: joint)
        joint.childNode(withName: "head", recursively: true)!.constraints = [ik]

The problem occurs when I use the same model in Arkit. In this case, I use a separate View Controller than above. I place it on the head. The model collapse when I show it in Arkit with the code below. I expect it to track head movement and bend according to it.

     func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
      guard let sceneView = renderer as? ARSCNView,
        anchor is ARFaceAnchor else { return nil }

    faceGeometry = ARSCNFaceGeometry(device: sceneView.device!)!

    contentNode = SCNReferenceNode(named: "art/ears")
    //contentNode!.physicsBody = .kinematic()

    let joint = contentNode!.childNode(withName: "Joint", recursively: true)!
    var ik:SCNIKConstraint = .inverseKinematicsConstraint(chainRootNode: joint)
    joint.childNode(withName: "head", recursively: true)!.constraints = [ik]
    return contentNode
    }

I have this extension
extension SCNReferenceNode {
    convenience init(named resourceName: String, loadImmediately: Bool = true) {
        let url = Bundle.main.url(forResource: resourceName, withExtension: "scn", subdirectory: "Models.scnassets")!
        self.init(url: url)!
        if loadImmediately {
            self.load()
        }
    }

Normal look of model is like this

Correctly applied inverse kinematics snapshot

I tried setting setMaxAllowedRotationAngle(between 20-45 degrees) to the joints, this prevents collapse behavior but it also prevents bending.
y property of model gravity is -9.8, x and z are 0.
What might be the problem that I can't create the same effect in Arkit?


text:
Q: How to convert decimal to binary and format it in a specific way? When using the Integer.toBinaryString() method to convert decimal to binary my program keeps returning the binary code without the leading 0's in the binary representation. How can I make sure that the zeros aren't lost? For example if the code is:
String binary = Integer.toBinaryString(84);

I get 1010100 instead of 01010100
How can I make sure that the leading zero doesn't disappear ?

A: You can format the result from the Integer.toBinaryString(int i) method with the String.format(String pattern, Object ... args) method:
String binaryString = Integer.toBinaryString(84);
String format = String.format("%8s", binaryString).replace(' ', '0');


text:
Q: setOnCancel and setOnDimiss Listeners doesn't execute  Face of Codes:
I have a n Object of Dialog that defined below.
dselect=new Dialog(SuraSurface.this);
    dselect.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dselect.setContentView(R.layout.dialogstatus);
    dselect.getWindow().setBackgroundDrawable(new    ColorDrawable(android.graphics.Color.TRANSPARENT));

and I implemented Listeners for it below.
dselect.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                Log.d("DIMISSED", "");
            }
        });

Problem
setOnDimissListener

of dialog doesn't execute.
Question
How can I solve this problem?


text:
Q: How to Measuring Notifications delivery rate & CTR for Android where notification are sent through Amazon SNS and GCM? I want to know how will i be able to track the following things when the notifications are sent to App through Amazon SNS and GCM?
1. Overall delivery rate[From the server till app] to the app , Delivery rate by type of notifications .
2. Failure reasons and its percentage
3. Click through rates of Notifications- On clicking notifications
4. Maximum / minimum no of notifications sent to a user per hour & per day
5. Average no of notifications sent to a user per hour & per day by platform
6. Delivery delay from the point of notification received till it reaches the user.
7. App launch via Notification click


text:
Q: Laravel / Eloquent WHERE NOT SUBQUERY I`m having trouble to setup a negative condition like such:
WHERE NOT( "last_day" "<=" $first_day OR "first_day" "<=" $last_day)

My query builder looks like this atm:
$query = $query->where(function ($query) use ($first_day, $last_day) {
   $query->where('last_day', '<=', $first_day);
   $query->orWhere('first_day', '<=', $last_day);
});

I would like it to be as such :
$query = $query->whereNot(function ($query) use ($first_day, $last_day) {
  $query->where('last_day', '<=', $first_day);
  $query->orWhere('first_day', '<=', $last_day);
});

To recap: I want an OR statement inside a negative WHERE condition. How can I accomplish this?
source : http://baodad.blogspot.nl/2014/06/date-range-overlap.html

A: You can play with the logic
$query = $query->where(function ($query) use ($first_day, $last_day) {
   $query->where('last_day', '>', $first_day);
   $query->where('first_day', '>', $last_day);
});

A: Went with reverting constraints according to answer found here: Eloquent MYSQL statement : WHERE NOT(A OR B)
$query = $query->where('last_day', '>', $first_day)->where('first_day', '>', $last_day);


text:
Q: Loading bitmap from internet in ImageView using Ice Cream Sandwich I'm trying to load an image from internet in ImageView using this code:
    public Bitmap getBitmap(String bitmapUrl) {
      try {
        URL url = new URL(bitmapUrl);
        return BitmapFactory.decodeStream(url.openConnection().getInputStream());
      }
      catch(Exception ex) {
        return null;
      }
}

It works fine with Android 2+ but fails on Ice Cream Sandwich, no errors, the image is just not displayed (I'm using the emulator btw). Any ideas what's the problem is?...thx a lot!

A: Solved:
I was getting an NetworkOnMainThreadException and I forgot print the error in catch (yeah, my bad!), so the problem is I was using the code within a sub-activyty and since Honeycomb is not possible to perform a networking operation on the main thread a handler or asynctask must be used.


text:
Q: Partial derivative and total derivative so i have a function  $ f: R  \rightarrow  R $ and a vector
 $ \overrightarrow{r} $ given.
So i found this, but i don't understand why this is working.
$ \frac{\partial f(r)  x_{3} }{\partial  x_{2} } - \frac{\partial f(r)  x_{2} }{\partial  x_{3} } =  \frac{d f(r)}{d r} ( \frac{ x_{2}  }{r}  x_{3} -  \frac{ x_{3}  }{r}  x_{2}) $ with $ r = \mid\overrightarrow{r}\mid  $


text:
Q: Django auth_user and custom user confusion I am trying to implement a application where the clients can sign up and use our services. One clients can creates many users and define the roles. There can be multiple clients which will have their specific users. For the model what I have in mind is:
class Client(models.Model):
     # Client attributes

class ClientUser(AbstractBaseUser):
    client = models.ForeignKey(Client)
    # Other attributes

Is this the correct way to define model in this scenario? Because default User model in Django already have the is_superuser attribute. What am I missing?

A: There are two ways of customizing your user model: via a one-to-one relation, or extending the User model. See https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model


text:
Q: Accuracy and loss does not change with RMSprop optimizer The dataset is CIFAR10. I've created a VGG-like network:
class FirstModel(nn.Module):
    def __init__(self):
        super(FirstModel, self).__init__()
        self.vgg1 = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.Conv2d(16, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg2 = nn.Sequential(
            nn.Conv2d(16, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.Conv2d(32, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg3 = nn.Sequential(
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.Conv2d(64, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.fc1 = nn.Linear(4 * 4 * 64, 4096)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(4096, 4096)
        self.fc3 = nn.Linear(4096, 10)
        self.softmax = nn.Softmax()
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        x = self.vgg3(self.vgg2(self.vgg1(x)))
        x = nn.Flatten()(x)
        x = self.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.softmax(self.fc3(x))

        return x

Then I train it and visualize loss and accuracy:
import matplotlib.pyplot as plt
from IPython.display import clear_output

def plot_history(train_history, val_history, title='loss'):
    plt.figure()
    plt.title('{}'.format(title))
    plt.plot(train_history, label='train', zorder=1)

    points = np.array(val_history)
    steps = list(range(0, len(train_history) + 1, int(len(train_history) / len(val_history))))[1:]

    plt.scatter(steps, val_history, marker='*', s=180, c='red', label='val', zorder=2)
    plt.xlabel('train steps')

    plt.legend(loc='best')
    plt.grid()

    plt.show()

def train_model(model, optimizer, train_dataloader, test_dataloader):
      criterion = nn.CrossEntropyLoss()

      train_loss_log = []
      train_acc_log = []
      val_loss_log = []
      val_acc_log = []

      for epoch in range(NUM_EPOCH):

        model.train()

        train_loss = 0.
        train_size = 0
        train_acc = 0.

        for inputs, labels in train_dataloader:

          inputs, labels = inputs.to(device), labels.to(device)

          optimizer.zero_grad()
          y_pred = model(inputs)

          loss = criterion(y_pred, labels)
          loss.backward()
          optimizer.step()

          train_loss += loss.item()
          train_size += y_pred.size(0)
          train_loss_log.append(loss.data / y_pred.size(0))

          _, pred_classes = torch.max(y_pred, 1)
          train_acc += (pred_classes == labels).sum().item()
          train_acc_log.append(np.mean((pred_classes == labels).cpu().numpy()))

        # блок validation
        val_loss = 0.
        val_size = 0
        val_acc = 0.

        model.eval()
        with torch.no_grad():
            for inputs, labels in test_dataloader:
                inputs, labels = inputs.to(device), labels.to(device)
                y_pred = model(inputs)
                loss = criterion(y_pred, labels)
                val_loss += loss.item()
                val_size += y_pred.size(0)

                _, pred_classes = torch.max(y_pred, 1)
                val_acc += (pred_classes == labels).sum().item()

        val_loss_log.append(val_loss/val_size)
        val_acc_log.append(val_acc/val_size)

        clear_output()
        plot_history(train_loss_log, val_loss_log, 'loss')
        plot_history(train_acc_log, val_acc_log, 'accuracy')

        print('Train loss:', train_loss / train_size)
        print('Train acc:', train_acc / train_size)
        print('Val loss:', val_loss / val_size)
        print('Val acc:', val_acc / val_size)

Then I train the model:
first_model = FirstModel()
first_model.to(device)

optimizer = optim.RMSprop(first_model.parameters(), lr=0.001, momentum=0.9)

train_model(first_model_rms, optimizer, train_dataloader, test_dataloader)

The loss and accuracy do not change (accuracy at level of 0.1). However, if the optimizer is SGD with momentum everything works fine (loss and accuracy change). I've already tried to change momentum and lr, but it does not help.
What should be fixed? Would be grateful for any possible advice!

A: try to decrease the learning rate more .....if then also there is no affect on the accuracy and loss then change the optimizer to adams or something else and play with different learning rates.

A: So first of all, you don't have to use softmax in the "model" as it is done by the nn.CrossEntropyLoss, and I also think that the RMSprop doesn't work with momentum.

A: In my case, I was facing the same error. On my laptop without GPU the training was fine. When I tried on GPU the model didn't change the accuracy and loss after the first epochs. I was using nn.CrossEntropyLoss() with Adam.
Changing Adam with SGD worked for me.


text:
Q: Extension method requires "this"?
Possible Duplicate:
Why is the 'this' keyword required to call an extension method from within the extended class

Using Visual Studio 2012
Sitefinity 5.* defines a few extension methods for System.Web.UI.MasterPage in the namespace Telerik.Sitefinity.Web.UI.
If I include a reference to that namespace, I can use one particular extension method which indicates of a page is being rendered normally, or by the internal search engine:
using Telerik.Sitefinity.Web.UI;

namespace MyWebApp
{
    public partial class MyMasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /// hide common page elements.
            /// GetIndexRenderMode() returns "Normal" if the page is being rendered
            /// normally, but not if the search engine is indexing the page.
            if (this.GetIndexRenderMode() != IndexRenderModes.Normal)
            {
                headerPlaceholder.Visible = false;
                footerPlaceholder.Visible = false;
                navigationPlaceholder.Visible = false;
            }
        }
    }
}

However, if I remove this from the if(...) statement, the compiler no longer finds the extension method.
What gives? I've never before seen a case where this was necessary, except to resolve ambiguity between class members and interface members or parameters.

A: Every extension method is an extension of some class.
You need an instance of that class to use the extension.
In your  case the extension is for an instance of a MasterPage and you use it inside a derived instance of a MasterPage. Thus you need the this


text:
Q: How a Jenkins non-privileged user can download a file from workspace? I have configured Jenkins job as a UI for my Python script, which takes an input file as a parameter, processes it as I need and writes results into output file which is placed besides the script in the job workspace. This job is intended to be executed by regular non-pivelege Jenkins user. And they permissions do not allow them to access anything in the workspace.
How can they retrieve the output file?
Should I configure ext email plugin, so the file will be sent to users as an attachment?

A: As a user izzekil mentioned, a good approach is to archive the file you need as a build artifact. After archiving the file will be available for download from Jenkins UI.


text:
Q: How do I make a new array nested sorted maps? I have a block of data that looks like this:
var list = [
  { id: '1', title: 'thing1', week: 1, day: 1 },
  { id: '2', title: 'thing2', week: 1, day: 1 },
  { id: '3', title: 'thing3', week: 1, day: 2 },
  { id: '4', title: 'thing4', week: 1, day: 2 },
  { id: '5', title: 'thing5', week: 1, day: 3 },
  { id: '6', title: 'thing6', week: 1, day: 3 },
  { id: '7', title: 'thing7', week: 2, day: 4 },
  { id: '8', title: 'thing8', week: 2, day: 5 },
];

what I want to be able to do is to transform this List to something that outputs this:
var transformedList = [
  { 'Week 1': [
      { id: '1', title: 'thing1', day: 1, week: 1 },
      { id: '2', title: 'thing2', day: 1, week: 1 },
      { id: '3', title: 'thing3', day: 2, week: 1 },
      { id: '4', title: 'thing4', day: 2, week: 1 },
      { id: '5', title: 'thing5', day: 3, week: 1 },
      { id: '6', title: 'thing6', day: 3, week: 1 },
    ],
    'Week 2': [
      { id: '7', title: 'thing7', day: 4, week: 2 },
      { id: '8', title: 'thing8', day: 5, week: 3 },
    ]
  }
]

What I've tried so far is:
var programMap = Map.fromIterable(userProgramSteps, key: (k) => k.getWeek(), value: (v) => v);

// handles the week port just fine, but very stuck on the list of days.

I'm very new to flutter and dart so I'm a little lost... could someone help?

A: Respect to your previous (deleted) question, the code here:
data_weeks.dart
const week_data = [
  { 'id': '1', 'week': 1, 'day': 1, 'title': 'thing1' },
  { 'id': '2', 'week': 1, 'day': 1, 'title': 'thing2' },
  { 'id': '3', 'week': 1, 'day': 1, 'title': 'thing3' },
  { 'id': '4', 'week': 1, 'day': 2, 'title': 'thing4' },
  { 'id': '5', 'week': 1, 'day': 2, 'title': 'thing5' },
  { 'id': '6', 'week': 2, 'day': 3, 'title': 'thing6' },
  { 'id': '7', 'week': 2, 'day': 4, 'title': 'thing7' },
];

home_page.dart
import 'package:flutter/material.dart';
import 'package:list_cards/src/shared/data_weeks.dart';

class HomePage extends StatelessWidget {
  /* ---------------------------------------------------------------------------- */
  const HomePage({Key key}) : super(key: key);
  /* ---------------------------------------------------------------------------- */
  @override
  Widget build(BuildContext context) {
    final data = getNewData();

    return Scaffold(
      appBar: AppBar(
        title: Text('Hi!'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          itemCount: data.length,
          itemBuilder: (context, index) => ListTile(
            title: Text(
              'Week ${data.keys.toList()[index]}',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            subtitle: getSubtitles1(data[data.keys.toList()[index]], context),
          ),
        ),
      ),
    );
  }

  Widget getSubtitles1(List<Map<int, Object>> data, BuildContext context) {
    return Column(
      children: List.generate(data.length, (index) => ListTile(
        title: Text(
          'DAY ${data[index].keys.toList()[0]}',
          style: TextStyle(
            fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black.withOpacity(0.4)
          ),
        ),
        subtitle: getSubtitles2(data[index][data[index].keys.toList()[0]], context),
      )),
    );
  }

  Widget getSubtitles2(List<String> data, BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Column(
      children: List.generate(data.length, (index) => Card(
        elevation: 0,
        margin: EdgeInsets.all(0),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
          child: Row(
            children: [
              Container(
                width: (size.width + 80) / 2,
                child: Text(data[index]),
              ),
              IconButton(icon: Icon(Icons.check_box_outline_blank), onPressed: () {}),
            ],
          ),
        ),
      )),
    );
  }

  Map<int, Object> getNewData() {
    var weeks = week_data.map<int>((m) => m['week']).toSet().toList();
    var newData = Map<int, Object>();

    weeks.forEach((w) {
      newData[w] = week_data.where((m) => m['week'] == w).map<int>((m) => m['day']).toSet().map<Map<int, Object>>((e) => {e: week_data.where((m) => m['week'] == w && m['day'] == e).map<String>((m) => m['title']).toList()}).toList();
    });

    return newData;
  }
}

The result:

And with respect to your current question, getNewData() method contains the logic for your answer. Enjoy it!

A: Try using package:collection version 1.15.0. It includes a groupListsBy extension method which allows you to write this as:
var transformedList = list.groupListsBy((o) => "Week ${o["week"]}");


text:
Q: Check for values from list in a string from a measure I have a Calculated column in table_1 which is a result of a measure that returns a string with several values in it. Each of these values represents a fault code and its format is DI followed by 4 digits.
Now I have a second table (table_2) that has a list of faults codes, some of those fault codes can be found in the string of the calculated column from the 1st table.
What I'm looking for is a measure that will return a 'True' statement if any row from the calculated column in the table1 has a fault code that is not on the list of fault codes from table2. Additionally will return a 'False' statement in case of all codes from the string of calculated column in table1 are present on the list of table_2. Please see a simplified example
 .
The result should look as follow
.
So far I've managed to check if only the first value from the string in the calculated column of table 1 fulfils that condition. Unfortunately, I'm not able to apply it to the full string, Could someone support, please.
Table2 list
| List   |
|--------|
| DI0001 |
| DI0002 |
| DI0003 |
| DI0004 |
| DI0005 |
| DI0006 |
| DI0007 |
| DI0008 |
| DI0009 |
| DI0011 |
| DI0013 |
| DI0015 |
| DI0105 |
| DI0107 |
| DI0108 |
| DI0211 |
| DI0212 |
| DI0505 |
| DI0806 |
| DI0907 |
| DI1113 |
| DI1212 |
| DI1504 |
| DI1505 |
| DI1601 |
| DI1602 |
| DI1603 |
| DI1604 |
| DI1605 |
| DI1606 |
| DI1607 |
| DI1608 |
| DI1609 |
| DI1610 |
| DI1611 |
| DI1612 |
| DI1613 |
| DI1614 |
| DI1615 |
| DI1616 |
| DI1617 |
| DI1618 |
| DI1701 |
| DI1702 |
| DI1703 |
| DI1704 |
| DI1705 |
| DI1706 |
| DI1707 |
| DI1708 |
| DI1801 |
| DI1802 |
| DI1803 |
| DI1804 |
| DI1901 |
| DI1902 |
| DI1903 |
| DI1904 |
| DI1905 |
| DI2601 |
| DI9901 |
| DI9902 |
| DI9903 |
| DI9904 |
| DI9905 |
| DI9906 |
| DI9907 |
| DI9908 |
| DI9909 |
| DI9910 |
| DI9911 |
| DI9912 |
| DI9913 |

Here is table1 and the calculated column
| Calculated   Column                                       |
|-----------------------------------------------------------|
| DI0501 DI1604 DI1605                                      |
| DI1604 DI1605                                             |
| DI1604 DI1605                                             |
| DI1605                                                    |
| DI1604 DI1605 DI0105                                      |
| DI1604 DI1605                                             |
| DI0105 DI1604 DI1605                                      |
| DI1605 DI1604                                             |
| DI1604 DI1605 DI0105 DI1604   DI1604 DI1604 DI1604 DI1604 |
| DI1604 DI1605                                             |
| DI1605                                                    |
| DI1604 DI1605                                             |
| DI1605                                                    |
| DI1604 DI1605 DI0105                                      |
| DI0105 DI1604 DI1605                                      |
| DI1604 DI1605                                             |
| DI1010 DI1604 DI1605 DI0105                               |
| DI1604 DI1605 DI0105                                      |
| DI1604 DI1605 DI1604 DI1604   DI1604 DI1604 DI1604        |
| DI1604 DI1605                                             |
| DI1604 DI1605                                             |
| DI1604 DI1605 DI0105 DI1604   DI1604 DI1604 DI1604 DI1604 |
| DI0204                                                    |
| DI1015 DI0105 DI1604 DI1605                               |
| DI1604 DI1605 DI0105                                      |
| DI1604 DI1605 DI0105                                      |
| DI1604 DI1605 DI0105 DI1604   DI1604 DI1604 DI1604 DI1604 |
| DI1102 DI1605                                             |
| DI1605                                                    |
| DI1604 DI1604 DI1605                                      |
| DI1604 DI1605 DI1604                                      |
| DI1605 DI1604 DI1010                                      |
| DI0107                                                    |
| DI0105 DI1604 DI1605                                      |
| DI1604 DI0204                                             |
| DI0105 DI1604 DI1605                                      |
| DI1605                                                    |
| DI1604 DI1605 DI0105 DI1604   DI1604 DI1604 DI1604 DI1604 |

Example of a model in the link:
https://drive.google.com/drive/folders/1QVaPfMHkY_QQQmcUrBgTLNCDwmbuwq98?usp=sharing

A: This is the modified DAX Measure
_Measure =
VAR _1 =
    FILTER (
        ADDCOLUMNS (
            Table_1,
            "new", SUBSTITUTE ( Table_1[Calculated column], " ", "|" )
        ),
        [new] <> BLANK ()
    )
VAR _2 =
    GENERATE (
        _1,
        ADDCOLUMNS (
            GENERATESERIES ( 1, PATHLENGTH ( [new] ) ),
            "_txt", TRIM ( PATHITEM ( [new], [Value], TEXT ) )
        )
    )
VAR _filt =
    ADDCOLUMNS (
        _2,
        "score",
            VAR _1 = [_txt]
            VAR _2 =
                CALCULATE ( MAX ( table_2[List] ), TREATAS ( { _1 }, table_2[List] ) )
            RETURN
                IF ( _2 = BLANK (), "x", _2 )
    )
RETURN
    IF (
        COUNTX ( FILTER ( _filt, [score] = "x" ), [Calculated column] ) >= 1,
        TRUE,
        FALSE
    )

A: If you are comfortable with Power Query, you can create a new table using this below Advanced Query code-
let
    Source = Table_1,
    #"Trimmed Text" = Table.TransformColumns(Source,{{"Calculated Column", Text.Trim, type text}}),
    #"Sorted Rows" = Table.Sort(#"Trimmed Text",{{"Calculated Column", Order.Ascending}}),
    #"Removed Other Columns" = Table.SelectColumns(#"Sorted Rows",{"Calculated Column"}),
    #"Removed Duplicates" = Table.Distinct(#"Removed Other Columns"),
    #"Added Index" = Table.AddIndexColumn(#"Removed Duplicates", "Index", 1, 1, Int64.Type),
    #"Reordered Columns" = Table.ReorderColumns(#"Added Index",{"Index", "Calculated Column"}),
    #"Split Column by Delimiter" = Table.ExpandListColumn(Table.TransformColumns(#"Reordered Columns", {{"Calculated Column", Splitter.SplitTextByDelimiter(" ", QuoteStyle.Csv), let itemType = (type nullable text) meta [Serialized.Text = true] in type {itemType}}}), "Calculated Column"),
    #"Changed Type" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Calculated Column", type text}}),
    #"Merged Queries" = Table.NestedJoin(#"Changed Type", {"Calculated Column"}, Table2, {"List  "}, "Table2", JoinKind.LeftOuter),
    #"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2", {"List  "}, {"Table2.List  "}),
    #"Sorted Rows1" = Table.Sort(#"Expanded Table2",{{"Index", Order.Ascending}}),
    #"Renamed Columns" = Table.RenameColumns(#"Sorted Rows1",{{"Table2.List  ", "Table2.List"}}),
    #"Grouped Rows" = Table.Group(#"Renamed Columns", {"Index"}, {{"AllData", each _, type table [Index=number, Calculated   Column=nullable text, #"Table2.List  "=nullable text]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each [AllData][Calculated Column]),
    #"Extracted Values" = Table.TransformColumns(#"Added Custom", {"Custom", each Text.Combine(List.Transform(_, Text.From), " "), type text}),
    #"Added Custom1" = Table.AddColumn(#"Extracted Values", "Custom.1", each [AllData][Table2.List]),
    #"Extracted Values1" = Table.TransformColumns(#"Added Custom1", {"Custom.1", each Text.Combine(List.Transform(_, Text.From), " "), type text}),
    #"Added Custom2" = Table.AddColumn(#"Extracted Values1", "Custom.2", each if Text.Length([Custom.1]) = 0 then false else true),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom2",{"Index", "AllData", "Custom.1"}),
    #"Renamed Columns1" = Table.RenameColumns(#"Removed Columns",{{"Custom", "Calculated Column"}, {"Custom.2", "Is_present"}})
in
    #"Renamed Columns1"

Output will be as below-

Now you can join your Table_1 and Table_1_new using Calculated Column and import Is_present from the new table for your further purpose.


text:
Q: C++ Combine two strings for displayBMP Currently working on a Lottery project for my CompSci class.
I've got 40 lottery ball images (1.BMP to 40.BMP) and I want to use a for loop to display each ball.
I can display them just fine if I call displayBMP all 40 times, but there has to be a prettier way of doing this.
string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    char alphanum = i;
    //char* name = combine alphanum and type
    displayBMP(name, randomX(), randomY());
}

Edit
Trying to put this junk in .cpp file for my header.
#include "Lottery.h"
void Lottery::initDisplay()
{

    //Draw Some Lines

    //Display Lottery balls 1-40

}

Any thoughts?

A: I think you want:
1.BMP
2.BMP
3.BMP
4.BMP

etc..
The code for that would be:
Non-C++11:
#include <sstream>

template <typename T>
std::string ToString(T Number)
{
    std::stringstream ss;
    ss << Number;
    return ss.str();
}

std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    displayBMP(ToString(i) + type, randomX(), randomY());
}

Using C++11:
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    displayBMP(std::to_string(i) + type, randomX(), randomY());
}

A: You can use function c_str() in string class to return const char*
So if the first type of displayBMP is const char*
e.g.
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
    char alphanum = i;

    std::string name = "" + alphanum + type;
    displayBMP(name.c_str(), randomX(), randomY());
}

However, the type is char*
e.g.
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
  char alphanum = i;

  std::string name = "" + alphanum + type;
  displayBMP(&name[0], randomX(), randomY());
}

Here, I suggest that convert the name's type to string that will be more convenient,
and if you don't want to change the name in the displayBMP, the first example will be more
intuition


text:
Q: Extracting code as pure string from Roslyn API Our goal is to build a toy abstract syntax tree for C# classes using Roslyn. We just want to show the basic structure of a class instead of walking through the entire AST. For example (Taken from MSDN):
class TimePeriod
{
  private double seconds;

  public double Hours
  {
      get { return seconds / 3600; }
      set { seconds = value * 3600; }
  }
}

Let us only consider the Property Hours; we are only interested in extracting the tokens for modifier (public), return type (double), identifier (Hours) as for the body of two accessors we want to directly extract it as a String.
However, as we walk though the roslyn (shown in the screen dump) when we get to get accessor's body we did not find the field representing the entire string. What's the correct way of achieving this?

A: The obvious way is to call ToString:

Returns the string representation of this node, not including its leading and trailing trivia.

If you want the leading and trailing trivia (whitespace, comments, ...), there's ToFullString:

Returns full string representation of this node including its leading and trailing trivia.

For efficiency purposes, you may also be interested in the WriteTo method, which writes what ToFullString would produce to a TextWriter, avoiding intermediate string allocations:

Writes the full text of this node to the specified TextWriter.


text:
Q: when toggle a div, how to let the user on top on that div instead of being scroll in the middle here is my problem,
On click of a button, I have a div being toggle underneath ( quite long). it ( randomly) bring the user on the middle of the new div, I would like to let the user on the top  of this new div instead.
How is this possible to achieve ?
Here is my current jquery:
$(document).on("click",".more, .more-com, .more-com-film",function() {
    $(".all-content-news, .all-content-news-single").css("display","none");
    // $(".overlaybg").css("display","none");

            //         $(this).parent().parent().parent().parent().children('.action-container-com-film').css("top","9.9%");

            $(this).parent().parent().parent().parent().children('.overlaybg').css("display","none");
            $(this).parent().parent().parent().parent().children('.all-content-news-single').fadeToggle();
            $(this).parent().parent().parent().parent().children('.entry-title-wrapper').css("background","rgba(0, 0, 0, 0)");

click on .more-com, toggle the new div .all-content-news-single
Any highlight will be wonderful, thank you so much !!

A: I think you need append particular element before or after
You can put on following code:
 $(".all-content-news-single").append("Hello world!");

 $("Hello world!").insertAfter(".all-content-news-single");

 $( "Hello world!" ).insertBefore( ".all-content-news-single" );

A: Bind a event for know the start or the end of your toogle:
$(document).ready(function(){
    $(document).on("click",".more, .more-com, .more-com-film",function() {
        $(this).parent().parent().parent().parent().children('.all-content-news-single').fadeToggle({
            start:function() {
                console.log('start');
            },
            done:function(data) {
                console.log('done');
            }
        });
    });
});

Then use a classic ancor or a script to scroll to your target
https://github.com/flesler/jquery.scrollTo


text:
Q: Commit and Rollback transactions in MongoDB Java Currently, I am using the following code:-
(I have marked the two important lines in the code. Between these lines are just some operations on existing documents)
clientSession.startTransaction();  // Important Line 1.
Document walletDetailDoc = new Document("identifier", "walletBalanceDistribution");
Document foundWalletDetailDoc1 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
walletDetailDoc = new Document("identifier", to + "Backup");
Document foundWalletDetailDoc2 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
walletDetailDoc = new Document("identifier", from + "Backup");
Document foundWalletDetailDoc3 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
assert foundWalletDetailDoc1 != null;
assert foundWalletDetailDoc2 != null;
assert foundWalletDetailDoc3 != null;
Bson updateWalletDoc = walletDetailDoc;
Bson updateWalletDocOperation = new Document("$set", updateWalletDoc);
walletDistributionCollection.updateOne(foundWalletDetailDoc1, updateWalletDocOperation);
updateWalletDoc = new Document("identifier", "walletBalanceDistribution")
        .append("totalRTKBalanceForPool", foundWalletDetailDoc2.get("totalRTKBalanceForPool"))
        .append("lastCheckedBlockNumber", foundWalletDetailDoc2.get("lastCheckedBlockNumber"))
        .append("lastCheckedTransactionIndex", foundWalletDetailDoc2.get("lastCheckedTransactionIndex"))
        .append("balanceCollectedAsFees", foundWalletDetailDoc2.get("balanceCollectedAsFees"));
updateWalletDocOperation = new Document("$set", updateWalletDoc);

//////// TEMPORARY... TO BE REMOVED
Thread.sleep(5000);
clientSession.abortTransaction();  // Important Line 2
boolean abc = true;
if(abc) {
    return;
}
////////

Now, I excepted that once I call abortTransaction(), the collection would revert back to it's previous state as it was before //Important Line 1. But that doesn't happend. As I keep making operations, they get saved in MonogDB and do not get reverted when // Important line 2 completes execution.
(Just in case, everything is in try catch and there are no errors between any lines. The code successfully reaches the return statement.)
Also, if required, I am using the following maven dependency:-
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.2.0</version>
</dependency>

How to do this operation properly such that everything gets done, or nothing gets done (i.e. rollback/abort).

A: You need to include the write operations inside the session transaction , example:
original state of collection:
 mongos> db.tra.find()
 { "_id" : ObjectId("601088bac5b64c7d32c73a8a"), "today" : ISODate("2021-01-26T21:25:14.835Z") }
 { "_id" : ObjectId("60108901c5b64c7d32c73a8b"), "today" : ISODate("2021-01-26T21:26:25.264Z") }
 mongos>

1 Now you start session:
 session = db.getMongo().startSession()

2 Now you start transaction in the started session:
 mongos> session.startTransaction()

3 You insert test document to the collection in the transaction:
 mongos> session.getDatabase("test").tra.insert({a:"this will be aborted",today : new Date()})
 WriteResult({ "nInserted" : 1 })

4 Check the collection now , there is no inserted document(transaction is yet not commited):
 mongos> db.tra.find()
 { "_id" : ObjectId("601088bac5b64c7d32c73a8a"), "today" : ISODate("2021-01-26T21:25:14.835Z") }
 { "_id" : ObjectId("60108901c5b64c7d32c73a8b"), "today" : ISODate("2021-01-26T21:26:25.264Z") }

5 Now abort the transaction:
 mongos> session.abortTransaction()

6 As you can see nothing is inserted(transaction was aborted):
 mongos> db.tra.find()
{ "_id" : ObjectId("601088bac5b64c7d32c73a8a"), "today" : ISODate("2021-01-26T21:25:14.835Z") }
{ "_id" : ObjectId("60108901c5b64c7d32c73a8b"), "today" : ISODate("2021-01-26T21:26:25.264Z") }
mongos>

Afcourse if you replace step 5 with session.commitTransaction() the transaction will be commited and you will see the operations applied to the collection.
There is nice java example here : https://www.mongodb.com/blog/post/java-and-mongodb-40-support-for-multidocument-acid-transactions

A: Correct answer was pretty simple...
(Found by referring to the link at the very bottom of @R2D2 's answer.)
(TL;DR :- Add clientSession as the first parameter in updateOne method).
All we had to do is this :-
        clientSession.startTransaction();  // Important Line 1.
        Document walletDetailDoc = new Document("identifier", "walletBalanceDistribution");
        Document foundWalletDetailDoc1 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
        walletDetailDoc = new Document("identifier", to + "Backup");
        Document foundWalletDetailDoc2 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
        walletDetailDoc = new Document("identifier", from + "Backup");
        Document foundWalletDetailDoc3 = (Document) walletDistributionCollection.find(walletDetailDoc).first();
        assert foundWalletDetailDoc1 != null;
        assert foundWalletDetailDoc2 != null;
        assert foundWalletDetailDoc3 != null;

        Bson updateWalletDoc = walletDetailDoc;
        Bson updateWalletDocOperation = new Document("$set", updateWalletDoc);
        walletDistributionCollection.updateOne(clientSession, foundWalletDetailDoc1, updateWalletDocOperation);
        updateWalletDoc = new Document("identifier", "walletBalanceDistribution")
                .append("totalRTKBalanceForPool", foundWalletDetailDoc2.get("totalRTKBalanceForPool"))
                .append("lastCheckedBlockNumber", foundWalletDetailDoc2.get("lastCheckedBlockNumber"))
                .append("lastCheckedTransactionIndex", foundWalletDetailDoc2.get("lastCheckedTransactionIndex"))
                .append("balanceCollectedAsFees", foundWalletDetailDoc2.get("balanceCollectedAsFees"));
        updateWalletDocOperation = new Document("$set", updateWalletDoc);

        //////// TEMPORARY... TO BE REMOVED
        Thread.sleep(5000);
        clientSession.abortTransaction();  // Important Line 2
        boolean abc = true;
        if(abc) {
            return;
        }
        ////////


text:
Q: Can I get the most recent commit of a repository with Bitbucket API? I am using Bitbucket API to retrieve different information. However I am looking to do a request that retrieves the latest commit for a repository. I initially thought it would be done like this:
https://bitbucket.org/!api/2.0/repositories/xxxx/xxxx/commits?limit=1

This just showed all the commits as normal but I want to show the most recent one. From looking through the API documentation I can't find anything that shows about limiting the number of commits to show. So was wondering if anyone could point me in the right direction?

A: Okay this wasn't straight forward either and I spent a couple of hours looking for how to do this myself. It ended up being easy if not unfortunate. Simply put the available API will not return just a target commit (like the latest). You have do parse it yourself. The following api:
"https://api.bitbucket.org/2.0/repositories/<project>/<repo>/commits/<branch>?limit=1"

Will still return ALL the commits for that particular branch BUT in order. So you can simply just grab the first result on the first page that is returned and that's the most recent commit for that branch. Here is a basic python example:
import os
import requests
import json

headers = {"Content-Type": "application/json"}
USER = ""
PASS = ""

def get_bitbucket_credentials():
    global USER, PASS
    USER = "<user>"
    PASS = "<pass>"

def get_commits(project, repo, branch):
    return json.loads(call_url("https://api.bitbucket.org/2.0/repositories/%s/%s/commits/%s?limit=1" % (project, repo, branch)))

def get_modified_files(url):
    data = json.loads(call_url(url))
    file_paths = []
    for value in data["values"]:
        file_paths.append(value["new"]["path"])
    return file_paths

def call_url(url):
    global USER, PASS
    response = requests.get(url, auth=(USER, PASS), headers=headers)
    if response.status_code == requests.codes.ok:
        return response.text
    return ""

if __name__ == "__main__":
    get_bitbucket_credentials()
    data = get_commits("<project>","<repo>","<branch>")
    for item in data["values"]:
        print("Author Of Commit: "+item["author"]["raw"])
        print("Commit Message: "+item["rendered"]["message"]["raw"])
        print("List of Files Changed:")
        print(get_modified_files(item["links"]["diff"]["href"].replace("/diff/","/diffstat/")))
        break

You can run the above example:
python3 mysavedfile.py

and that will output like:
Author Of Commit: Persons Name <personemail@email.com>
Commit Message: my commit message

List of Files Changed:
['file1.yaml','file2.yaml']

A: There a simple way to do it, using Bitbucket pagination mechanism.
Like so:
https://bitbucket.org/!api/2.0/repositories/xxxx/xxxx/commits?pagelen=1
Normally you'll need to specify the page number, "page=1", but the default is 1 so...


text:
Q: Catch own Exceptions I build some package with my own Exception but when I try to catch a exception I got fatal error: Uncaught exception. This situation is only when method with throw is passed by add_action( 'init', array( $this, 'wp_some_method' ) );
Example:
class SomeClass {
    public function __construct() {
        add_action( 'init', array( $this, 'wp_some_method' ) );
        echo '__constructor
';
    }
    function some_method(){
        throw new \Exception('some message');
    }
    function wp_some_method( $post_type ){
        throw new \Exception('Some second error');
    }
}
try{
    echo 'try
';
    $o = new SomeClass();
    //$o->some_method(); - this throw exception correct

} catch (\Exception $ex) {
    echo $ex->getMessage();
}

Displayed on the screen:
try
__constructor
And:
Fatal error: Uncaught exception 'Exception'

A: Your exception isn't caught by the try{} catch(){} block, because it isn't thrown inside the try catch block. This demonstrates a lack of understanding of asynchronous events and the WordPress hook/action/event system.
The methods of your object are attached to the init action hook, and are thrown when the init hook is fired, not when the object is created, and not when they're attached.
e.g.
class SomeClass {
    public function __construct() {
        // when the init action/event happens, call the wp_some_method
        add_action( 'init', array( $this, 'wp_some_method' ) );
    }
    function wp_some_method( $post_type ){
        throw new \Exception('error');
    }
}
try{
    // great, no exceptions where thrown while creating the object
    $o = new SomeClass();
} catch (\Exception $ex) {
    echo $ex->getMessage();
}

// a small period of time later somewhere in WP Core...

do_action( 'init' ); // a method we attached to the init hook threw an exception, but nothing was there to catch it!

Your method is not called when your object is created. It's attached to the init event yes, but it is not called, precisely because the 'init' event hasn't happened yet. The init event happens long after your try{} catch statement runs.
So instead, these would be more appropriate:

*

*add a try catch in the class methods ( best )

*Don't throw exceptions in functions attached to hooks/events ( even better )

*throw the exception in a new method that isn't the method you attached so you can add in a try catch ( okay, requires good separation of concerns and abstraction )

*add a global error handler ( hackish, strongly advise against, will take more time than its worth, may catch other exceptions that you never intended to catch )

Otherwise there is no rational, logical, common sense reason why the line of code that says throw new \Exception should be executed inside the try catch block as you have above without you purposefully calling it manually as you did in your test.


text:
Q: soap webservice method with an object to be called from android I need to call a soap webservice from my android app.the webservice method has an object with 4 values.I have read about ksoap lib.But i am confused of how the object in service be sent as parameter from android.Please help me solve this.
  public SoapObject soap(String METHOD_NAME, String SOAP_ACTION, String NAMESPACE, String URL,String IP,String SERVICEPATH) throws IOException, XmlPullParserException
  {

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); //set up request

    PropertyInfo pi = new PropertyInfo();

    pi.setName("Parameter1");
    pi.setValue(Value1);

    request.addProperty(pi);
     pi.setName("Parameter2");
     pi.setValue(Value2);
    request.addProperty(pi);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap
envelope.dotNet = true;
envelope.setOutputSoapObject(request); // prepare request
envelope.bodyOut = request;
  Log.d("ENVELOPE",""+"Coming3");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//androidHttpTransport.
androidHttpTransport.call(SOAP_ACTION, envelope);

Log.d("ENVELOPE",""+envelope.bodyIn);
SoapObject result = (SoapObject) envelope.bodyIn; // get response
Log.d("ENVELOPE",""+envelope.bodyIn);
SoapObject responseBodyRaw,responseBody,tableRow;
return result;
}

Is this how it should be done?
I have not worked with ksoap and soap webservices.Please help

A: Suppose you have webmethod defined like this which returns Category object.
[WebMethod]
public Category GetCategoryById(Category C);

Say Category class has three properties like CategoryId, Name and Description.So to use it with KSoap you have to implement KvmSerializable.
package CommonObjects;

import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

public class Category implements KvmSerializable
{
public int CategoryId;
public String Name;
public String Description;

public Category(){}
public Category(int categoryId, String name, String description) {

    CategoryId = categoryId;
    Name = name;
    Description = description;
}
public Object getProperty(int arg0) {

    switch(arg0)
    {
    case 0:
        return CategoryId;
    case 1:
        return Name;
    case 2:
        return Description;
    }

    return null;
}

public int getPropertyCount() {
    return 3;
}
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
    switch(index)
    {
    case 0:
        info.type = PropertyInfo.INTEGER_CLASS;
        info.name = "CategoryId";
        break;
    case 1:
        info.type = PropertyInfo.STRING_CLASS;
        info.name = "Name";
        break;
    case 2:
        info.type = PropertyInfo.STRING_CLASS;
        info.name = "Description";
        break;
    default:break;
    }
}

public void setProperty(int index, Object value) {
    switch(index)
    {
    case 0:
        CategoryId = Integer.parseInt(value.toString());
        break;
    case 1:
        Name = value.toString();
        break;
    case 2:
        Description = value.toString();
        break;
    default:
        break;
    }
}
}

Now you have to map the properties, read them and write them.
So the web service call is:
public void WebServiceCallExample()
    {
        String NAMESPACE = "http://vladozver.org/";
        String METHOD_NAME = "GetCategoryById";
        String SOAP_ACTION = "http://vladozver.org/GetCategoryById";
        String URL = "http://192.168.1.3/VipEvents/Services/CategoryServices.asmx";

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

        /*
         * Create Category with Id to be passed as an argument
         *
         * */
        Category C = new Category();
        C.CategoryId = 1;

        /*
         * Set the category to be the argument of the web service method
         *
         * */
        PropertyInfo pi = new PropertyInfo();
        pi.setName("C");
        pi.setValue(C);
        pi.setType(C.getClass());
        Request.addProperty(pi);

        /*
         * Set the web service envelope
         *
         * */
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);

        envelope.addMapping(NAMESPACE, "Category",new Category().getClass());
        AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
        /*
         * Call the web service and retrieve result ... how luvly <3
         *
         * */
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapObject response = (SoapObject)envelope.getResponse();
            C.CategoryId =  Integer.parseInt(response.getProperty(0).toString());
            C.Name =  response.getProperty(1).toString();
            C.Description = (String) response.getProperty(2).toString();
            TextView tv = (TextView)findViewById(R.id.TextView01);
            tv.setText("CategoryId: " +C.CategoryId + " Name: " + C.Name + " Description " + C.Description);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

In order to use this code, make sure that you replace the first three variables in this method with your own. NOTE: The SOAP_ACTION could actually be computed as NAMESPACE + METHOD_NAME
In the lines about the property info, I show how to actually pass a Category class complex object to KSOAP.
PropertyInfo pi = new PropertyInfo();
pi.setName("Category");
pi.setValue(C);
pi.setType(C.getClass());
Request.addProperty(pi);

Regarding the return type, if your web method returns a complex object (such as ours), you need to tell KSOAP how to handle the response. That is done with the following code:
envelope.addMapping(NAMESPACE, "Category",new Category().getClass());

This part of the code is the actual retrieval of the response:
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
C.CategoryId =  Integer.parseInt(response.getProperty(0).toString());
C.Name =  response.getProperty(1).toString();
C.Description = (String) response.getProperty(2).toString();

Reference from this blogpost.


text:
Q: Local testing without affecting backend I am looking to import some resources into terraform but I would first like to test everything locally before making any changes to state in our backend.
ie. I would like to check out the current state, run terraform import locally and and see the changes of my plan without changing the backend state.
What I have been doing so far:

*

*initialize using backend

*comment out the backend block and run init again telling terraform to copy my previously found state

*run my imports and terraform plan

Just wondering if there is a better approach? I've looked into workspaces but I don't want terraform to treat everything as new.
Thanks.


text:
Q: Join between 2 tables in MySQL DB I have 2 tables in MySQL db like this:
First table:
db.number
id     name    id_codes    date

And second table:
db.number1
id_num   package_id    username     paswword

Please help me to find name, username, password when date is bigger then x and num_package =y.
With Join or another transaction in MySQL db.
PS
id_codes at db.number is equivalent with id_num at db.number1

A: Is it like this way?
SELECT
T1.name,
T2.username,
T2.password
FROM
number T1
INNER JOIN number1 T2
ON T1.id_codes = T2.id_num
WHERE
T1.date > '2017-05-10' AND
T2.package_id = 'y'

A: @fortune I used this: like your answer but I modify
SELECT
T1.name,
T2.username,
T2.password
FROM
number T1
INNER JOIN number1 T2
ON T1.id_codes = T2.id_num
WHERE
T1.date > '2017-05-10'
and T2.package_id = 'y'

And this giving me the result that I want.


text:
Q: Go back arrow and kebab menu not showing up in Gmail app in gmail addon I am developing a sample addon. The add-on is working fine on desktop gmail but in android mobile gmail app, when i open my add-on, i notice that "Go back arrow" and "kebab" menu is not showing up. Although both of these are showing and working fine on desktop gmail.com.
First image is when I open gmail on desktop and can see the go back and kebab menu
Second image is when I open gmail app on mobiel and can not see the go back and kebab menu
Thanks in advance.


text:
Q: Proof that $\left \langle 0\mid \hat{S}\mid 0 \right \rangle = e^{\sum (\text{all connected vacuum diagrams})}$ In my book on QFT  (Lancaster & Blundell) they state the following equation, without proof: $$\left \langle 0\mid \hat{S}\mid 0 \right \rangle  = e^{\sum (\text{all connected vacuum  diagrams})}$$ where $\hat{S}$ is the S-matrix. This is what I tried:
If we expand the expression above in terms using dyson's series, we get:$$\left \langle 0\mid \hat{S}\mid 0 \right \rangle = \left \langle 0\mid Te^{-i\int d^{4}z\hat{H}_{I}(z)}\mid0  \right \rangle$$ and then maclaurin expanding the exponential gives us the following:$$\left \langle 0\left | T \left [ 1-i\int d^{4}z\hat{H}_I(z)+\frac{(-i)^{2}}{2}\int d^{4}yd^{4}w\hat{H}_I(y)\hat{H}_I(w)+... \right ]\right | 0\right \rangle$$    I am not sure where to go from here, however. Can anyone help me complete this proof?

A: Note that each term in your MacLaurin$^\dagger$ series represents one or more diagrams. Since they are sandwiched between the vacuum $|0>$, the only nonzero diagrams are those with no external lines. In particular, there will be 'disconnected' diagrams where not all vertices are connected. If you agree that the series generates all the diagrams, then the linked cluster theorem tells you that the exponential of those are the connected ones (where connected means that all vertices in the diagram are connected).
$\dagger$ Most people would call it a Dyson series.
If this is more appropriate as a comment, feel free to move/remove it. I haven't posted enough to comment yet.


text:
Q: Making IKImageView aware of my custom NSImageRep In my application, I've written a custom NSImageRep to handle a proprietary image format. The application's primary view is an IKImageView, which I intend to load the images I've made the custom NSImageRep for into for viewing and manipulation.
If I create a CGImageRef of these images and then pass the reference over to the image view it works fine, but this is not ideal. If possible, I'd like to make use of IKImageView's setImageWithURL: method, as this is mentioned as being the preferred method by the docs, plus it's just cleaner. Unfortunately the view seems entirely ignorant of my NSImageRep and simply fails to load the image.
Is there anything that can be done to make the image view understand custom representations?

A: I think you need to call NSImageRep's registerImageRepClass: sometime early in your app's startup.
I'm fairly sure you also need to implement imageUnfilteredTypes in your sub-class
From: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSImageRep_Class/Reference/Reference.html#//apple_ref/occ/clm/NSImageRep/registerImageRepClass:


text:
Q: how to allow empty in a JFormattedTextField in java? (i'm sry if i make english mistake my native language is french) for a university project i've to make a little software, the user need to inmput a number, it's why i used a  JFormattedTextField, but i also need to allow an empty field and i don't know how to do it, if someone is kind enought to help me i would be more than happy.
the code that i use:
    NumberFormat format = NumberFormat.getInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);
    textID = new JFormattedTextField(formatter);

I find this here JFormattedTextField problem

final JFormattedTextField field = new JFormattedTextField(NumberFormat.getInstance()) {
@Override
protected void processFocusEvent(final FocusEvent e) {
    if (e.isTemporary()) {
        return;
    }

    if (e.getID() == FocusEvent.FOCUS_LOST) {
        if (getText() == null || getText().isEmpty()) {
            setValue(null);
        }
    }
    super.processFocusEvent(e);
}};

but i don't know to use it so i try to create my own version with my knowledge in class
class JFormattedTextFieldCorrected extends JFormattedTextField{
public JFormattedTextFieldCorrected(NumberFormatter formatter) {
    super(formatter);
}

@Override
protected void processFocusEvent(final FocusEvent e) {
    if (e.isTemporary()) {
        return;
    }

    if (e.getID() == FocusEvent.FOCUS_LOST) {
        if (getText() == null || getText().isEmpty()) {
            setValue(null);
        }
    }
    super.processFocusEvent(e);
}}

of course i changed JFormattedTextField by JFormattedTextFieldCorrected but i didn't manage to make it work.
Have a nice day.
[edit this is a minimal reproductible exemple, to use it just enter a random number and try to erase it]
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.NumberFormatter;

public class MinimalExempleTextFormat extends JFrame{
    private JFormattedTextField textID;
    public MinimalExempleTextFormat() {
        NumberFormat format = NumberFormat.getInstance();
        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setValueClass(Integer.class);
        formatter.setAllowsInvalid(false);
        formatter.setCommitsOnValidEdit(true);
        getContentPane().setLayout(null);
        textID = new JFormattedTextField(formatter);
        textID.setBounds(208, 0, 226, 261);
        getContentPane().add(textID);
        this.setSize(500,500);
    }
    public static void main(String[] args) {
        MinimalExempleTextFormat m=new MinimalExempleTextFormat();
        m.setVisible(true);
    }
}

[edit i find a way to avoid this problem]


text:
Q: Prove that $\int \vert \ \vert f_n\vert-\vert f_n-f\vert^p -\vert f\ \vert \ \vert d\mu \to 0$, if $\sup_n\vert f_n \vert\leq C$
Let $f_n\in L(\mu)$, $1\leq p<\infty$ be such that $\exists C>0$ such that $\sup_n \vert f_n \vert^p\leq C$ and also $f_n\to f$. So prove that if $n\to\infty$, then $$\int \vert \ \vert f_n\vert-\vert f_n-f\vert^p -\vert f\ \vert \ \vert d\mu \to 0$$

Since the integrand is a positive functions, I tried to use Fatou's Lema for prooving something like $\lim \sup \int \cdots d\mu =0$, but wasn't successeful.
Searching I little more, I found something similar on "Lieb and Loss - Analysis" pg.21

I could understand (or almost could) this proof, but I found it too "tricky" and maybe there is another diffrent way...
But also about this proof... I couldn't link the hypothesis of this theorem with my question, is there something missing? If $\mu(X)<\infty$ I could do $\vert f_n \vert^p \leq \sup \vert f_n \vert ^p \leq C \implies \int \vert f_n \vert ^pd\mu < C\mu(X)<\infty$ ... otherwise I couldn't.
There are some steps of this proof that I couldn't get too, if anyone could give me hints of how to proceed by another way I'd be grateful!

A: What you are claiming:

Let $f_n\in L(\mu)$, $1\leq p<\infty$ be such that $\exists C>0$ such that $\sup_n \vert f_n \vert^p\leq C$ and also $f_n\to f$. So prove that if $n\to\infty$, then $$\int \vert \ \vert f_n\vert-\vert f_n-f\vert^p -\vert f\ \vert \ \vert d\mu \to 0$$

is in fact not true!
For a simple counter-example, take Lebesgue measure on $\mathbb R$, and consider $f_n(x) = c \, 1_{[n,n+1]}(x)$ for some $c>0$. Then $f_n \to f(x) := 0$, and $f_n$ is uniformly bounded in the sup-norm. Furthermore,
$$
\int_\mathbb{R} ||f_n|-|f| - |f_n-f|^p|= \int_\mathbb{R} |c - c^p| \, 1_{[n,n+1]} = |c-c^p|>0,
$$
if $p\ne 1$ and $c\ne 1$...
Maybe you made a mistake when copying this question?


text:
Q: Cant See Syntax Error with PHP Code I'm new to php and I don't know what why I get a syntax error.
I checked over and over but I can't find where I went wrong!

Parse error: syntax error, unexpected '$string' (T_VARIABLE) in D:\xampp\htdocs\password\generator.php on line 12

   <?php
    $lower= implode( range('a','z'));
    $upper=implode( range('A','Z'));
    $number= implode(range('0','9'));
    $symbols= '$*?!-';
    $char = $lower.$upper.$number.$symbols;

    //echo $char2;
    //echo rand(1,6);
    function random_char($string){
      $i = mt_rand (0, strlen($string)-1);
      retrun $string[$i];
    }
    echo random_char($char);

    $length=8;
    $output='';
    for($i =0; $i<$length; $i++){
      $output .= random_char($char);
    }
    echo $output;

    ?>

A: You had simple typo on return line:
<?php
    $lower= implode( range('a','z'));
    $upper=implode( range('A','Z'));
    $number= implode(range('0','9'));
    $symbols= '$*?!-';
    $char = $lower.$upper.$number.$symbols;

    //echo $char2;
    //echo rand(1,6);
    function random_char($string){
      $i = mt_rand (0, strlen($string)-1);
      return $string[$i];
    }
    echo random_char($char);

    $length=8;
    $output='';
    for($i =0; $i<$length; $i++){
      $output .= random_char($char);
    }
    echo $output;

    ?>


text:
Q: [ExtendScript]Change font color, size of certain word in text layer I want replace font color and weight and size of certain word in text layer.
For example:
I want THIS look different
 and this as well.

My plan was replacing every characters' color between  and  then "" and "" to be removed.
First of all, I'd like to know that changing colors and size of certain words in a text layer would even be feasible.
Another thing is, even if I somehow manage to change font color in a text layer and then remove  and , font colors change back to what it was before. To the color of first character of the layer.
function Replace132Step1(){
    var desctxt  = app.activeDocument.artLayers.getByName ("Description");
    var reg = new RegExp("(.*<\/?b>)");
    var boldColor1 = new SolidColor();
    boldColor1.rgb.hexValue= 'EE3E2E';
    //I got stuck from here. .replace doesn't seem like to work.

}

function Replace132Step2(){
    var desctxt  = app.activeDocument.artLayers.getByName ("Description");
    desctxt.textItem.contents = desctxt.textItem.contents.replace("", "");
    desctxt.textItem.contents = desctxt.textItem.contents.replace("", "");
}