text:
Q: How to copy the value of one sheet to another sheet Google sheets Script I have a customer sheet and a invoice sheet
When I go to the invoice sheet D12 and I type the invoice ID that's located in the customer sheet, then I get all the data from some vlookups.
But what I want is this:
I click on a cell in the customer sheet where the invoice number is located in that row. I activate the test1 function and the invoice number should be changed in the invoice sheet D12.
But when I run this script I get this error:

TypeError: Cannot find function setActiveSheet in object Sheet

Does anyone know how to change the invoice D12 cell?
function test1() {
  var ss = SpreadsheetApp.getActiveSheet();
  var row = ss.getActiveCell().getRow();
  var rowSource = ss.getRange(row, 8);
  ss.setActiveSheet(spreadsheet.getSheetByName('Invoice'), true);
  ss.getRange('D12').activate();
  ss.getCurrentCell().setValue(rowSource);
}

A: The code examples on https://developers.google.com/apps-script and other places use ss to hold a Class Spreadsheet object rather than a Class Sheet object.
Try replacing
var ss = SpreadsheetApp.getActiveSheet();

by
var ss = SpreadsheetApp.getActiveSpreadsheet();


text:
Q: Initial render of MTKView skewed I'm trying to adapt Apple's AVCamFilter tutorial to MacOS (it's originally for iOS) and I've become stuck on a weird issue. It does work great on iOS. Almost all of the adapted code is the identical, except for things that don't make sense to adapt, like the depth filter. I haven't been able to find any expected differences in the documentation.
Here's the adapted project so you can it for yourself and see what I'm talking about: AVCamFilterMacOS
What happens when I run is the MTKView's contents are skewed
If I resize it, it then becomes
I found that if I set the view's autoResizeDrawable = false, after I resize it seems to be fixed and stay fixed. But no matter what else I do, I can't seem to get the view to initialize to the expected state. It consistently renders skewed upon launch.
In addition, if I don't use the tutorial's RosyMetalRenderer and use its RosyCIRenderer instead, the problem remains. This suggests to me the shaders and transform logic of the metal renderer are not the source of the problem (which doesn't surprise me, since they're pretty simple passthrough type shaders).
Has anyone seen anything like this before? Any help would be appreciated. Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closure and Decorator I just discovered that decorator is one way of nesting functions and I came across this peculiar case with a concept called "closure". It basically means the nested function has access to the outter scope of an enclosing function. This looks intuitive enough till I found this piece of code as follows,
def decorator_with_arguments(function):
   "this decorator actually takes a real function as input"
    def wrapper_accepting_arguments(arg1,arg2):
        print("My arguments are: {0},{1}".format(arg1,arg2))
        function(arg1,arg2)
    return wrapper_accepting_arguments

@decorator_with_arguments
def cities(city_one,city_two):
    print("Cities I love are {0} and {1}".format(city_one,city_two))
cities("Beijing","Chicago")

The output would be as follows,
My arguments are: Bejing,Chicago
Cities I love are Bejing and Chicago

I have two questions regarding this piece of code.
First of all, isn't it amazing that the function wrapper_accepting_arguments understands that the arg1 and arg2 come from the function and print them off in a certain way before it has access to the function(arg1,arg2)? Does Python interpreter not read line by line? I understand when you apply multiple decorators to a function, say you have two @ along with a function, then the @ at the bottom gets excuted first. But within the body of a function, why it is read backwards?
The second question is that, if you delete the line of function(arg1,arg2) (as I tried to understand what it does), the output would be as follows,
My arguments are: Beijing,Chicago

as if you had never called the function of "cities" defined at the bottom. why is that?
This along with recursion works in a miraculous way. It's certainly not linear or from top down.
Thank you very much! Any pointer would be really appreciated!

A: The moment this code
@decorator_with_arguments
def cities(city_one,city_two):
    print("Cities I love are {0} and {1}".format(city_one,city_two))

gets imported, the function decorator_with_arguments is called with the function cities as parameter. This will immediately return your inner function wrapper_accepting_arguments, which will effectively replace the definition of def cities.
So when you then call cities("Beijing","Chicago"), it is actually calling that inner function wrapper_accepting_arguments with the arguments "Beijing","Chicago". This will cause My arguments are: Beijing,Chicago to be outputted followed by a call to the original definition of the cities (which was saved in the closure) resulting in Cities I love are Beijing and Chicago being printed.


text:
Q: Concatenate random element from list with user input in Python I'm writing a code that allows a user to enter a city they have been to. After the user inputs it, I want my code to return a randomly generated remark about the city from my list. However, whenever I run the code, it concatenates the user input with a random letter, which is not my intention of the code.
import random

message = "Type your city here: "

#Comments to concatenate with user input
comments = [f"what a lovely {}", f"I always wanted to visit {}", "I hope you enjoyed your trip to {}"]

#While loop for user input
while True:
   message = input(message)

   for elem in comments:
      message += random.choice(elem)

   if message == "quit":
      break

A: I assume this is what your looking for?
import random
#Comments to concatenate with user input
comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

#While loop for user input
message = None
while message != "quit":
   message = input("Type your city here: ")
   print(random.choice(comments)+message)

A: I recommend coding a function that takes the city as input then at the end returns the list. Like this
def random_quote(city):
    comments = [f"what a lovely ", f"I always wanted to visit ", "I hope you
     enjoyed your trip to "]
    comment = random.choice(comments)
    return comment + city

A: random.choice() accepts a list (take a look at the docs), Don't iterate over your comments variable, pass it to random.choice() and don't forget to replace {} with the city:
city = input('Please enter a city')

comment = random.choice(comments)

comment.replace('{}', city)

print(comment)

A: You do not need a for loop inside your while. You should always avoid while True as it is an opening for bugs. Having a break inside a loop usually marks bad programming.
You should probably read a bit about what f-string is before using it, you also don't seem to know what random.choice does since you put it into the for which gave it the messages, which it randomly took a character out of.
import random

def main():
    prompt = "Type your city here: "

    # Comments to concatenate with user input
    comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]

    usr_input = input(prompt)
    # While loop for user input
    while usr_input != 'quit':
        message = random.choice(comments) + usr_input
        usr_input = input(prompt)

if __name__ == '__main__':
    main()


text:
Q: Array, quantity of positive and negative numbers must be equal
*

*quantity of positive and negative numbers in array must be equal.

*an array mustn't contain zero.

The main issue is that array is not always consist of 50/50 of percent of positive and negative numbers.
If you can show me much simply way to code it you are welcome!
public static void main(String[] args) throws IOException {
        int array[] = new int[12];
        int positiveCounter = 0;
        int negativeCounter = 0;

        for (int i = 0; i < array.length; i++) {
            array[i] = createRandom();
            while (array[i] == 0) {
                array[i] = createRandom();
            }

            if (positiveCounter > array.length / 2) {
                array[i] = -1 * array[i];
                positiveCounter--;
                negativeCounter++;
            }
            if (negativeCounter > array.length / 2) {
                array[i] = -1 * (-array[i]);
                negativeCounter--;
                positiveCounter++;
            }

            if (array[i] > 0) {
                positiveCounter++;
            }
            if (array[i] < 0) {
                negativeCounter++;
            }
        }
        System.out.println(Arrays.toString(array));
        System.out.println("Pos: " + positiveCounter);
        System.out.println("Neg: " + negativeCounter);
    }

    static int createRandom() {
        Random random = new Random();
        int x = -10 + random.nextInt(11 - (-10));
        return x;
    }

A: The comments may lead to a very compact way to achieve your goal, but for what it is worth I'd like to explain why your code is not working as expected, and show a way that it will.
You attempt to invert the sign to keep the amount of positive and negative numbers balanced.  This will work, but you have a flaw in your code.  You must only invert the number if the current number needs to be inverted.  If you look at this code you will see it always inverts and adjusts the counters even if array[i] is negative (in which case nothing needs to be done):
if (positiveCounter > array.length / 2) {
     array[i] = -1 * array[i];   // <- This is a problem
     positiveCounter--;
     negativeCounter++;
}

To follow should fix your issue; the inversion is only done as needed:
for (int i = 0; i < array.length; i++) {
        array[i] = createRandom();
        while (array[i] == 0) {
            array[i] = createRandom();
        }
        if (positiveCounter >= array.length / 2 && array[i] > 0) {
            array[i] = array[i] * -1;   // Force the number to be negative
        }
        if (negativeCounter >= array.length / 2 && array[i] < 0) {
            array[i] = array[i] * -1;   // Force the number to be positive
        }
        if (array[i] > 0) {
            positiveCounter++;
        }
        if (array[i] < 0) {
            negativeCounter++;
        }
 }


text:
Q: Alternatives to the Matrix Exponential The exponential of the matrix $At$ is related to linear systems of ordinary differential equations. It is given by the concise yet apparently somewhat arbitrary formula $e^{At} = Y(t)Y(0)^{-1}$, where the order of operations between inverting the second $Y$ and evaluating it at $0$ doesn't matter.
Oftentimes in linear algebra, there are multiple ways to view basic operations (column and row approaches to multiplication), or multiple ways operations could be defined, with one arbitrary choice being declared correct.  Do expressions similar to the actual $e^{At}$ formula such as $$Y(0)Y(t)^{-1}$$$$Y(t)^{-1}Y(0)$$$$Y(0)^{-1}Y(t)$$ relate to the ODE system as well, or is there something special about the actual formula that conveys informations about the system?

A: I do not think you define the exponential of a matrix via systems of equations (although that is possible of course). You define it independently of any ODE as a series
$$
e^A=I+A+\frac{A^2}{2!}+\dots
$$
which is convergent for any matrix $A$. Then you prove some basic properties of this function and, in particular, you prove that
$$
\frac{d}{dt}e^{At}=Ae^{At}
$$
a property that is telling you that $e^{At}x_0$ is a solution of the differential system $x'=Ax$, and all you need to adjust is the initial value, so you need $x_0=x(0)$. In other words,
$$
x(t)=e^{At}x(0),
$$
or, for any  system of solutions $Y(t)$ (in particular for the fundamental system),
$$
Y(t)=e^{At}Y(0)
$$
from which your relation follows. But I do not think the distinction between representations as $Y(t)Y^{-1}(0)$ and similar ones is relevant.

A: First,there is no ncessary connection between systems of differential equations and the matrix exponential. Whenever I taught a course in linear algebra that had solving systems of differential equations as an application of diagonalization by similarity, I avoided getting into matrix exponentials, which seemed, to my purely subjective view, to be an unnecessarry red herring.  Second, the power series definition for the exponential function of anything works perfectly well over an arbitrary real or complex Banach algebra, in particular for a square real or complex matrix. Then the formulae for the exponential of a sum works fine for two commuting matrices and the differential equations formula is an easy consequence of the definitions. So, my opinion is :Keep the ideas separate at first and bring them together as a delightful bonus!


text:
Q: azure data factory compression limits I'm going to prepare some export functionality from blob storage. For this I'd like to use azure data factory (ADF) where I will use copy activity with target data set blob storage using zip compression. I just can't find some information on how big that target zip file could be. In my case it's something between few hundreds of MB to few hundreds of GB. Is there some documentation or does someone have experiences with creating huge (>100GB) zip files with ADF?

A: Data Factory is designed to scale to handle petabytes of data.
However, Limit for payload size doesn't relate to the amount of data you can move and process with Azure Data Factory.
To know more about Azure Data Factory limits you can refer documentation


text:
Q: React: Convert HOC const to component I am using React Google Maps to add Google Maps to my page, and I am setting up the map here:

import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";

export const MapWithMarkers = withScriptjs(withGoogleMap((props) =>
  <GoogleMap
    defaultZoom={17}
    center={{ lat: parseFloat(props.lat), lng: parseFloat(props.long) }}
  >
    {props.markers.map(marker => (
        <Marker
          key={marker.todoId}
          position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
        />
    ))}
  </GoogleMap>
))

However, I would like to inject a store and use this.props.store.lat rather than props.lat, using @inject('store'), which requires MapWithMarkers to be turned into a class instead of the const.
I have tried the following:

import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";

@inject('store') @observer
export class MapWithMarkers extends React.Component {
  static propTypes = {
    store: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props);
  }

  renderMarkers = (props) => {
    <GoogleMap
      defaultZoom={17}
      center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
    >
      {this.props.store.todos.map(marker => (
        <Marker
          key={marker.todoId}
          position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
        />
      ))}
    </GoogleMap>
  }

  render() {
    const props = this.props;
    return withScriptjs(withGoogleMap(this.renderMarkers()));
  }

}

This is not working, returning:

Uncaught (in promise) Error: MapWithMarkers.render(): A
  valid React element (or null) must be returned. You may have returned
  undefined, an array or some other invalid object.

What am I doing wrong?

A: withScriptjs & withGoogleMap are HOC, you should pass a HOC a component. So your component should look something like this:
import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";

@inject('store') @observer
export class Map extends React.Component {
  static propTypes = {
    store: PropTypes.object.isRequired,
  }

  render() {
    return <GoogleMap
      defaultZoom={17}
      center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
    >
      {this.props.store.todos.map(marker => (
        <Marker
          key={marker.todoId}
          position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
        />
      ))}
    </GoogleMap>
  }

}

export const MapWithMarkers = withScriptjs(withGoogleMap(Map))


text:
Q: Slide list items off screen and loop back in jquery I am trying to animate logos on the bottom of a site. I want them to disappear of the left side of the screen and then loop around and reappear on the right side of the screen. Similar to a ticker but without the dead white space at the end. I can make it almost work in jsfiddle (except it tweaks out when I adjust the screen size) and it doesn't work in my actual project at all.
http://jsfiddle.net/yoda_wookie/jm7w0jf8/1/
$(function(){
    var scroller = $('#logo-ticker div.footer-logo-slider');
    var scrollerContent = scroller.children('ul');
    scrollerContent.children().clone().appendTo(scrollerContent);
    var curX = 0;
    scrollerContent.children().each(function(){
        var $this = $(this);
        $this.css('left', curX);
        curX += $this.outerWidth(true);
    });
    var fullW = curX / 2;
    var viewportW = scroller.width();

    // Scrolling speed management
    var controller = {curSpeed:0, fullSpeed:2};
    var $controller = $(controller);
    var tweenToNewSpeed = function(newSpeed, duration)
    {
        if (duration === undefined)
            duration = 600;
        $controller.stop(true).animate({curSpeed:newSpeed}, duration);
    };

    // Pause on hover
    scroller.hover(function(){
        tweenToNewSpeed(0);
    }, function(){
        tweenToNewSpeed(controller.fullSpeed);
    });

    // Scrolling management; start the automatical scrolling
    var doScroll = function()
    {
        var curX = scroller.scrollLeft();
        var newX = curX + controller.curSpeed;
        if (newX > fullW*2 - viewportW)
            newX -= fullW;
        scroller.scrollLeft(newX);
    };
    setInterval(doScroll, 20);
    tweenToNewSpeed(controller.fullSpeed);
});

I'm still learning jQuery and really struggling with this. Any help would be greatly appreciated :)


text:
Q: how to send dictionary json key value pairs from C# Socket Client to python socket server I am trying to send data to Python via C# client. My code works for sending a string  from c# client to python server . But how to send dictionary key value pairs from and c# client to python server .
For reference i am using the below code
This is my c# client
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

// State object for receiving data from remote device.
public class StateObject
{
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    // The port number for the remote device.
    private const int port = 11000;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[2];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client, "This is a test<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Send(Socket client, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main(String[] args)
    {
        StartClient();
        return 0;
    }
}

AND below is my python server which receives the string . But how to send dictionary key value from C# client to python socket server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host=socket.gethostname()
port=7634
s.bind((host,port))
s.listen(1)
connection, client_address = s.accept()
while True:
  frames= connection.recv(6000)
  data_receive=frames.decode()
  print(data_receive)

How to modify the C# code for sending a key value pairs and how to fetch that in python
foreg {"company":"abc","id":1}
Thanks in advance


text:
Q: how to sort results from full text search query I'm testing the fulltext search python api of Google App Angine.
The api search engine works fine, but I could not manage to get ordered results, following the basic steps described at: https://developers.google.com/appengine/docs/python/search/sortexpressionclass
The search function is really simple, but sort_options does not look to make any difference
    def FindDocuments(self, query_string, limit):
    try:
        sort_options=search.SortOptions(expressions=[search.SortExpression(expression='comment', default_value='',direction=search.SortExpression.ASCENDING)])
        query_options = search.QueryOptions(limit=limit,sort_options=sort_options)
        query_obj = search.Query(query_string=query_string, options=query_options)
        return search.Index(name=_INDEX_NAME).search(query=query_obj)
    except search.Error:
        logging.exception('Search failed')
    return None

Searching for the word 'item' the result set are always unsorted:
item 4
item 3
item 1
item 2

All document items are proper returned, but never sorted.
It only works if I code the function to sort the results object:
results = sorted(results, key=lambda k: k.order_id)

But It does not looks to be the proper way once the sort is already an argument of the query object.
I would thanking you all for any sort of clue.

A: Are you trying this on your local dev server? According to this ticket the direction functionality doesn't work locally but should work as expected when deployed.


text:
Q: I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly? My NSArray contains 100, 110, 91, 98, and 87, all NSStrings.
I'd like to sort them to show up in this order: 87, 91, 98, 100, 110.
Instead they are showing up as 100, 110, 87, 91, 98.
I can't start the array with all ints instead of strings unfortunately. Anyone have any ideas on how to tell if the array contains ONLY numbers from strings, maybe using a for loop? Then I could just convert them all to ints within the array and do the sort that way. Or maybe there is an easy way I am missing?
Let me know if anyone has any ideas.

A: You can use the NSNumericSearch option to the NSString compare function to sort strings numerically. To do this with an NSArray, you will need to write a block or function to call the compare:options: method.
NSArray *theStrings; // Contains strings, some of which are numbers
NSArray *theSortedStrings = [theStrings sortedArrayUsingComparator:^(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];

This will also sort numerically if there is a numer within a string, i.e. "abcd89" will come before "abcd123".

A: There are a whole mess of options for sorting an array; that isn't really the problem.
The sort methods always put the objects in order. The order is up to the objects, or to you.
So what you need to do is one of the following:

*

*Get the strings to compare themselves numerically.

*Get the array to ask you to compare them, then compare them numerically.

Door number one is a trick and a half. NSString and the other class clusters don't let you inherit implementations; you can make your own string class, but you'd basically need to do everything from scratch (or wrap a string within a string and forward every message except compare: to it).
Door number two is much easier. Nearly every one of the sort methods takes either a block or a function, which you implement; either way, the block/function takes two of the objects from the array, compares them, and returns the order they're in.
Your block/function should send a compare:options: message to one of the two strings it receives, passing the NSNumericSearch option, and return the result.
With NSArray asking you how the strings compare and you asking the strings how they compare numerically, the array will then sort its objects in numeric order.


text:
Q: PyQGIS Composer Map size/bounding box problem SVG I expect the following code to find the bounding box around feature (which is the magenta polygon in the picture) and render that so that the height is 1000px. The white background is indeed the bounding box of the feature but it's smaller than 1000px, on a bigger gray background, and the whole SVG is still larger; moreover, features outside the bounding box are drawn.
How do I draw the exact extent I want, at an exact specified extent?
from PyQt4.QtSvg import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *

layers = QgsMapLayerRegistry.instance().mapLayers()
for layer_name, layer in layers.items():
    if 'regions' in layer_name:
        break

feature = next(layer.getFeatures(QgsFeatureRequest(4)))
region_name = feature.attribute('regionname')
region = feature.geometry()
bb = region.boundingBox()

renderer = iface.mapCanvas().mapRenderer()

c = QgsComposition(renderer)
c.setPlotStyle(QgsComposition.Print)

composerMap = QgsComposerMap(c, 0, 0, 1000, 1000)
composerMap.setNewExtent(bb)
c.addItem(composerMap)

print (composerMap.rect().width(),composerMap.rect().height())
print composerMap.extent().toRectF()

c.setPaperSize(composerMap.rect().width(),composerMap.rect().height())

svg = QSvgGenerator()
svg.setFileName("/tmp/mwe.svg")
svg.setSize(QSize(composerMap.rect().width(),composerMap.rect().height()))
svg.setTitle(region_name)

painter = QPainter(svg)
c.render(painter)
painter.end()


text:
Q: Switch From Activity to Navigation drawer activity I use Activity in my main Activity. and I would like to go from my main Activity to navigation drawer activity by clicking button on my main intent.
I created navigation drawer from navdrawer-wizard in android studio.
But i got an error when i click the button.
I use Api level 10. Android support Library v7,v4 is also inside my project.
I use Android studio.
i've debugged that issue it tigger the start activity But it gots and error in logcat like this.
java.lang.RuntimeException: Unable to start activity     ComponentInfo{www.epicmyanmar.com.andropos/www.epicmyanmar.com.andropos.MyActivity}:     android.view.InflateException: Binary XML file line #24: Error inflating class fragment

Any help or any suggestion would be appricieate
`
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
`    `<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="www.epicmyanmar.com.andropos.MyActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    `enter code here`<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->
    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        class="www.epicmyanmar.com.andropos.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>`

A: I got solutions By my self
Ker p peg is right.I found error in styles.xml .
Now i modified the style. normal Style for normal Activity.
and Nav-drawer style for Navdrawer activity.
Thanks every one


text:
Q: At What Point Does Mass Cease to Matter? I know very little about physics so I naturally have a lot of simple minded questions.
Assuming I am piloting a rocket and want to obtain the fastest speed possible.

*

*At what point does mass more or less cease to influence drag/retrograde effects on the rocket?

*When I am "out of" (more or less free from) the gravity well of the Earth?

*Or maybe it is minimal as long as I am outside of the atmosphere?

A: *

*Mass affects the acceleration through $f=ma$, The higher the mass, the lower the acceleration for a given force. Drag is not affected by mass, only by the speed and the density of the atmosphere. Mass never ceases to influence the rocket's behaviour. Any change in speed or direction (i.e. any change in velocity) is affected by mass through the above formula.

*You are never out of the gravity well of earth, it stretches  infinitely far. However, if you go more than $11km/s$ directly away from earth, you will continue to move away from it to infinity. This assumes there are no other bodies present: $11km/s$ certainly will not let you escape the sun. In other words, you will stay in the solar system.

*Not sure what you mean by "it is minimal". Mass and gravitation are  not affected by the atmosphere at all - drag is, of course. Mass always stays the same, gravitational force (from the earth) reduces as you move further from the earth.

A: Simple questions are good questions, and often do not have simple answers.
Gravity will always effect your rocket, although if you're far away enough from the gravity's source it may be negligible (not noticeable to you). So how far is "enough"? It depends on your limit of precision. Suppose you were making a trip that took 10 days, and you wanted to get there +- 1 meter, then you can neglect velocities that are smaller than 1/10 m days$^{-1}$. You can then neglect accelerations that are smaller than 1/100 m days$^{-2}$, and thus forces that are smaller than $m_{rocket}$/100 kg m days$^{-2}$. You can then use this to find the distance from the gravity source at which the force is smaller than your limit, by rearranging Newtons law of gravity for r.
$$
F = \frac{GMm}{r^2}, r = +\sqrt\frac{GMm}{F} = + \sqrt\frac{GM}{a}
$$
E.g. For Earth (M = 5.972 × 10$^{24}$ kg) and a space shuttle with a mass of 2000 tons like discovery, r works out as
$$
r = \sqrt \frac{ 6.674×10^{−11} * 5.972 × 10^{24}}{1/(100*24*60*60)} = 5.87 × 10^{10}m
$$
For a sense of scale, the distance from the earth to the sun is 1.496 × 10$^{11}$m.
N.B. In reality, there will be so many more sources of gravity and error that you'll want a much higher precision.


text:
Q: Android Actionbar Tabs + Fragments + Service So, I have 2 problems with my code:
1) I want that each tab saves its state. So that a TextView shows changed text if it was changed.
2) I can't correctly connect/bind and unbind service to Fragment

Text must be changed from Service.

Please help, I don't know how I realize my intent.

MyActivity.java
package com.example.tabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MyActivity extends Activity {

    private static String ACTION_BAR_INDEX = "ACTION_BAR_INDEX";

    private Tab tTab1;
    private Tab tTab2;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private TabListener<Tab1> tab1Listener;
    private TabListener<Tab2> tab2Listener;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {

                }
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        myServiceIntent = new Intent(this, MyService.class);
        bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
        if (!isServiceRunning()) {
            startService(myServiceIntent);
        }

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);

        tTab1 = actionBar.newTab();

        tab1Listener = new TabListener<Tab1>(this, R.id.fl_main, Tab1.class);

        tTab1.setTag("Tab_1");
        tTab1.setText("Tab_1");
        tTab1.setTabListener(tab1Listener);

        tTab2 = actionBar.newTab();

        tab2Listener = new TabListener<Tab2>(this, R.id.fl_main, Tab2.class);

        tTab2.setTag("Tab_2");
        tTab2.setText("Tab_2");
        tTab2.setTabListener(tab2Listener);

        actionBar.addTab(tTab1, 0);
        actionBar.addTab(tTab2, 1);
    }

    public boolean isServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (MyService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbindService(myConnection);
        stopService(myServiceIntent);
    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {

        private Fragment fragment;
        private Activity activity;
        private Class<T> fragmentClass;
        private int fragmentContainer;

        public TabListener(Activity activity, int fragmentContainer, Class<T> fragmentClass) {

            this.activity = activity;
            this.fragmentContainer = fragmentContainer;
            this.fragmentClass = fragmentClass;
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            if (fragment != null) {
                ft.attach(fragment);
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (fragment == null) {
                String fragmentName = fragmentClass.getName();
                fragment = Fragment.instantiate(activity, fragmentName);
                ft.add(fragmentContainer, fragment, fragmentName);
            } else {
                ft.attach(fragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (fragment != null) {
                ft.detach(fragment);
            }
        }

    }

}

MyService.java
package com.example.tabs;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MyService extends Service {

    private final IBinder myBinder = new MyBinder();
    private static Handler myServiceHandler;

    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    public void sendMessage(String sText, int id) {

        Bundle bundle = new Bundle();
        bundle.putString("Text" + id, sText);
        Message bundleMessage = new Message();
        bundleMessage.setData(bundle);

        myServiceHandler.sendMessage(bundleMessage);
    }

    public class MyBinder extends Binder {

        public MyService getService() {
            return MyService.this;
        }

        public void setCallbackHandler(Handler myActivityHandler) {
            myServiceHandler = myActivityHandler;
        }

        public void removeCallbackHandler() {
            myServiceHandler = null;
        }
    }
}

Tab1.java
package com.example.tabs;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Tab1 extends Fragment {

    public static String TAG = Tab1.class.getClass().getSimpleName();

    private static TextView tvText;
    private EditText editText;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {
                    tvText.setText(text);
                }
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab1, container, false);

        tvText = (TextView) view.findViewById(R.id.tv_tab1);

        editText = (EditText) view.findViewById(R.id.editText1);

        Button btn1 = (Button) view.findViewById(R.id.btn_change_text_1);

        btn1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                myService.sendMessage(String.valueOf(editText.getText()), 1);
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        myServiceIntent = new Intent(activity, MyService.class);
        activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {

        super.onDetach();

        getActivity().unbindService(myConnection);
    }
}

Tab2.java
package com.example.tabs;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Tab2 extends Fragment {

    public static String TAG = Tab2.class.getClass().getSimpleName();

    private static TextView tvText;
    private EditText editText;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {
                    tvText.setText(text);
                }
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab2, container, false);

        tvText = (TextView) view.findViewById(R.id.tv_tab2);

        editText = (EditText) view.findViewById(R.id.editText2);

        Button btn2 = (Button) view.findViewById(R.id.btn_change_text_2);

        btn2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                myService.sendMessage(String.valueOf(editText.getText()), 2);
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        myServiceIntent = new Intent(activity, MyService.class);
        activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {

        super.onDetach();

        getActivity().unbindService(myConnection);
    }

}

main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical" >
    <FrameLayout
    android:id="@+id/fl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

</LinearLayout>

tab1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_change_text_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Change text" />

    <TextView
        android:id="@+id/tv_tab1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TAB1\nTAB1\nTAB1" />

</LinearLayout>

tab2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_change_text_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Change text" />

    <TextView
        android:id="@+id/tv_tab2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="TAB2\nTAB2\nTAB2" />

</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tabs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="TabsPlusService"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name="com.example.tabs.MyActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="TabsPlusService"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true" >
        </service>
    </application>

</manifest>

A: so, i get it :)
1) remove all service code from activity
MainActivity.java
package com.example.tabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MyActivity extends Activity {

    private Tab tTab1;
    private Tab tTab2;

    private TabListener<Tab1> tab1Listener;
    private TabListener<Tab2> tab2Listener;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);

        tTab1 = actionBar.newTab();

        tab1Listener = new TabListener<Tab1>(this, "tab1", Tab1.class);

        tTab1.setTag("Tab_1");
        tTab1.setText("Tab_1");
        tTab1.setTabListener(tab1Listener);

        tTab2 = actionBar.newTab();

        tab2Listener = new TabListener<Tab2>(this, "tab2", Tab2.class);

        tTab2.setTag("Tab_2");
        tTab2.setText("Tab_2");
        tTab2.setTabListener(tab2Listener);

        actionBar.addTab(tTab1, 0);
        actionBar.addTab(tTab2, 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {

        private Fragment mFragment;
        private Activity activity;
        private Class<T> mFragmentClass;
        private String mTag;

        public TabListener(Activity activity, String mTag, Class<T> fragmentClass) {

            this.activity = activity;
            this.mFragmentClass = fragmentClass;
            this.mTag = mTag;
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.attach(mFragment);
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(activity, mFragmentClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.detach(mFragment);
            }
        }

    }

}

2) add service code to tab1.java & tab2.java
Tab1.java
 package com.example.tabs;

    import android.app.ActivityManager;
    import android.app.ActivityManager.RunningServiceInfo;
    import android.app.Fragment;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class Tab1 extends Fragment {

        public static String TAG = Tab1.class.getSimpleName();

        private static TextView tvText;
        private EditText editText;

        private static MyService.MyBinder myBinder;
        private static Intent myServiceIntent;
        private static MyService myService;

        private static ServiceConnection myConnection = new ServiceConnection() {

            public void onServiceConnected(ComponentName name, IBinder binder) {
                myBinder = (MyService.MyBinder) binder;
                myService = myBinder.getService();
                myBinder.setCallbackHandler(myServiceHandler);
            }

            public void onServiceDisconnected(ComponentName name) {
                myService = null;
                myBinder = null;
            }
        };

        /** Callbackhandler. */
        private static Handler myServiceHandler = new Handler() {

            public void handleMessage(Message message) {

                super.handleMessage(message);

                Bundle bundle = message.getData();

                if (bundle != null) {
                    String text = bundle.getString("Text1", "");

                    if (!text.equals("")) {
                        tvText.setText(text);
                    }
                }
            }
        };

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab1, container, false);

            tvText = (TextView) view.findViewById(R.id.tv_tab1);

            editText = (EditText) view.findViewById(R.id.editText1);

            Button btn1 = (Button) view.findViewById(R.id.btn_change_text_1);

            btn1.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    myService.sendMessage(String.valueOf(editText.getText()), 1);
                }
            });

            return view;
        }

        public void onResume() {
            super.onResume();
            myServiceIntent = new Intent(getActivity(), MyService.class);
            getActivity().bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
            if (!isServiceRunning()) {
                getActivity().startService(myServiceIntent);
            }
        }

        public void onPause() {
            super.onPause();
            getActivity().unbindService(myConnection);
        }

public void onDestroy() {
    super.onDestroy();

    if (isServiceRunning()) {
        getActivity().stopService(myServiceIntent);
    }

}

        public boolean isServiceRunning() {
            ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
            for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (MyService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
            return false;
        }
    }

Tab2.java looks similarly


text:
Q: angularjs - ui-router multiple nested views Trying to figure out multiple nested views concept and don't seem to understand what I'm doing wrong.
app.js routing config :
.config(function($stateProvider, $locationProvider, $urlRouterProvider) {
    'ngInject';

    $stateProvider.state('home', {
         url: '/',
         templateUrl: 'tpls/views/welcome.html'
    })
    .state('feeds', {
        url: '/feeds',
        views: {
            'main': {
                templateUrl: 'tpls/views/main.html'
            },
            'siderbar@feeds' : {
                templateUrl: 'tpls/views/sidebar.html',
                controller: 'MyCtrl',
                controllerAs : 'main'
            },
            'mainfeed@feeds': {
                templateUrl: 'tpls/views/mainfeed.html',
                controller: 'MyCtrl',
                controllerAs : 'main'
            }
        }
    });
    $urlRouterProvider.otherwise('/');
    $locationProvider.html5Mode(true);
});

HTMLs:
on index.html I have an an empty directive

and this is main.html :

My views arent rendering. When in /feeds I only see the background.
Can you please help me spot the problem?
Went over the github documentation and still couldn't infer the solution.
Thanks!

A: Make sure that base page index.html should have named view main.

If main named view isn't there then, you could have '' in your base view of feeds like below.
Code
.state('feeds', {
    url: '/feeds',
    views: {
        //used blank to target unnamed `ui-view` placed on html
        '': {
            templateUrl: 'tpls/views/main.html'
        },
        'siderbar@feeds' : {
            templateUrl: 'tpls/views/sidebar.html',
            controller: 'MyCtrl',
            controllerAs : 'main'
        },
        'mainfeed@feeds': {
            templateUrl: 'tpls/views/mainfeed.html',
            controller: 'MyCtrl',
            controllerAs : 'main'
        }
    }
});

A: This is how the syntax look like for Nested views. Please cross check with your
Syntax.
Note : This one is third party so we used ui.router.stateHelper
angular.module('myApp', ['ui.router', 'ui.router.stateHelper'])
  .config(function(stateHelperProvider){
    stateHelperProvider.setNestedState({
      name: 'root',
      templateUrl: 'root.html',
      children: [
        {
          name: 'contacts',
          templateUrl: 'contacts.html',
          children: [
            {
              name: 'list',
              templateUrl: 'contacts.list.html'
            }
          ]
        },
        {
          name: 'products',
          templateUrl: 'products.html',
          children: [
            {
              name: 'list',
              templateUrl: 'products.list.html'
            }
          ]
        }
      ]
    });
  });

visit this more details..https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views


text:
Q: Nan in loss of keras Resnet-50 The validation loss was nan, but training loss is fine.
How could i solve it?
I've confirmed that there is no nan value in dataset.
from tensorflow import keras

base_model = keras.applications.resnet50.ResNet50(include_top = False, weights='imagenet')

for layer in base_model.layers:
    layer.trainable = False

avg = keras.layers.GlobalAveragePooling2D(name="global_avg")(base_model.output)
output = keras.layers.Dense(1, activation = 'sigmoid', name = "predictions")(avg)
model = keras.Model(inputs = base_model.input, outputs = output, name = "ResNet-50")

optimizer = keras.optimizers.SGD(lr=0.01, momentum=0.9, decay=0.0001, clipnorm = 0.1)
reduce_LROP = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto',
    min_delta=0.0001, cooldown=0, min_lr=0)
model.compile(loss=tf.keras.losses.BinaryCrossentropy(), optimizer = optimizer, metrics = ['accuracy'])

history = model.fit(tri, y_train, epochs = 10, batch_size = 32, validation_data = (vai, y_val),
                    callbacks = [reduce_LROP])

A: I bought GIGABYTE RTX 3080 gaming oc 10GB for deep learning and used it to train a model.
I tested the same script with 4 environments:

*

*3700x + RTX 3080 (CUDA 10.1)

*3700x only (no GPU)

*Other laptop (i7 8750H + GTX 1050ti)

*3700x + RTX 3080 (CUDA 11.0 + cudnn 8.0.3)

The validation loss was fine except for the 1st environment.
Using Tensorflow nightly build and CUDA 11.0 solved the issue in my case.


text:
Q: Attributes not showing to choose in woocommerce At my product page, when I go to Product Data, select "Variable product" and then click on "Variations" I get the message, "Before adding variations, add and save some attributes on the Attributes tab."
enter image description here
So… I went to the Attributes tab, created an attribute titled 'Colors', and 'Size'.
enter image description here
With those saved, I went back to my saved product, went back to "Product Data", selected "Variable product" and clicked on, "Variations"
But there I again see that message "Before adding variations, add and save some attributes on the Attributes tab.".

A: After you've added your global attributes (Products › Attributes), you still need to select those attributes from the Attributes tab on the product edit page. You'll then be able to set up variations for a product.

*

*Go to: Products › Add Product (or edit an existing one).

*Select the Attributes tab in the Product Data. Use the dropdown menu to choose any of the global attributes that you've created.

*Select Add to make the attribute type available for variations

*Select the terms that you want to use for this product's variations (I've selected Black and White in the screenshot below).

*Check Use for variations

*Click Save attributes

*You can now set up variations within the Variations tab


text:
Q: How to detect when third party app's dialog box appears in React native? My app sends stickers to WhatsaApp and it shows a dialog box. How to wait for the user action on the dialog box and perform action after the dialog box gone.
export default function CreateScreen({route, navigation}){
    const [PreviewImages, setPreviewImages] = React.useState([]);
    const [isAnimated, setAnimated] = React.useState(false);
    const [PackName, setPackName] = React.useState(Date.now().toString());
    const [AuthorName, setAuthorName] = React.useState('');
    const [Version, setVersion] = React.useState(1);

    const context = React.useContext(AppContext);

    React.useLayoutEffect(() => {
        navigation.setOptions({
          headerRight: () => (
            <Button onPress={send} title="Create" color="#00ff00"/>
          ),
        });
    });

    const removePreview=(x)=>{
        setPreviewImages(PreviewImages.filter((i,index)=>index!==x));
    }

    const src = 'file://'+RNFS.DownloadDirectoryPath+'/'+'file10.jpg';
    const dest = 'file://'+RNFS.DownloadDirectoryPath+'/'+'file10_1.jpg';

    const send =async()=>{

        log('sending...')

        try{

            const packData = {
                authorName:AuthorName,
                packName:PackName,
                isAnimated:isAnimated,
                version:Version,
                previewImages:PreviewImages,
            }

            let jsonData = await DecoratePack(packData)

            await RNWhatsAppStickers.prepare(jsonData)
            .then(res=>res.slice(1))
            .then(str=>JSON.parse(str))
            .then(obj=>{
                log('pack ',obj['identifier'])
                return RNWhatsAppStickers.send(obj['identifier'],obj['identifier'])
            })
            .then(r2=>log(r2))
            .catch(err=>Alert.alert('Could not create pack',err.toString()))

        }catch(e){
            Alert.alert('Problem with pack',e.toString())
        }

    }

    return(
        <View style={root.main}>
            <Screen1/>
        </View>
    );
}

If I set the create button to navigate back to home screen after creatnig pack then whatsapp dialoge box will appear on home screen. It is kind of ok but dialog box is appeared to tell there is issue in pack or pack name already exist then it will be annoying for user to go to the create screen again.
Thanks for your help

A: By onActivityResult we can detect the activity of third party apps fired by your app.
You'll need to listen to onActivityResult if you want to get results from an activity you started with startActivityForResult. To do this, you must extend BaseActivityEventListener or implement ActivityEventListener.
http://reactnative.dev/docs/native-modules-android#getting-activity-result-from-startactivityforresult


text:
Q: SecurityException: Permission Denial Background
I'm working on an Android app that controls the screen rotation. The app is available on the Google Play store. To control the screen rotation, the app disables system auto rotation and changes the values of USER_ROTATION. The source code is available via Mercurial/hg.
Problem
While the app works fine on my phone, a rooted Sony Xperia M, it crashes on a friend's Samsung Galaxy S3 running Android 4.3. The crash occurs outside of my code, so I don't get a crash report in the Google Play Store, and the stack trace only shows external code that I don't have access to.

java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
at android.os.Parcel.readException(Parcel.java:1431)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.call(ContentProviderNative.java:602)
at android.provider.Settings$NameValueCache.getStringForUser(Settings.java:934)
at android.provider.Settings$System.getStringForUser(Settings.java:1162)
at android.provider.Settings$System.getIntForUser(Settings.java:1232)
at com.android.internal.policy.impl.WindowOrientationListener$ScreenOrientationEventListenerImpl.onSensorChanged(WindowOrientationListener.java:501)
at android.hardware.SystemSensorManager$SensorE

This stack trace implies that the system auto rotation is still running. It also shows the OS code is trying to read an int system setting as a particular user after receiving a screen orientation change event. So I suspect the problem is related to me disabling ACCELEROMETER_ROTATION or changing USER_ROTATION, both of which are int system settings.
Troubleshooting

*

*I checked other questions about this error. Most of them only explain what the error means without providing any solution. I couldn't find any with the exact same call stack trace.

*I checked the AOSP code for WindowOrientationListener, but it doesn't contain the inner class in which the error occurs, ScreenOrientationEventListenerImpl. The Samsung phone probably uses a custom version of the code, most likely in part because it has a non-AOSP feature, Smart Rotation.

*I don't think my code is doing any user-specific stuff; it's just using normal Android APIs.

*I tested the app on a non-rooted Sony Xperia M and a Sony Xperia Ray, and it was fine on them.

*I tested the app on 4 different Samsung Galaxy S3s using Samsung Remote Test Lab.

*I tried to find the source code where the error is occurring. I found a smali file, which at a glance indicates that it's trying to read the setting "intelligent_rotation_mode" as user -0x2, which is interesting since I'm not touching that presumably-Samsung-specific setting. I also downloaded a copy of the official source code, but it didn't seem to contain the relevant file.

A: The app was using a local copy of com.android.internal.policy.impl.WindowOrientationListener from AOSP. However, the local copy was still using the original package, com.android.internal.policy.impl. It turned out that when the app tried to use this local copy of the class, it was actually using the original system version with the same fully-qualified name. So the problem was the app was accidentally directly using the phone's built-in WindowOrientationListener.


text:
Q: VM execution error at contract simulation UMA LSP contract I am trying to deploy a smart contract on Kovan testnet with the UMA protocol. More specifically following this tutorial: https://docs.umaproject.org/developers/deploy-an-lsp
I am running the deployment script with the following parameters:
node index.js
--gasprice 15
--url wss://kovan.infura.io/ws/v3/PROJECTIDInfura
--mnemonic "SEED PHRASE"
--pairName "WHTUSDJune"
--expirationTimestamp 1655312460
--collateralPerPair 1000000000
--priceIdentifier BTCUSD
--longSynthName "wheat_SRW_June_long"
--longSynthSymbol WHTUSDBJun
--shortSynthName "wheat_SRW_June_short"
--shortSynthSymbol WHTUSDSJun
--collateralToken 0x7079f3762805cff9c979a5bdc6f5648bcfee76c8
--fpl Linear
--lowerBound 0
--upperBound 2000000000
--proposerReward 2000000
--optimisticOracleProposerBond 200000000

But this is the error I get at contract simulation:
Error: VM execution error.
    at WebsocketSubprovider._handleSocketMessage (C:\Users\FOLDER\launch-lsp\node_modules\@trufflesuite\web3-provider-engine\subproviders\websocket.js:121:18)
    at WebSocket.onMessage (C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\websocket.js:720:20)
    at Receiver.emit (events.js:315:20)
    at Receiver.dataMessage (C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\receiver.js:414:14)
    at C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\receiver.js:371:23
    at C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\permessage-deflate.js:307:9
    at C:\Users\FOLDER\launch-lsp\node_modules\ws\lib\permessage-deflate.js:389:7
    at afterWrite (_stream_writable.js:468:5)
    at onwrite (_stream_writable.js:448:7)
    at InflateRaw.afterTransform (_stream_transform.js:98:3)
    at Zlib.processCallback (zlib.js:580:8)

What I am doing wrong?

A: Found out which parameter was making my request crash. It is:
--priceIdentifier BTCUSD

I replaced it with
--priceIdentifier UMAUSD

and it worked like a charm. Not sure why as BTCUSD is listed as a price identfier on their site.


text:
Q: Extracting Elements from character vector in my set-up I have these variables:
loc <- c('anf', 'iqq', 'stg', 'ccp', 'coy', 'puq')
subDirs <- list.dirs(full.names = FALSE)

In the current directory from where I extract sub-directories names, I have some sub-directories in which I data I am interested in processing. But there are also some other sub Directories that I cannot delete because they contain other important files. The sub-dirs I am interested in have the particularity that each one starts with a "code" which can be either: anf, iqq, stg, ccp, coy, puq. Therefore, I want to extract sub-dirs names that contains those codes at the first 3 characters of subdirs name.
for (k in 1:length(subDirs)){
    if (!substr(subDirs[k], 1, 3) %in% loc & !is.na(subDirs[k])){
        subDirs <- subDirs[subDirs != subDirs[k]]
    }
}

For instance, I Have
[1] ""               "anf_b2_results" "anf_c1_results" "anf_c2_results" "anf_c3_results"
 [6] "anf_e1_results" "anf_e2_results" "iqq_b2_results" "iqq_e1_results" "iqq_e2_results"
[11] "poi_library"    "stg_b2_results" "stg_e1_results" "stg_e2_results"

I want:
[1] "anf_b2_results" "anf_c1_results" "anf_c2_results" "anf_c3_results" "anf_e1_results"
 [6] "anf_e2_results" "iqq_b2_results" "iqq_e1_results" "iqq_e2_results" "stg_b2_results"
[11] "stg_e1_results" "stg_e2_results"

I did that for extracting the names I am interested in, but is there a better (efficient, easier) way? I have the feeling that what I did is too much hardcoding and I want an efficient code, because there will be lots of sub-dirs later.
Best Regards

A: You don't need any for loops. substr is vectorized. Just do:
subDirs[substr(subDirs, 1, 3) %in% loc]
# [1] "anf_b2_results" "anf_c1_results" "anf_c2_results" "anf_c3_results" "anf_e1_results"
# [6] "anf_e2_results" "iqq_b2_results" "iqq_e1_results" "iqq_e2_results" "stg_b2_results"
# [11] "stg_e1_results" "stg_e2_results"


text:
Q: "Me neither" - why oblique case?
I don't like white wine.
Me neither.

We're talking about subjects here, so naturally the pronoun should be "I". The use of "me" would only make sense to me if "neither" was a postposition. According to a dictionary it can be all kinds of things but not a preposition.

*

*Why are we using "me" here?

*What part of speech is neither?

*Is this sentence a shortened version of something that explains the weird grammar?


text:
Q: Don't change from Edit link to Update and Cancel in gridview when bind data in code behind insteaf of in asp.net page I test the demo on link: http://csharpdotnetfreak.blogspot.com/2009/05/gridview-sqldatasource-insert-edit.html
It worked fine.
But when I get data from a function in code behind, instead of use DataSourceID="SqlDataSource1" like demo, by bind data to gridview in code behind like that:
protected void Page_Load(object sender, EventArgs e)
{
    lblMessage.Text = "";
    if (!IsPostBack)
    {
        GridView1.DataSource = MyFunctionGetData();
        GridView1.DataBind();
    }

}

When I click to Edit link in gridview, it don't change to Update and Cancel link and don't run to EditItemTemplate in debug mode like above demo.


text:
Q: how to get data from DB using axios I'm having a problem.
i have list of project i want when i click in one project he take me to another page(components) this is the component ProjectDetail when i can find the detail of that project  Inside of it, I have this block of code:
this is the route who take me to another components:
 {path: '/detail/:id', name: detail , component: detail },

I want to get the project with the id in the url detail from DB w but nothing Happen this is ProjectDetail.vue:
export default {
      data(){
      return{
      id: this.$route.params.id,
    projets:[],
   projet:{
    id:'',
   name:'',
     durre:'',
  description:'',
      budget:'',
  owner:'',
      }
   }
 },
      methods:{
    afficherProjets(){
       axios.get('api/getProjects/'+this.id)
         .then(data => {
           this.projets = data.data;
               });
                  }
           },
          mounted() {
           console.log('Component mounted.')
           this.afficherProjets();
        }
           }

and this is my controller:
 public function getProjects($id)
{
   return Projet::findOrFail($id);
}

A: in your vue.
export default {
  data(){
   return{
    id: this.$route.params.id,
    projet:{}
  }
},
methods:{
 //GETID
 afficherProjet(){
   axios.get('api/getProject/'+this.id)
      .then(data => {
              this.projet = data.data;
           });
 }
},
mounted() {
  console.log('Component mounted.')
  this.afficherProjet();
}

File in routes api.php
//ALL
Route::get('getProjects', ['uses' =>'API\ProjetController@getProjects']);
//SPECIFIQ ID
Route::get('getProject/{id}', ['uses' =>'API\ProjetController@getProject']);

In your controller, app/Http/API/ProjetController
public function getProjects()
{
   return Projet::latest()->paginate(15);
}

public function getProject($id)
{
  return Projet::findOrFail($id);
}

Your model projet
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Projet extends Model
{
   public $timestamps = false;

   protected $table = 'projets';

   protected $fillable = [
     'name',
     'durre',
     'description',
     'budget',
     'owner'
   ];
}

Do you have your model?
Your error comes from the 'data.data' i thing it's empty, you should just call 'data'.
Personally i prefer Mounted.
I thing now it's working!


text:
Q: How to unmarshal an escaped JSON string I am using Sockjs with Go, but when the JavaScript client send json to the server it escapes it, and send's it as a []byte. I'm trying to figure out how to parse the json, so that i can read the data. but I get this error.

json: cannot unmarshal string into Go value of type main.Msg

How can I fix this? html.UnescapeString() has no effect.
val, err := session.ReadMessage()
if err != nil {
break
}
var msg Msg

err = json.Unmarshal(val, &msg)

fmt.Printf("%v", val)
fmt.Printf("%v", err)

type Msg struct {
    Channel string
    Name    string
    Msg     string
}

//Output
"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"
json: cannot unmarshal string into Go value of type main.Msg

A: You might want to use strconv.Unquote on your JSON string first :)
Here's an example, kindly provided by @gregghz:
package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type Msg struct {
    Channel string
    Name string
    Msg string
}

func main() {
    var msg Msg
    var val []byte = []byte(`"{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}"`)

    s, _ := strconv.Unquote(string(val))

    err := json.Unmarshal([]byte(s), &msg)

    fmt.Println(s)
    fmt.Println(err)
    fmt.Println(msg.Channel, msg.Name, msg.Msg)
}

A: As Crazy Train pointed out, it appears that your input is doubly escaped, thus causing the issue.  One way to fix this is to make sure that the function session.ReadMessasge() returns proper output that is escaped appropriately.  However, if that's not possible, you can always do what x3ro suggested and use the golang function strconv.Unquote.
Here's a playground example of it in action:
http://play.golang.org/p/GTishI0rwe

A: You need to fix this in the code that is generating the JSON.
When it turns out formatted like that, it is being JSON encoded twice. Fix that code that is doing the generating so that it only happens once.
Here's some JavaScript that shows what's going on.
// Start with an object
var object = {"channel":"buu","name":"john", "msg":"doe"};

// serialize once
var json = JSON.stringify(object); // {"channel":"buu","name":"john","msg":"doe"}

// serialize twice
json = JSON.stringify(json); // "{\"channel\":\"buu\",\"name\":\"john\",\"msg\":\"doe\"}"

A: Sometimes, strconv.Unquote doesn't work.
Heres an example shows the problem and my solution.
(The playground link: https://play.golang.org/p/Ap0cdBgiA05)
Thanks for @Crazy Train's "encodes twice" idea, I just decoded it twice ...
package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type Wrapper struct {
    Data string
}

type Msg struct {
    Photo string
}

func main() {
    var wrapper Wrapper
    var original = `"{\"photo\":\"https:\/\/www.abc.net\/v\/t1.0-1\/p320x320\/123.jpg\"}"`

    _, err := strconv.Unquote(original)

    fmt.Println(err)

    var val []byte = []byte("{\"data\":"+original+"}")
    fmt.Println(string(val))
    err = json.Unmarshal([]byte(val), &wrapper)

    fmt.Println(wrapper.Data)

    var msg Msg
    err = json.Unmarshal([]byte(wrapper.Data), &msg)
    fmt.Println(msg.Photo)
}

A: The data shown in the problem is stringified for some purposes, in some cases you can even have \n in your string representing break of line in your json.
Let's understand the easiest way to unmarshal/deserialize this kind of data using the following example:

*

*Next line shows the data you get from your sources and want to derserialize

stringifiedData := "{\r\n  \"a\": \"b\",\r\n  \"c\": \"d\"\r\n}"

*Now, remove all new lines first

stringifiedData = strings.ReplaceAll(stringifiedData, "\n", "")

*Then remove all the extra quotes that are present in your string

stringifiedData = strings.ReplaceAll(stringifiedData, "\\"", "\"")

*Let's now convert the string into a byte array

dataInBytes := []byte(stringifiedData)

*Before doing unmarshal, let's define structure of our data

jsonObject := &struct{
  A string `json:"a"`
  C string `json:"c"`
  }

*Now, you can dersialize your values into jsonObject

json.Unmarshal(dataInBytes, jsonObject)}

A: You got into infamous escaped string pitfall from JavaScript. Quite often people face (as I did) the same issue in Go, when serializing JSON string with json.Marshal, e.g.:
in := `{"firstName":"John","lastName":"Dow"}`
bytes, err := json.Marshal(in)

json.Marshal escapes double quotes, producing the same issue when you try to unmarshal bytes into struct.
If you faced the issue in Go, have a look at How To Correctly Serialize JSON String In Golang post which describes the issue in details with solution to it.


text:
Q: Getting top 2 rows in each group without row_number() in SQL Server I am looking for a simple query to get result of 2 rows with latest invoice date in each group. Although this task can be accomplished by a row_number() that you can see in below code ,I need an alternative to this with minimum complexity.
Code :
create table #tt
(
    id int,
    invoiceDT datetime
)

insert into #tt
values(1,'01-01-2016 00:12'),(1,'01-02-2016 06:16'),(1,'01-01-2016 00:16')
    ,(2,'01-01-2016 01:12'),(2,'04-02-2016 06:16'),(2,'01-06-2016 00:16')

select *
from (
SELECT id,invoiceDT,row_number() over(partition by id order by invoiceDT desc) as rownum
FROM #tt
)tmp
where rownum <=2

I need same result that is returned by above query
Please suggest an alternative.

A: Strange request, but here you go:
WITH CTE as
(
  SELECT distinct id FROM #tt t1
)
SELECT x.*
FROM CTE
CROSS APPLY
(
  SELECT top 2 *
  FROM #tt
  WHERE CTE.id = id
  ORDER BY invoiceDT desc
) x


text:
Q: Bundling and minification of angular2 project, Js and Html Been working on an angular2 project for a while now, after updating it from angular1 (loving angular2 btw).
Now i would like to bundle the project, but unsure what is the best bundler to use?
Also i see some posts saying that they split the bundle into multiple files (like app.bundle.js and vendors.bundle.js) and others have 1 large file.  What is the best method?  I always throught that many files were better because browsers can download multiple files at the same time?
Do you need to use a gulp task for all this, or something else completely?
Also, how can i minify the HTML templates in an angular2 app?

A: You can either use Webpack or Systemjs-Builder to bundle your app. There are tons of seed projects from which you can take hints e.g. this and this and you can use this in your gulp task to inline the templates with your build.

A: Now i would like to bundle the project, but unsure what is the best bundler to use?
All answers to your questions will be subjective, but it is factual that Webpack offers plugins and configuration settings to suit your needs.
Also i see some posts saying that they split the bundle into multiple files (like app.bundle.js and vendors.bundle.js) and others have 1 large file. What is the best method?
Splitting into multiple files is definitely the most common method.  It allows you to keep your application code separated from your dependencies, which makes debugging less of a nightmare.
The part of your Webpack config file that handles this might look something like this:
  // our angular app
  entry: { 'vendor': './src/vendor.ts', 'main': './src/main.ts' },

  // Config for our build files
  output: {
    path: '',
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

Do you need to use a gulp task for all this, or something else completely?
If you use Webpack, then Gulp is not required at all.  I'd recommend just using NPM scripts.  Don't quote me on this, but I think Webpack can just flat out replace Gulp for Angular2 projects.
Also, how can i minify the HTML templates in an angular2 app?
Webpack has a HTML minify plugin for this.
You can use it like so:
loaders: [
        {
                test: /\.html$/,
                name: "mandrillTemplates",
                loader: 'raw!html-minify' // raw is another loader
        }
    ]


text:
Q: Moving from Snaps to Apt (home desktop situation) While I understand that developers maintaining versions appreciate snap functionality, home users probably won't. People install Ubuntu for home use, as a replacement of other OSs, one of the reasons might be the low-resource demand. Since I installed Ubuntu 20.04, my disk (particularly root partition) is permanently full. The offending directory being /var/lib/snapd/snaps. I have already reduced snap retention to 2 (one current, one recent), but still, the same issue with excess space usage. This may actually frustrate "regular users" who want foremost to use their PC for some work, not to play with tools and utilities and spend hours with tweaking the settings. I am talking about opt-in situation than this enforced opt-out in regards of snap.
I noticed that some preinstalled tools: vlc, clementine, gimp, gnome, but also zoom or skype - are installed as snaps.
I would appreciate at least one easy to find webpage/procedure for "undemanding home users" explaining how to easily migrate from snap installs of these (as many as possible) tools to regular apt. Or do I have to manually "snap remove" and then "apt install" for every single one? Any risk of breaking dependencies on the way?
What about things like core, gnome, eventually snapstore, snapd -> am I forced to keep them as snaps, tumorizing my disk space?
This may be a great utility for a specific use, but distributing it as a default was a bad idea imho.


text:
Q: Definable subsets of the J-hierarchy in fine structure theory So there is a lemma in Ralf Schindler's book, which is said to be an immediate consequence of a previous lemma, but it is not really immediate to me. So let me give some context.
Let $E$ be a set or a proper class. We say a function or relation is $\text{rud}_E,$ if it is rudimentary in $E$. And for any transitive set $U$, $\text{rud}_E(U)$ denotes the closure of $U$ under $\text{rud}_E$ functions. And for a structure $(U, \in, E)$,  $\tilde{\Sigma}_n^{(U, \in, E)}$ denotes the set of $\Sigma_n$-definable relations with parameters from $U$ and $\tilde{\Sigma}_\omega^{(U, \in, E)} = \bigcup_{n\in\omega}\tilde{\Sigma}_n^{(U, \in, E)}$. Also we index the J-hierarchy with limit ordinals.
And the following is the lemma which we will quote:

$(*)$ Let $U$ be a transitive set and $E \subseteq U$. Then $P(U)\cap\text{rud}_E(U\cup\{U\}) = P(U)\cap\tilde{\Sigma}_\omega^{(U, \in, E)}$.

And below is the lemma which is said to be a direct consequence of $(*)$:

Let $E$ be a set or a proper class. Assume that $E \subseteq Lim \times V$, where $Lim$ is the class of all limit ordinals. Let us write $E_\alpha = \{x: (\alpha, x) \in E\}$ and $E|\alpha = E \cap (\alpha \times V)$ for limit ordinals $\alpha$. Let assume that $E_\alpha \subseteq J_\alpha[E]$ and that $(J_\alpha[E], \in, E_\alpha)$ is amenable for every limit ordinal $\alpha$. Then
  $$P(J_\alpha[E])\cap J_{\alpha + \omega}[E] = P(J_\alpha[E])\cap\tilde{\Sigma}_\omega^{(J_\alpha[E], \in, E|\alpha, E_\alpha)}.$$

So proving that the lhs is a subset of the rhs is not that hard because of the lemma, since $E\cap J_\alpha[E] = E|\alpha$. What I can't prove, is the converse and it's because of the $E_\alpha$ predicate. The best thing I tried was to modify the proof of $(*)$, but there I had to show that membership in $E_\alpha$ was $\text{rud}_E$, which isn't really clear to me.
So I looked this up in the handbook of set theory, there the equivalent result was mentioned, without this $E_\alpha$ predicate. To me, the thing that seems to be the main obstacle, is that there is no clear connection between $E \cap J_\alpha[E]$ and $E_\alpha$. And that we have less information to work with, in the structure $(J_\alpha[E], \in, E)$.
I hope someone can clarify the situation and tell me how this lemma is proven.

A: First, we can strenghen $(\ast)$ a bit in the following sense: If $F$ satisfies the same assumption as $E$ then $$\mathcal P(U)\cap\operatorname{rud}_{E, F}(U\cup\{U\})=\mathcal P(U)\cap\bar\Sigma_\omega^{(U, \in, E, F)}$$
where $\operatorname{rud}_{E, F}$ closes under functions that are rudimentary in $E$ or $F$.
You can see that even with this relaxed assumption we cannot immediately apply $(\ast)$ to calculate $\mathcal P(J_{\alpha}[E])\cap J_{\alpha+\omega}[E]$ as elements of the form $(\alpha, x)\in E$ are not in $J_\alpha[E]$. This is why we need to consider $E_\alpha$. The following holds true:
$$\mathcal P(J_\alpha[E])\cap J_{\alpha+\omega}[E]=\mathcal P(J_\alpha[E])\cap\operatorname{rud}_{E|\alpha, E_\alpha}(J_\alpha[E]\cup\{J_\alpha[E]\})=\mathcal P(J_\alpha[E])\cap\bar\Sigma_\omega^{(J_\alpha[E],\in, E|\alpha, E_\alpha)}$$
The second equality is true by the revised version of $(\ast)$ above, noting that $E_\alpha\subseteq J_\alpha[E]$. For the first equality we simply observe that $$J_{\alpha+\omega}[E]=\operatorname{rud}_E(J_\alpha[E]\cup\{J_\alpha[E]\})=\operatorname{rud}_{E|\alpha+1}(J_\alpha[E]\cup\{J_\alpha[E]\})=\operatorname{rud}_{E|\alpha, E_\alpha}(J_\alpha[E]\cup\{J_\alpha[E]\})$$
Here the first equality is by definition, the second one holds as in general
$$\operatorname{rud}_E(U\cup\{U\})=\operatorname{rud}_{E\cap V_{\operatorname{rank}(U)+\omega}}(U\cup\{U\})$$
for transitive $U$ and $E\cap V_{\alpha+\omega}=E|\alpha+1$. Finally, we argue that the last equality holds: For $\subseteq$ note that both $E|\alpha$ and $E_\alpha$ are rudimentary in $E$ over $J_{\alpha+\omega}[E]$. Similar for $\supseteq$, $E|\alpha+1$ is rudimentary in $E|\alpha, E_\alpha$ over $\operatorname{rud}_{E|\alpha, E_\alpha}(J_\alpha[E]\cup\{J_\alpha[E]\})$.
Finally I want to mention that it is definately possible that
$$\mathcal P(J_\alpha[E])\cap \bar\Sigma_\omega^{(J_\alpha[E],\in, E)}\subsetneq\mathcal P(J_\alpha[E])\cap J_{\alpha+\omega}[E]$$
It is a nice exercise to come up with such an example. (Hint: there are some with $\alpha=\omega$)


text:
Q: Query over initialisation of global variables Not able to figure out why this code gives error.
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
unsigned long long A[102];
A[0]=2;
int main()
{
    cout<<"OK";
}

Error while compiling:
prog.cpp:6:1: error: 'A' does not name a type

But this works fine.
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
unsigned long long A[102];
int main()
{
    A[0]=2;
    cout<<"OK";
}

What could be the reason ?

A: This
A[0]=2;

is not an initialization, it is an assignment to the first element of A. You cannot do that outside of a function.
This is initialization, and is legal:
#include<iostream>

unsigned long long A[102] = {2};

int main()
{
    std::cout<<"OK\n";
}

It will set the first element to 2 and all the rest to 0.


text:
Q: A fast method for comparing a value in one Panda's row to another in a previous row? I have a DataFrame, df, that looks like:
ID    |          TERM       |   DISC_1
1     |         2003-10     |   ECON
1     |         2002-01     |   ECON
1     |         2002-10     |   ECON
2     |         2003-10     |   CHEM
2     |         2004-01     |   CHEM
2     |         2004-10     |   ENGN
2     |         2005-01     |   ENGN
3     |         2001-01     |   HISTR
3     |         2002-10     |   HISTR
3     |         2002-10     |   HISTR

ID is a student ID, TERM is an academic term, and DISC_1 is the discipline of their major.  For each student, I'd like to identify the TERM when (and if) they changed DISC_1, and then create a new DataFrame that reports when. Zero indicates they did not change. The output looks like:
ID    |     Change
1     |         0
2     |         2004-01
3     |         0

My code below works, but it's very slow. I tried to do this using Groupby, but was unable to.  Could someone explain how I might accomplish this task more efficiently?
df = df.sort_values(by = ['PIDM', 'TERM'])
c = 0
last_PIDM = 0
last_DISC_1 = 0
change = [ ]
for index, row in df.iterrows():
    c = c + 1
    if c > 1:
        row['change'] = np.where((row['PIDM'] == last_PIDM) & (row['DISC_1'] != last_DISC_1),     row['TERM'], 0)
        last_PIDM = row['PIDM']
        last_DISC_1 = row['DISC_1']

    else:
        row['change'] = 0
    change.append(row['change'])

df['change'] = change
change_terms = df.groupby('PIDM')['change'].max()

A: Here's a start:
df = df.sort_values(['ID', 'TERM'])
gb = df.groupby('ID').DISC_1
df['Change'] = df.TERM[gb.apply(lambda x: x != x.shift().bfill())]
df.Change = df.Change.fillna(0)

A: I've never been a big pandas user, so my solution would involve spitting that df out as a csv, and iterating over each row, while retaining the previous row. If it is properly sorted (first by ID, then by Term date) I might write something like this...
import csv

with open('inputDF.csv', 'rb') as infile:
    with open('outputDF.csv', 'wb') as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)

        previousline = reader.next()  #grab the first row to compare to the second
        termChange = 0
        for line in reader:
            if line[0] != previousline[0]:  #new ID means print and move on to next person
                writer.writerow([previousline[0], termChange])  #print to file ID, termChange date
                termChange = 0
            elif line[2] != previousline[2]:  #new discipline
                termChange = line[1]  #set term changed date
                #termChange = previousline[1]  #in case you want to rather retain the last date they were in the old dicipline

            previousline = line  #store current line as previous and continue loop


text:
Q: Creating NSG using Azure python sdk does not use the security rule I am using
λ pip show azure
Name: azure
Version: 2.0.0
I want to create a NSG with a specific security rule. I have the following code.
```
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
subscription_id = 'my-id'
credentials = ...

compute_client = ComputeManagementClient(
    credentials,
    subscription_id
)

network_client = NetworkManagementClient(
    credentials,
    subscription_id
)
from azure.mgmt.resource.resources import ResourceManagementClient

resource_client = ResourceManagementClient(
    credentials,
    subscription_id
)
resource_client.providers.register('Microsoft.Compute')
resource_client.providers.register('Microsoft.Network')

resource_group_name = 'test-rg'

security_rule = SecurityRule( protocol='Tcp', source_address_prefix='Internet',
                              source_port_range="*", destination_port_range="3389", priority=100,
                              destination_address_prefix='*', access='Allow', direction='Inbound')
nsg_params = NetworkSecurityGroup(id='test-nsg', location='UK South', tags={ 'name' : 'testnsg' })
network_client.network_security_groups.create_or_update(resource_group_name, "test-nsg", parameters=nsg_params, security_rules=[security_rule])

This does create the NSG fine but fails to create the proper rules.
What am I missing?

A: We can use this script to achieve it:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
from azure.mgmt.resource.resources import ResourceManagementClient

subscription_id = 'xxxxxxxxx-xxxxxxxxxxxxxxxxxxxx'
credentials = ServicePrincipalCredentials(
    client_id = 'xxxxxx-xxxx-xxx-xxxx-xxxxxxx',
    secret = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx',
    tenant = 'xxxxxx-xxxxxxx'
)

compute_client = ComputeManagementClient(
    credentials,
    subscription_id
)

network_client = NetworkManagementClient(
    credentials,
    subscription_id
)

resource_client = ResourceManagementClient(
    credentials,
    subscription_id
)
resource_client.providers.register('Microsoft.Compute')
resource_client.providers.register('Microsoft.Network')

resource_group_name = 'test-rg'

parameters = NetworkSecurityGroup()
parameters.location = 'UK South'

parameters.security_rules = [SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow RDP port 3389',
                                 source_port_range='*', destination_port_range='3389', priority=100, name='RDP01')]

network_client.network_security_groups.create_or_update(resource_group_name, "test-nsg", parameters)

network_client.network_security_groups.create_or_update only have three values, resource_group, security_group_name and parametes.
More information about network_client.network_security_groups.create_or_update, please refer to this link.