问:
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

```<code>$ myapp -n 3,4,5,6
</code>```

or

```<code>$ myapp -n 3-6
</code>```

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

```<code>$ myapp -n 22-27, 51-64
</code>```

答:
Use Python's range function. Parse your user's input, splitting it by the '-' character, and then pass those parameters to range.

Your code might look something like this:

```<code>parameters = input.split('-')
completeRange = range(int(parameters[0]), int(parameters[1]))
</code>```

If they enter individual numbers, you can just parse that into a list quite easily.

Title: Parsing command line input for numbers

Body:
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6]
I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64

Body:
Use Python's range function. Parse your user's input, splitting it by the '-' character, and then pass those parameters to range.

Your code might look something like this:

parameters = input.split('-')
completeRange = range(int(parameters[0]), int(parameters[1]))

If they enter individual numbers, you can just parse that into a list quite easily.


来源: stackexchange

问:
How to solve import cv2 import error on Amazon linux?
I am using an Amazon linux machine with python 2.7.
I am working with Anaconda.
When typing:

```<code>import cv2
</code>```

I get the following exception:

```<code>ImportError: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory
</code>```

I have tried to search online but did not find a solution for amazon linux.

Thanks.

答:
I have followed instructions in this page and worked fine:
https://ubunifu.co/python/installing-libgtk-x11-2-0-so-0-in-amazon-linux-ami-2017-03-1

```<code>$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/hicolor-icon-theme-0.11-1.1.el6.noarch.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/atk-1.30.0-1.el6.x86_64.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/gdk-pixbuf2-2.24.1-6.el6_7.x86_64.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/gtk2-2.24.23-9.el6.x86_64.rpm
</code>```

As it seems Amazon AMI doesn’t have a yum repository for the libgtk-x11-2.0.so.0. So, we can install it from CentOs distro packages.

ContentLicense: CC BY-SA 3.0

Body:
I am using an Amazon linux machine with python 2.7.
I am working with Anaconda.
When typing:

import cv2

I get the following exception:

ImportError: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory

I have tried to search online but did not find a solution for amazon linux.

Thanks.

Body:
I have followed instructions in this page and worked fine:
https://ubunifu.co/python/installing-libgtk-x11-2-0-so-0-in-amazon-linux-ami-2017-03-1

$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/hicolor-icon-theme-0.11-1.1.el6.noarch.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/atk-1.30.0-1.el6.x86_64.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/gdk-pixbuf2-2.24.1-6.el6_7.x86_64.rpm
$ sudo yum install ftp://ftp.riken.jp/Linux/centos/6/os/x86_64/Packages/gtk2-2.24.23-9.el6.x86_64.rpm

As it seems Amazon AMI doesn’t have a yum repository for the libgtk-x11-2.0.so.0. So, we can install it from CentOs distro packages.


问:
AsyncTask <Map<String, List<Object>>
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

```<code>Map<String, List<Object>>
</code>```

I tried starting the asynctask like this:

```<code>public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>
</code>```

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

```<code>@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}
</code>```

and the on post execute like this:

```<code>@Override
public void onPostExecute(Map<String, List<Object>> map) {
}
</code>```

What is wrong with my syntax and how would I implement this correctly?

Thanks

答:
You have to define parameters for Params, Progress, Result

```<code>public abstract class AsyncTask<Params, Progress, Result>
</code>```

--

```<code>public static class GetIndividualAlarmsFromDataBase extends AsyncTask<Map<String, List<Object>>,Void ,Map<String, List<Object>>> {

    @Override
    protected Map<String, List<Object>> doInBackground(Map<String, List<Object>>[] maps) {
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}
</code>```

Title: AsyncTask <Map<String, List<Object>>

Body:
I am trying to do an asynctask with the data being queried and returned from the database being in the form:

Map<String, List<Object>>

I tried starting the asynctask like this:

public class GetIndividualAlarmsFromDataBase extends AsyncTask <Map<String, List<Object>>

which I think is correct because I don't get any errors beside implement methods.

But when I go to implement the methods I am doing them incorrectly because it says method does not override superclass.

I tried to create the do in background like this:

@Override
protected Map<String, List<Object> doInBackground(Map<String, List<Object>> map) {
    return null;
}

and the on post execute like this:

@Override
public void onPostExecute(Map<String, List<Object>> map) {
}

What is wrong with my syntax and how would I implement this correctly?

Thanks

Body:
You have to define parameters for Params, Progress, Result

public abstract class AsyncTask<Params, Progress, Result>

--

public static class GetIndividualAlarmsFromDataBase extends AsyncTask<Map<String, List<Object>>,Void ,Map<String, List<Object>>> {

    @Override
    protected Map<String, List<Object>> doInBackground(Map<String, List<Object>>[] maps) {
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}


问:
making python algorithm to accept input values
So I have that algorithm for breadth first and depth first search in python. I want to change it that instead of the parents variable which keeps the nodes, I want the values to be introduced by the user by an input and I dont know how to do that..

def DFS_dist_from_node(query_node, parents):
    """Return dictionary containing distances of parent GO nodes from the query"""
    result = {}
    stack = []
    stack.append( (query_node, 0) )
    while len(stack) > 0:
        print("stack=", stack)
        node, dist = stack.pop()
        result[node] = dist
        if node in parents:
            for parent in parents[node]:
                # Get the first member of each tuple, see
                # http://stackoverflow.com/questions/12142133/how-to-get-first-element-in-a-list-of-tuples
                stack_members = [x[0] for x in stack]
                if parent not in stack_members:
                    stack.append( (parent, dist+1) )
    return result

def BFS_dist_from_node(query_node, parents):
    """Return dictionary containing minimum distances of parent GO nodes from the query"""
    result = {}
    queue = []
    queue.append( (query_node, 0) )
    while queue:
        print("queue=", queue)
        node, dist = queue.pop(0)
        result[node] = dist
        if node in parents: # If the node *has* parents
            for parent in parents[node]:
                # Get the first member of each tuple, see
                # http://stackoverflow.com/questions/12142133/how-to-get-first-element-in-a-list-of-tuples
                queue_members = [x[0] for x in queue]
                if parent not in result and parent not in queue_members: # Don't visit a second time
                    queue.append( (parent, dist+1) )
    return result

if __name__ == "__main__":

    parents = dict()
    parents = {'N1': ['N2', 'N3', 'N4'], 'N3': ['N6', 'N7'], 'N4': ['N3'], 'N5': ['N4', 'N8'], 'N6': ['N13'],
               'N8': ['N9'], 'N9': ['N11'], 'N10': ['N7', 'N9'], 'N11': ['N14'], 'N12': ['N5']}

    print("Depth-first search:")
    dist = DFS_dist_from_node('N1', parents)
    print(dist)

    print("Breadth-first search:")
    dist = BFS_dist_from_node('N1', parents)
    print(dist)
    ```

答:
To take user input during execution of the script, look into input() and raw_input().

To take input before the script starts i.e. as command line arguments, take a look at how to use sys.argv() and argparse


问:
Python3 exchangelib connect error: _ssl.c:749?
Python3 exchangelib connect error: _ssl.c:749?

I am trying to connect to my company's Exchange server with exchangelib.
I want to see all the mails I have received on MS Exchange / OWA.

When I run the code below, I get:

```<code>  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn
    conn.connect()
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connection.py", line 326, in connect
    ssl_context=context)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Program Files\Python36\lib\ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "C:\Program Files\Python36\lib\ssl.py", line 808, in __init__
    self.do_handshake()
  File "C:\Program Files\Python36\lib\ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "C:\Program Files\Python36\lib\ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

from exchangelib import DELEGATE, Account, Credentials,NTLM,Configuration,Version,Build
creds = Credentials(username = 'inter.com\\login',password='password')
config = Configuration(service_endpoint='https://alpha.com/EWS/Exchange.asmx',credentials=creds,auth_type=NTLM)
account = Account(primary_smtp_address='login@alpha.com',config=config,autodiscover=False,access_type=DELEGATE,verify_ssl=False)
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
</code>```

Can you please let me know how to use certificates with exchangelib?

How to fix it?

Thanks for your help!

答:
Have you tried disabling ssl verification in your config ?

```<code>config = Configuration(service_endpoint ='...', credentials=credentials, auth_type=NTLM, verify_ssl=False)
</code>```

The sources seem to talk about a parameter like this.

Body:
Python3 exchangelib connect error: _ssl.c:749?

I am trying to connect to my company's Exchange server with exchangelib.
I want to see all the mails I have received on MS Exchange / OWA.

When I run the code below, I get:

  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn
    conn.connect()
  File "C:\Program Files\Python36\lib\site-packages\urllib3\connection.py", line 326, in connect
    ssl_context=context)
  File "C:\Program Files\Python36\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Program Files\Python36\lib\ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "C:\Program Files\Python36\lib\ssl.py", line 808, in __init__
    self.do_handshake()
  File "C:\Program Files\Python36\lib\ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "C:\Program Files\Python36\lib\ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

from exchangelib import DELEGATE, Account, Credentials,NTLM,Configuration,Version,Build
creds = Credentials(username = 'inter.com\\login',password='password')
config = Configuration(service_endpoint='https://alpha.com/EWS/Exchange.asmx',credentials=creds,auth_type=NTLM)
account = Account(primary_smtp_address='login@alpha.com',config=config,autodiscover=False,access_type=DELEGATE,verify_ssl=False)
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

Can you please let me know how to use certificates with exchangelib?

How to fix it?

Thanks for your help!

Body:
Have you tried disabling ssl verification in your config ?

config = Configuration(service_endpoint ='...', credentials=credentials, auth_type=NTLM, verify_ssl=False)

The sources seem to talk about a parameter like this.


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答: No, there isn't. By definition, the only operations on a queue are enqueuing and dequeuing, so if your application requires other operations, then a queue isn't the right structure.</p>

ContentLicense: CC BY-SA 2.5


问:
The 'Content-Length' header must be modified using the appropriate property or method. Parameter name: name
I try to send data to a webapi using WebClient.
Running my code gives an exception shown in the Title.
Can someone help me?

Here part of my code with the Header Definition

```<code>using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                wc.Headers[HttpRequestHeader.Authorization] = headerString;

                data = Encoding.UTF8.GetBytes(jsonData);
                string contentLength = data.Length.ToString();

                wc.Headers[HttpRequestHeader.ContentLength] = contentLength;
                wc.Headers[HttpRequestHeader.Accept] = "application/json";

                wrCache = new CredentialCache();
                wrCache.Add(new Uri(URI), "Basic", new NetworkCredential("user1", "f_k@1F7"));

                wc.Credentials = wrCache;

                byte[] htmlResult = wc.UploadData(URI, "POST", data);
</code>```

答:
You can use a HttpWebRequest. For example:

```<code>private static HttpStatusCode UploadSharepointFile(string fileName)
{
        // Read file from path
        byte[] buffer = File.ReadAllBytes(fileName);

        HttpWebRequest http =
            WebRequest.CreateHttp($"https://google.com");

        http.Method = "POST";

        http.Credentials = (ICredentials) Program.cred;

        http.Headers.Add("Accept", "application/json");
        http.ContentLength = buffer.Length;
        http.GetRequestStream().Write(buffer, 0, buffer.Length);

        HttpWebResponse response = (HttpWebResponse) http.GetResponse();
        return response.StatusCode;
}
</code>```

Body:
I try to send data to a webapi using WebClient.
Running my code gives an exception shown in the Title.
Can someone help me?

Here part of my code with the Header Definition

using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                wc.Headers[HttpRequestHeader.Authorization] = headerString;

                data = Encoding.UTF8.GetBytes(jsonData);
                string contentLength = data.Length.ToString();

                wc.Headers[HttpRequestHeader.ContentLength] = contentLength;
                wc.Headers[HttpRequestHeader.Accept] = "application/json";

                wrCache = new CredentialCache();
                wrCache.Add(new Uri(URI), "Basic", new NetworkCredential("user1", "f_k@1F7"));

                wc.Credentials = wrCache;

                byte[] htmlResult = wc.UploadData(URI, "POST", data);

Body:
You can use a HttpWebRequest. For example:

private static HttpStatusCode UploadSharepointFile(string fileName)
{
        // Read file from path
        byte[] buffer = File.ReadAllBytes(fileName);

        HttpWebRequest http =
            WebRequest.CreateHttp($"https://google.com");

        http.Method = "POST";

        http.Credentials = (ICredentials) Program.cred;

        http.Headers.Add("Accept", "application/json");
        http.ContentLength = buffer.Length;
        http.GetRequestStream().Write(buffer, 0, buffer.Length);

        HttpWebResponse response = (HttpWebResponse) http.GetResponse();
        return response.StatusCode;
}


问:
Template error when displaying hostname in Spring Boot sample application - pet clinic
I'm using the sample spring-petclinic Spring Boot app for a demo I'm building. I'm trying to do something that seems super basic, but am struggling (I'm a Java n00b).

Here's the sample app: https://github.com/spring-projects/spring-petclinic

Essentially I want to display the server hostname on the welcome page of the website.

In the WelcomeController.java file (spring-petclinic/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java) I have the following:

```<code>package org.springframework.samples.petclinic.system;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
class WelcomeController {

    @RequestMapping("/")
    public String welcome() {
        return "Hello from " + System.getenv("HOSTNAME") + String.format("%n");
    }
}
</code>```

All I have replaced is the return value from return "welcome" to what you see above.

The build completes and I can run the application, but the page loads with the following error:

```<code>Something happened...

Error resolving template "Hello from d7710dcc2456 ", template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

I've played around with model.addAttribute and adding additional public String blocks, but am a little out of my depth! Any ideas?

答:
When you return a String value from a controller method with @RequestMapping, spring will resolve the string value from
configured view template. So return "welcome" resolves the welcome.html inside resources/templates/ directory.

When you replace it with return "Hello from " + System.getenv("HOSTNAME") + String.format("%n")
it will look for the template with name "Hello from " + System.getenv("HOSTNAME") + String.format("%n")

As this is not present inside resources/templates/, it gives error.

Change your controller like this:

```<code>@GetMapping("/")
public String welcome(Model model) {
    model.addAttribute("hostname", System.getenv("HOSTNAME") );
    return "welcome";
}
</code>```

And change your welcome.html like this,

```<code><h1>Hello from <span th:text="${hostname}">hostname</span></h1>
</code>```

Body:
I'm using the sample spring-petclinic Spring Boot app for a demo I'm building. I'm trying to do something that seems super basic, but am struggling (I'm a Java n00b).

Here's the sample app: https://github.com/spring-projects/spring-petclinic

Essentially I want to display the server hostname on the welcome page of the website.

In the WelcomeController.java file (spring-petclinic/src/main/java/org/springframework/samples/petclinic/system/WelcomeController.java) I have the following:

package org.springframework.samples.petclinic.system;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
class WelcomeController {

    @RequestMapping("/")
    public String welcome() {
        return "Hello from " + System.getenv("HOSTNAME") + String.format("%n");
    }
}

All I have replaced is the return value from return "welcome" to what you see above.

The build completes and I can run the application, but the page loads with the following error:

Something happened...

Error resolving template "Hello from d7710dcc2456 ", template might not exist or might not be accessible by any of the configured Template Resolvers

I've played around with model.addAttribute and adding additional public String blocks, but am a little out of my depth! Any ideas?

Body:
When you return a String value from a controller method with @RequestMapping, spring will resolve the string value from
configured view template. So return "welcome" resolves the welcome.html inside resources/templates/ directory.

When you replace it with return "Hello from " + System.getenv("HOSTNAME") + String.format("%n")
it will look for the template with name "Hello from " + System.getenv("HOSTNAME") + String.format("%n")

As this is not present inside resources/templates/, it gives error.

Change your controller like this:

@GetMapping("/")
public String welcome(Model model) {
    model.addAttribute("hostname", System.getenv("HOSTNAME") );
    return "welcome";
}

And change your welcome.html like this,

<h1>Hello from <span th:text="${hostname}">hostname</span></h1>


问:
Jumpy flex layout
I'm relatively new to Flex however needed to take over maintenance and development of an application after a bit of a crisis. I'm familiar with AS3 and OOP in general if that's any help.

The application is built using Flex builder 3, Flex SDK 4.1 and is based around the Halo theme. Main.mxml contains a few navigation bits and pieces, application border and a canvas named placeholder.

As the user navigates around the site the state of the Main.mxml is changed, and based upon that the appropriate "screen" is then swapped within the placeholder with no animation applied (Sometimes a ProgressBar halts progress until data has loaded). Each screen is the same size as the main application, based around a mx:Canvas and set to position its self at 0,0 thus filling the entire window.

First off, is this a good approach, would you make any recommendations on things to change?

Next, some screens are suffering from some strange jumping with the layout and positioning and for the life of me I cannot figure out why. It's happening on a number of visual elements.

My first example being a button built using hbox, image and text controls. The hbox has been modified to include gradient backgrounds however the issue occurs when using the default mx hbox. The first image is on first render having had no interaction, the second is after I have rolled my mouse over it, and the 3rd (and correct) image is after leaving that screen and then returning. Notice it is no longer being clipped and includes the rounded corners on the right hand side too.

My second example is harder to capture but I have a series of 4 gradient buttons based around the flexlib advanced button skin stacked in a mx:vbox. On first display they are correct, on second display they appear correct but when hovering over them something seems to change but I'm not sure what which causes the buttons beneath to jump down by about a pixel for each button hovered over. After each button has caused that jump, everything is ok again.

And finally, when returning to the previous screen the entire screen appears to jump to the left slightly just after it has displayed giving it a very jerky appearance.

Many thanks for any help

EDIT - Success

After many hours of trying your suggestions and messing about removing elements from the stage one by one i eventually discovered the source of the problem to be the borderMetrics property of the VideoDisplay control. After removing these (i'm not even sure why they were there in the first place) all of the strange display issues I was suffering from went away.

Many thanks for the suggestions!

答: I'd recommend posting some code for your button so we can analyze it, but what you are seeing is the result of the component measuring itself multiple times.  The way I've combated this in the past is to either set explicit sizes on the component and its subcomponents, and/or add judiciously placed minWidth="0" properties on the components/subcomponents.  The latter is an old trick to cause a component to measure itself properly.  Hope that helps.  If not, post some code.  Good luck.</p>

Title: Jumpy flex layout


问:
array_splice() for associative arrays
Say I have an associative array:

```<code>array(
  "color" => "red",
  "taste" => "sweet",
  "season" => "summer"
);
</code>```

and I want to introduce a new element into it:

```<code>"texture" => "bumpy"
</code>```

behind the 2nd item but preserving all the array keys:

```<code>array(
  "color" => "red",
  "taste" => "sweet",
  "texture" => "bumpy",
  "season" => "summer"
);
</code>```

is there a function to do that? array_splice() won't cut it, it can work with numeric keys only.

答:
```<code>function insrt_to_offest($targetArr, $toBeEmbed, $indAfter) {
    $ind = array_search($indAfter, array_keys($targetArr));
    $offset = $ind + 1;

    # Insert at offset 2
    $newArray = array_slice($targetArr, 0, $offset, true) +
    $toBeEmbed +
    array_slice($targetArr, $offset, NULL, true);

    return $newArray;
}

$features = array(
            "color" => "red",
            "taste" => "sweet",
            "season" => "summer"
          );

print_r($features);

$toBeEmbed = array("texture" => "bumpy");

$newArray = insrt_to_offest($features, $toBeEmbed, 'taste');

print_r($newArray);
</code>```

Title: array_splice() for associative arrays

Body:
Say I have an associative array:

array(
  "color" => "red",
  "taste" => "sweet",
  "season" => "summer"
);

and I want to introduce a new element into it:

"texture" => "bumpy"

behind the 2nd item but preserving all the array keys:

array(
  "color" => "red",
  "taste" => "sweet",
  "texture" => "bumpy",
  "season" => "summer"
);

is there a function to do that? array_splice() won't cut it, it can work with numeric keys only.


问:
C# - Stopping a Forms application on exception
I am creating a Windows Forms application in which I need small help for exception handling.

What my application would do (an overview): Take inputs from the user in the start. When the user clicks on the Finish button, the inputs are processed. Based on the inputs given, certain computations are performed. After this, an application is uninstalled using msiexec /x command (being launched as a separate process).

If there is an exception during the input processing time (that is, before the uninstall task), I am calling the Application.Exit() method. Following code snippet might give you an idea:

```<code>try
{
    //some processing
}
catch (Exception exc)
{
    DisplayErrorMessage();
    WriteToLog(exc.Message);
    WriteToLog("Inner Exception: " + exc.InnerException);
    Application.Exit();
}
</code>```

My Observation: If any exception was encountered during the processing time, the Process.Start() method is returning null.

Can somebody tell why this is happening? Is there a way to overcome this?

P.S: How do i need to modify my code so that, if an exception occurs previously, the process doesn't even start?

答:
I have figured out that calling Environment.Exit(1) actually terminates the forms application, which is not done by calling the Application.Exit() method.

More information can be obtained from the following link: How to properly exit a C# application?

Body:
I am creating a Windows Forms application in which I need small help for exception handling.

What my application would do (an overview): Take inputs from the user in the start. When the user clicks on the Finish button, the inputs are processed. Based on the inputs given, certain computations are performed. After this, an application is uninstalled using msiexec /x command (being launched as a separate process).

If there is an exception during the input processing time (that is, before the uninstall task), I am calling the Application.Exit() method. Following code snippet might give you an idea:

try
{
    //some processing
}
catch (Exception exc)
{
    DisplayErrorMessage();
    WriteToLog(exc.Message);
    WriteToLog("Inner Exception: " + exc.InnerException);
    Application.Exit();
}

My Observation: If any exception was encountered during the processing time, the Process.Start() method is returning null.

Can somebody tell why this is happening? Is there a way to overcome this?

P.S: How do i need to modify my code so that, if an exception occurs previously, the process doesn't even start?


问:
Dex error On Android Studio 3.0 Beta4
```<code>Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Error:java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Error:com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Error:com.android.dex.DexException: Multiple dex files define Lcom/google/zxing/integration/android/IntentResult;
</code>```

答:
I have tried other comments from removing gradle and bla bla bla, but adding multiDexEnabled true  solving my problem, I investigate that my apk has reached Over 64K Method.

Ref: https://developer.android.com/studio/build/multidex.html)

Title: Dex error On Android Studio 3.0 Beta4


问:
How to select a row having a column with max value with a group by
I have a table with the next columns

```<code>MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE
</code>```

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

```<code>select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;
</code>```

答:
You can use window function row_number to find row with largest parse time in each hour like this:

```<code>select *
from (
    select to_number(to_char(creation_date, 'HH24')) as hour,
        port,
        msg_id,
        round(parsed_on - creation_date) * 24 * 60 as parse_time,
        row_number() over (
            partition by to_char(creation_date, 'HH24'), port, msg_id
            order by (parsed_on - creation_date) desc nulls last
            ) as rn
    from t_income_calls t
    where creation_date between trunc(sysdate)
                            and trunc(sysdate + 1) - interval '1' second
    ) t
where rn = 1;
</code>```

Also, notice the filter. I used date range instead of to_char on creation_date. The use of to_char on creation_date inhibits the use of index on creation_date if it is present.

Body:
I have a table with the next columns

MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;

Body:
You can use window function row_number to find row with largest parse time in each hour like this:

select *
from (
    select to_number(to_char(creation_date, 'HH24')) as hour,
        port,
        msg_id,
        round(parsed_on - creation_date) * 24 * 60 as parse_time,
        row_number() over (
            partition by to_char(creation_date, 'HH24'), port, msg_id
            order by (parsed_on - creation_date) desc nulls last
            ) as rn
    from t_income_calls t
    where creation_date between trunc(sysdate)
                            and trunc(sysdate + 1) - interval '1' second
    ) t
where rn = 1;

Also, notice the filter. I used date range instead of to_char on creation_date. The use of to_char on creation_date inhibits the use of index on creation_date if it is present.


问:
implementing a callback in android with Activities
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.</p>

```<code>public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}
</code>```

答: You can do one thing. Create an object of your library when activity starts and pass the reference of your activity to that object instantiation. And implement that interface call back to the activity. And internally in your library, you will have activity reference cast that to your interface callback and call interface method that will give you call back at your activity level.</p>

Body:
I am developing an library for Android and have following scenario, I want a response back to MainActivity. How could I do it? I have tried with callbacks but could not as I could not create an object of Activity class by myself. is there any other way to achieve it? in AsyncTaskListener implementation I am doing some network operation. I could not use startActivityForResult as it's not according to my library specification.

public class MainActivity extends AppCompatActivity implements MyReceiver{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    MyServiceImpl b = new MyServiceImpl();
    String request = "123";
    b.request(this,request);
    }

    @Override
    public void completed(String result) {
        Log.d("MainActivity","Result - "+result);
    }
}

public class MyServiceImpl{

   public void request(Activity appActivity,String req){
        Intent intent = new Intent(appActivity, ActivityB.class);
        appActivity.startActivity(intent);
   }
}

public class ActivityB extends AppCompatActivity imnplements AsyncTaskListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // shows UI
        // network operations
    }

   @Override
   public void taskFinish(String response) {
     //  my result comes here
     //  now  i want this result to propagated to MainActiviy
   }
}


问:
AWS Spectrum giving blank result for parquet files generated by AWS Glue
We are building a ETL with AWS Glue. And to optimise the query performance we are storing data in apache parquet. Once the data is saved on S3 in parquet format. We are using AWS Spectrum to query on that data.

We successfully tested the entire stack on our development AWS account. But when we moved to our production AWS account. We are stuck with a weird problem. When we query the rows are returned, but the data is blank.

Though the count query return a good number

On further investigation we came to know the apache parquet files in development AWS account is RLE encoded and files in production AWS account is BITPACKED encoded. To make this case stronger, I want to convert BITPACKED to RLE and see if I am able to query data.

I am pretty new to parquet files and couldn't find much help to convert the encodings. Can anybody get me the ways of doing it.

Currently our prime suspect is the different encoding. But if you can guess any other issue. I will be happy to explore the possibilities.

答: We found our configuration mistake. The column names of our external tables and specified in AWS Glue were inconsistent. We fixed that and now able to view data. I bit shortfall from AWS Spectrum part would be not giving appropriate error message. </p>


问:
Fuse Error deploying bundle IndexOutOfBoundsException
I am new to FUSE. I am trying to start a simple REST service.

I am using Jboss Fuse 6.3.

The bundle installs but i cannot start it without the error.
After installing the bundle, it appears as "Active", but with the tag "Failure".

The log prints the following error:

```<code> 12:29:17,046 | ERROR | Thread-53        | BlueprintContainerImpl           | 23 - org.apache.aries.blueprint.core - 1.4.5 | Unable to start blueprint container for bundle null/0.0.0
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)[:1.8.0_151]
    at java.util.ArrayList.get(Unknown Source)[:1.8.0_151]
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.readDirectives(BlueprintContainerImpl.java:214)
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.doRun(BlueprintContainerImpl.java:296)
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.run(BlueprintContainerImpl.java:270)
    at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:294)
    at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:263)
</code>```

This is my code:

Picture of project structure

Pom.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.fusesource.example</groupId>
    <artifactId>rest-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>rest-service</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.servicemix.specs</groupId>
            <artifactId>org.apache.servicemix.specs.jsr311-api-1.1.1</artifactId>
            <version>1.9.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.servicemix</groupId>
            <artifactId>servicemix-http</artifactId>
            <version>2013.01</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>

    <build>
       <defaultGoal>install</defaultGoal>
       <plugins>
          <plugin>
             <groupId>org.apache.felix</groupId>
             <artifactId>maven-bundle-plugin</artifactId>
             <version>2.3.6</version>
             <extensions>true</extensions>

             <configuration>
                <instructions>
                   <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                   <Import-Package>* </Import-Package>
                </instructions>
             </configuration>

          </plugin>
       </plugins>
    </build>

</project>
</code>```

Blueprint.xml:

```<code><?xml version = "1.0" encoding = "UTF-8"?>
<blueprint xmlns = "http://www.osgi.org/xmlns/blueprint/v1.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jaxrs = "http://cxf.apache.org/blueprint/jaxrs"
   xmlns:cxf="http://cxf.apache.org/blueprint/core"
   xsi:schemaLocation = "http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
   http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
   http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">

   <jaxrs:server id="servicios" address="/serviciosPrueba">
      <jaxrs:serviceBeans>
        <ref component-id="miServicio" />
      </jaxrs:serviceBeans>
   </jaxrs:server>

   <bean id="miServicio" class="com.rest.Servicio" />

</blueprint>
</code>```

Java:

```<code>package com.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/servicioPrueba")
public class Servicio {

   @GET
   @Path("/getData")
   @Produces(MediaType.APPLICATION_JSON)
   public String getUser() {
      String reponse = "This is standard response from REST";
      return reponse;
   }
}
</code>```

Thank you very much.

答:
I resolved the second error adding specific versions of dependencies in pom.xml:</p>

```<code> <configuration>
                <instructions>
                   <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                   <Import-Package>
                        javax.ws.rs;version="[2.0,3)",
                        javax.ws.rs.core;version="[2.0,3)",
                        *
                   </Import-Package>
                </instructions>
</configuration>
</code>```

Body:
I am new to FUSE. I am trying to start a simple REST service.

I am using Jboss Fuse 6.3.

The bundle installs but i cannot start it without the error.
After installing the bundle, it appears as "Active", but with the tag "Failure".

The log prints the following error:

 12:29:17,046 | ERROR | Thread-53        | BlueprintContainerImpl           | 23 - org.apache.aries.blueprint.core - 1.4.5 | Unable to start blueprint container for bundle null/0.0.0
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)[:1.8.0_151]
    at java.util.ArrayList.get(Unknown Source)[:1.8.0_151]
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.readDirectives(BlueprintContainerImpl.java:214)
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.doRun(BlueprintContainerImpl.java:296)
    at org.apache.aries.blueprint.container.BlueprintContainerImpl.run(BlueprintContainerImpl.java:270)
    at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:294)
    at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:263)

This is my code:

Picture of project structure

Pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.fusesource.example</groupId>
    <artifactId>rest-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>rest-service</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.servicemix.specs</groupId>
            <artifactId>org.apache.servicemix.specs.jsr311-api-1.1.1</artifactId>
            <version>1.9.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.servicemix</groupId>
            <artifactId>servicemix-http</artifactId>
            <version>2013.01</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>

    <build>
       <defaultGoal>install</defaultGoal>
       <plugins>
          <plugin>
             <groupId>org.apache.felix</groupId>
             <artifactId>maven-bundle-plugin</artifactId>
             <version>2.3.6</version>
             <extensions>true</extensions>

             <configuration>
                <instructions>
                   <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                   <Import-Package>* </Import-Package>
                </instructions>
             </configuration>

          </plugin>
       </plugins>
    </build>

</project>

Blueprint.xml:

<?xml version = "1.0" encoding = "UTF-8"?>
<blueprint xmlns = "http://www.osgi.org/xmlns/blueprint/v1.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jaxrs = "http://cxf.apache.org/blueprint/jaxrs"
   xmlns:cxf="http://cxf.apache.org/blueprint/core"
   xsi:schemaLocation = "http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
   http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
   http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">

   <jaxrs:server id="servicios" address="/serviciosPrueba">
      <jaxrs:serviceBeans>
        <ref component-id="miServicio" />
      </jaxrs:serviceBeans>
   </jaxrs:server>

   <bean id="miServicio" class="com.rest.Servicio" />

</blueprint>

Java:

package com.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/servicioPrueba")
public class Servicio {

   @GET
   @Path("/getData")
   @Produces(MediaType.APPLICATION_JSON)
   public String getUser() {
      String reponse = "This is standard response from REST";
      return reponse;
   }
}

Thank you very much.

Body:
I resolved the second error adding specific versions of dependencies in pom.xml:

 <configuration>
                <instructions>
                   <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                   <Import-Package>
                        javax.ws.rs;version="[2.0,3)",
                        javax.ws.rs.core;version="[2.0,3)",
                        *
                   </Import-Package>
                </instructions>
</configuration>


问:
Initialize Constant Using ng-init Variables in AngularJs
I am working with AngularJs and I am initializing a variable in the ng-init of that model.

```<code><body ng-init="allowedState=2" ng-controller="amCtrl">
</body>
</code>```

Now what I want is to declare a constant using this variable which will then be shared within the app.

```<code>angular.module('amModule').constant('temp', ?)
</code>```

I am trying to figure this out and I am now wondering if it's even possible?

答:
Yes you can do the above way</p>

```<code>angular.module('amModule').constant('allowedState',2);
</code>```

Body:
I am working with AngularJs and I am initializing a variable in the ng-init of that model.

Now what I want is to declare a constant using this variable which will then be shared within the app.

angular.module('amModule').constant('temp', ?)

I am trying to figure this out and I am now wondering if it's even possible?

Body:
Yes you can do the above way

angular.module('amModule').constant('allowedState',2);


问:
Angular 4 : Cli compiler issue with d.ts file when adding Angular material
I've added to my project angular material by installing npm install @angular/material and npm install @angular/cdk and now when I compile my app I am getting .d.ts file errors.

I've checked my tsconfig.json file

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types": [ "node", "mocha", "chai" ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "wwwroot",
    "typings/main",
    "typings/main.d.ts"
  ]
}
</code>```

tsconfig.app.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "typings"
  ]
}
</code>```

Errors:

```<code> RROR in /node_modules/@angular/material/dialog/typings/dialog-config.d.ts (22,40): ',' expected.

    ERROR in /node_modules/@angular/material/dialog/typings/dialog-config.d.ts (22,42): Type parameter name cannot be 'any'

    ERROR in /node_modules/@angular/material/dialog/typings/dialog-container.d.ts (36,14): Generic type 'MatDialogConfig<D, any>' requires 2 type argument(s).

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,15): ',' expected.

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,17): Type parameter name cannot be 'any'

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,90): Generic type 'MatDialogConfig<D, any>' requires 2 type argument(s).
</code>```

答:
Be careful when you do 'npm i @angular/material ' as you install the latest and the latest has breaking changes. It is a shame that your IDE can't tell you upfront and ask you if you want to take continue.

@angular/material is asking for the latest typescript, and latest typescript that is 2.4 I think is only working on Angular version 5.

The same goes for  @angular/cdk.

Best thing is that finally, it is a stable version and not beta.

Body:
I've added to my project angular material by installing npm install @angular/material and npm install @angular/cdk and now when I compile my app I am getting .d.ts file errors.

I've checked my tsconfig.json file

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types": [ "node", "mocha", "chai" ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "wwwroot",
    "typings/main",
    "typings/main.d.ts"
  ]
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "typings"
  ]
}

Errors:

 RROR in /node_modules/@angular/material/dialog/typings/dialog-config.d.ts (22,40): ',' expected.

    ERROR in /node_modules/@angular/material/dialog/typings/dialog-config.d.ts (22,42): Type parameter name cannot be 'any'

    ERROR in /node_modules/@angular/material/dialog/typings/dialog-container.d.ts (36,14): Generic type 'MatDialogConfig<D, any>' requires 2 type argument(s).

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,15): ',' expected.

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,17): Type parameter name cannot be 'any'

    ERROR in /node_modules/@angular/material/dialog/typings/dialog.d.ts (49,90): Generic type 'MatDialogConfig<D, any>' requires 2 type argument(s).


问:
react native Image Loading on android faster than IOS
I'm building an application where i render many images in swiper, flatlist and i'm using React Native Image Component, but the component loads the images very fast on Android and very slow on iOS, also the caching is better on android than ios although i use force-cache prop, is there any way to improve image performance for ios ?!</p>

答: You might want to use react-native-web-image, it often gives a way faster experience.


问:
Maven `help:effective-pom` only generating for a single project, not all projects
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

```<code><!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2017-11-12T09:56:26                  -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->

<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective POM for project                                              -->
<!-- 'org.gradle.test.performance:project:pom:1.0'                          -->
<!--                                                                        -->
<!-- ====================================================================== -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>
    <scriptSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\scripts</scriptSourceDirectory>
    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>
</code>```

答:
You need to specify the parent element in each of your sub-modules pom.xml in addition to the modules elements in your root project such as:

```<code><parent>
    <groupId>org.gradle.test.performance</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
</parent>
</code>```

Otherwise it won't be picked-up when you run help:effective-pom command.

EDIT: some precision as to why the plugin does not work with Aggregation. Aggregation (done with modules element) is different than Inheritance (using the parent element). However the plugin documentation clearly mentions:

The effective-pom goal is used to make visible the POM that results
  from the application of interpolation, inheritance and active
  profiles.

And there is no mention of aggregated plugins. I believe it basically means:

I will take the pom you are providing me, apply interpolation, inheritance and active profiles but NOT aggregation, and give you the resulting pom. Deal with it.

Body:
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>

    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>

Body:
You need to specify the parent element in each of your sub-modules pom.xml in addition to the modules elements in your root project such as:

<parent>
    <groupId>org.gradle.test.performance</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
</parent>

Otherwise it won't be picked-up when you run help:effective-pom command.

EDIT: some precision as to why the plugin does not work with Aggregation. Aggregation (done with modules element) is different than Inheritance (using the parent element). However the plugin documentation clearly mentions:

The effective-pom goal is used to make visible the POM that results
  from the application of interpolation, inheritance and active
  profiles.

And there is no mention of aggregated plugins. I believe it basically means:

I will take the pom you are providing me, apply interpolation, inheritance and active profiles but NOT aggregation, and give you the resulting pom. Deal with it.


问:
Re-doing a reverted merge in Git
I have run into a bit of a problem here: I had a problem-specific branch 28s in Git, that I merged in the general develop branch. Turns out I had done it too fast, so I used git-revert to undo the merge. Now, however, the time has come to merge 28s into develop, but git-merge command sees the original merge, and happily announces that all is well and branches have been already merged. What do I do now? Create a 'Revert "Revert "28s -> develop"" ' commit? Doesn't seem to be a good way to do it, but I can't imagine any other at the moment.

What the tree structure looks like:

答:
I just found this post when facing the same problem. I find above wayyy to scary to do reset hards etc.  I'll end up deleting something I don't want to, and won't be able to get it back.

Instead I checked out the commit I wanted the branch to go back to e.g. git checkout 123466t7632723. Then converted to a branch git checkout my-new-branch.  I then deleted the branch I didn't want any more.  Of course this will only work if you are able to throw away the branch you messed up.

Title: Re-doing a reverted merge in Git


问:
Declaring theano variables for pymc3
I am having issues replicating a pymc2 code using pymc3.

I believe it is due to the fact pymc3 is using the theano type variables which are not compatible with the numpy operations I am using. So I am using the @theano.decorator:

I have this function:

```<code>with pymc3.Model() as model:

    z_stars         = pymc3.Uniform('z_star',    self.z_min_ssp_limit, self.z_max_ssp_limit)
    Av_stars        = pymc3.Uniform('Av_star',   0.0, 5.00)
    sigma_stars     = pymc3.Uniform('sigma_star',0.0, 5.0)

    #Fit observational wavelength
    ssp_fit_output = self.ssp_fit_theano(z_stars, Av_stars, sigma_stars,
                                         self.obj_data['obs_wave_resam'],
                                         self.obj_data['obs_flux_norm_masked'],
                                         self.obj_data['basesWave_resam'],
                                         self.obj_data['bases_flux_norm'],
                                         self.obj_data['int_mask'],
                                         self.obj_data['normFlux_obs'])

    #Define likelihood
    like = pymc.Normal('ChiSq', mu=ssp_fit_output,
                       sd=self.obj_data['obs_fluxEr_norm'],
                       observed=self.obj_data['obs_fluxEr_norm'])

    #Run the sampler
    trace = pymc3.sample(iterations, step=step, start=start_conditions, trace=db)
</code>```

where:

```<code>@theano.compile.ops.as_op(itypes=[t.dscalar,t.dscalar,t.dscalar,t.dvector,
                                  t.dvector,t.dvector,t.dvector,t.dvector,t.dscalar],
                          otypes=[t.dvector])
def ssp_fit_theano(self, input_z, input_sigma, input_Av, obs_wave, obs_flux_masked,
                   rest_wave, bases_flux, int_mask, obsFlux_mean):
   ...
   ...
</code>```

The first three variables are scalars (from the pymc3 uniform distribution). The
remaining variables are numpy arrays and the last one is a float. However, I am
getting this "'numpy.ndarray' object has no attribute 'type'" error:

```<code>  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 615, in __call__
    node = self.make_node(*inputs, **kwargs)
  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 963, in make_node
    if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):
  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 963, in <genexpr>
    if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):
AttributeError: 'numpy.ndarray' object has no attribute 'type'
</code>```

Please any advice in the right direction will be most welcomed.

答:
I had a bunch of time-wasting-stops when I went from pymc2 to pymc3. The problem, I think, is that the doc is quite bad. I suspect they neglect the doc as far as the code is still evolving. 3 comments/advises:

I wish you could find some help using '@theano.compile.ops.as_op' here: failure to adapt pymc2 into pymc3 or here how to fit a method belonging to an instance with pymc3?

The drawback of '@theano.compile.ops.as_op' is that you implicitly exclude any analysis related to the gradient of your function. To have access to the gradient, I think you need to define your function in a more complex way presented here how to fit a method belonging to an instance with pymc3?

warning: for the moment, using theano seems to be a source of problem if you want to distribute your code under Windows. See build a .exe for Windows from a python 3 script importing theano with pyinstaller, but I am not sure whether it is just a personal clumsiness or really a problem. Personally I had to give up theano to be able to distribute my code...

Title: Declaring theano variables for pymc3

Body:
I am having issues replicating a pymc2 code using pymc3.

I believe it is due to the fact pymc3 is using the theano type variables which are not compatible with the numpy operations I am using. So I am using the @theano.decorator:

I have this function:

with pymc3.Model() as model:

    z_stars         = pymc3.Uniform('z_star',    self.z_min_ssp_limit, self.z_max_ssp_limit)
    Av_stars        = pymc3.Uniform('Av_star',   0.0, 5.00)
    sigma_stars     = pymc3.Uniform('sigma_star',0.0, 5.0)

    #Fit observational wavelength
    ssp_fit_output = self.ssp_fit_theano(z_stars, Av_stars, sigma_stars,
                                         self.obj_data['obs_wave_resam'],
                                         self.obj_data['obs_flux_norm_masked'],
                                         self.obj_data['basesWave_resam'],
                                         self.obj_data['bases_flux_norm'],
                                         self.obj_data['int_mask'],
                                         self.obj_data['normFlux_obs'])

    #Define likelihood
    like = pymc.Normal('ChiSq', mu=ssp_fit_output,
                       sd=self.obj_data['obs_fluxEr_norm'],
                       observed=self.obj_data['obs_fluxEr_norm'])

    #Run the sampler
    trace = pymc3.sample(iterations, step=step, start=start_conditions, trace=db)

where:

@theano.compile.ops.as_op(itypes=[t.dscalar,t.dscalar,t.dscalar,t.dvector,
                                  t.dvector,t.dvector,t.dvector,t.dvector,t.dscalar],
                          otypes=[t.dvector])
def ssp_fit_theano(self, input_z, input_sigma, input_Av, obs_wave, obs_flux_masked,
                   rest_wave, bases_flux, int_mask, obsFlux_mean):
   ...
   ...

The first three variables are scalars (from the pymc3 uniform distribution). The
remaining variables are numpy arrays and the last one is a float. However, I am
getting this "'numpy.ndarray' object has no attribute 'type'" error:

  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 615, in __call__
    node = self.make_node(*inputs, **kwargs)
  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 963, in make_node
    if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):
  File "/home/user/anaconda/lib/python2.7/site-packages/theano/gof/op.py", line 963, in <genexpr>
    if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):
AttributeError: 'numpy.ndarray' object has no attribute 'type'

Please any advice in the right direction will be most welcomed.


问:
Find Index of Object in array with Aggregate
Is there a way to get index in aggregate pipeline, I have a result from long aggreagte query

```<code>[
    {
        "_id": "59ed949227ec482044b2671e",
        "points": 300,
        "fan_detail": [
            {
                "_id": "59ed949227ec482044b2671e",
                "name": "mila   ",
                "email": "mila@gmail.com ",
                "password": "$2a$10$J0.KfwVnZkaimxj/BiqGW.D40qXhvrDA952VV8x.xdefjNADaxnSW",
                "username": "mila  0321",
                "updated_at": "2017-10-23T07:04:50.004Z",
                "created_at": "2017-10-23T07:04:50.004Z",
                "celebrity_request_status": 0,
                "push_notification": [],
                "fan_array": [],
                "fanLength": 0,
                "celeb_bio": null,
                "is_admin": 0,
                "is_blocked": 2,
                "notification_setting": [
                    1,
                    2,
                    3,
                    4,
                    5,
                    6,
                    7
                ],
                "total_stars": 0,
                "total_points": 134800,
                "user_type": 2,
                "poster_pic": null,
                "profile_pic": "1508742289662.jpg",
                "facebook_id": "alistnvU79vcc81PLW9o",
                "is_user_active": 1,
                "is_username_selected": "false",
                "__v": 0
            }
        ]
    }
],
</code>```

so I want to find the index of _id in aggregate query and above array can contain 100s of object in it.

答:
Depending on the available version of MongoDB you have there are different approaches:

$indexOfArray - MongoDB 3.4

The best operator for this is simply $indexOfArray where you have it available. The name says it all really:

```<code>Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },

  { "$addFields": {
    "fanIndex": {
      "$indexOfArray": [
        "$fan_detail._id",
        mongoose.Types.ObjectId("59ed949227ec482044b2671e")
      ]
    }
  }}
])
</code>```

$unwind with includeArrayIndex - MongoDB 3.2

Going back a version in releases, you can get the index from the array from the syntax of $unwind. But this does require you to $unwind the array:

```<code>Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },
  { "$unwind": { "path": "$fan_detail", "includeArrayIndex": true } },
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } }
])
</code>```

mapReduce - Earlier versions

Earlier versions of MongoDB to 3.2 don't have a way of returning an array index in an aggregation pipeline. So if you want the matched index instead of all the data, then you use mapReduce instead:

```<code>Model.mapReduce({
  map: function() {
    emit(
      this._id,
      this['fan_detail']
        .map( f => f._id.valueOf() )
        .indexOf("59ed949227ec482044b2671e")
    )
  },
  reduce: function() {},
  query: { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") }
})
</code>```

In all cases we essentially "query" for the presence of the element "somewhere" in the array beforehand. The "indexOf" variants would return -1 where nothing was found otherwise.

Also $addFields is here just for example. If it's your real intent to not return the array of 100's of items, then you're probably using $project or other output anyway.

Body:
Is there a way to get index in aggregate pipeline, I have a result from long aggreagte query

[
    {
        "_id": "59ed949227ec482044b2671e",
        "points": 300,
        "fan_detail": [
            {
                "_id": "59ed949227ec482044b2671e",
                "name": "mila   ",
                "email": "mila@gmail.com ",
                "password": "$2a$10$J0.KfwVnZkaimxj/BiqGW.D40qXhvrDA952VV8x.xdefjNADaxnSW",
                "username": "mila  0321",
                "updated_at": "2017-10-23T07:04:50.004Z",
                "created_at": "2017-10-23T07:04:50.004Z",
                "celebrity_request_status": 0,
                "push_notification": [],
                "fan_array": [],
                "fanLength": 0,
                "celeb_bio": null,
                "is_admin": 0,
                "is_blocked": 2,
                "notification_setting": [
                    1,
                    2,
                    3,
                    4,
                    5,
                    6,
                    7
                ],
                "total_stars": 0,
                "total_points": 134800,
                "user_type": 2,
                "poster_pic": null,
                "profile_pic": "1508742289662.jpg",
                "facebook_id": "alistnvU79vcc81PLW9o",
                "is_user_active": 1,
                "is_username_selected": "false",
                "__v": 0
            }
        ]
    }
],

so I want to find the index of _id in aggregate query and above array can contain 100s of object in it.

Body:
Depending on the available version of MongoDB you have there are different approaches:

$indexOfArray - MongoDB 3.4

The best operator for this is simply $indexOfArray where you have it available. The name says it all really:

Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },

  { "$addFields": {
    "fanIndex": {
      "$indexOfArray": [
        "$fan_detail._id",
        mongoose.Types.ObjectId("59ed949227ec482044b2671e")
      ]
    }
  }}
])

$unwind with includeArrayIndex - MongoDB 3.2

Going back a version in releases, you can get the index from the array from the syntax of $unwind. But this does require you to $unwind the array:

Model.aggregate([
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } },
  { "$unwind": { "path": "$fan_detail", "includeArrayIndex": true } },
  { "$match": { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") } }
])

mapReduce - Earlier versions

Earlier versions of MongoDB to 3.2 don't have a way of returning an array index in an aggregation pipeline. So if you want the matched index instead of all the data, then you use mapReduce instead:

Model.mapReduce({
  map: function() {
    emit(
      this._id,
      this['fan_detail']
        .map( f => f._id.valueOf() )
        .indexOf("59ed949227ec482044b2671e")
    )
  },
  reduce: function() {},
  query: { "fan_detail._id": mongoose.Types.ObjectId("59ed949227ec482044b2671e") }
})

In all cases we essentially "query" for the presence of the element "somewhere" in the array beforehand. The "indexOf" variants would return -1 where nothing was found otherwise.

Also $addFields is here just for example. If it's your real intent to not return the array of 100's of items, then you're probably using $project or other output anyway.


问:
Show offline cache when server is unreachable
Is it possible to show an offline cache of my website when the server is down?

All the examples I can find regarding offline pages has to do with the client being offline. What I need is to show the user a cached version of my site if the server can't be reached.

I've read about the Cache Manifest in HMTL 5 but it's getting removed and it causes to many problems.

What can be done without using any other loadbalancing servers and such?

答:
I recently learned that with Fetch API and service workers its dead simple:

First, you register the Service worker:

```<code>  if (!navigator.serviceWorker) return;

  navigator.serviceWorker.register('/sw.js')
</code>```

Then configure it to cache whats needed:

```<code>self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        '/',
        'js/main.js',
        'css/main.css',
        'imgs/icon.png',
      ]);
    })
  );
});
</code>```

And use Fetch API to get cached peaces if no response from the call:

```<code>self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});
</code>```

if need to get cached version only if server is down, try something like:

```<code>self.addEventListener('fetch', function(event) {
  event.respondWith(
    return fetch(event.request).then(function(response) {
     if (response.status !== 200) {
       caches.match(event.request).then(function(response) {
         return response;
       }).catch(function(error) {
         console.error('Fetching failed:', error);
         throw error;
      });
    })
  );
});
</code>```

p.s. using Fetch API seems much nicer way than implementing old and nasty XMLHttpRequest.

Body:
I recently learned that with Fetch API and service workers its dead simple:

First, you register the Service worker:

  if (!navigator.serviceWorker) return;

  navigator.serviceWorker.register('/sw.js')

Then configure it to cache whats needed:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        '/',
        'js/main.js',
        'css/main.css',
        'imgs/icon.png',
      ]);
    })
  );
});

And use Fetch API to get cached peaces if no response from the call:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

if need to get cached version only if server is down, try something like:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    return fetch(event.request).then(function(response) {
     if (response.status !== 200) {
       caches.match(event.request).then(function(response) {
         return response;
       }).catch(function(error) {
         console.error('Fetching failed:', error);
         throw error;
      });
    })
  );
});

p.s. using Fetch API seems much nicer way than implementing old and nasty XMLHttpRequest.


问:
Custom ImageView with drop shadow
Okay, I've been reading and searching around, and am now banging my head against the wall trying to figure this out. Here's what I have so far:

```<code>package com.pockdroid.sandbox;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.widget.ImageView;

public class ShadowImageView extends ImageView {

private Rect mRect;
private Paint mPaint;

public ShadowImageView(Context context)
{
    super(context);
    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShadowLayer(2f, 1f, 1f, Color.BLACK);
}

@Override
protected void onDraw(Canvas canvas)
{
    Rect r = mRect;
    Paint paint = mPaint;

    canvas.drawRect(r, paint);
    super.onDraw(canvas);
}

@Override
protected void onMeasure(int w, int h)
{
    super.onMeasure(w,h);
    int mH, mW;
    mW = getSuggestedMinimumWidth() < getMeasuredWidth()? getMeasuredWidth() : getSuggestedMinimumWidth();
    mH = getSuggestedMinimumHeight() < getMeasuredHeight()? getMeasuredHeight() : getSuggestedMinimumHeight();
    setMeasuredDimension(mW + 5, mH + 5);
}
</code>```

}

The "+5" in the measurements are there as temporary; From what I understand I'll need to do some math to determine the size that the drop shadow adds to the canvas, right?

But when I use this:

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    ShadowImageView sImageView;
    if (convertView == null) {
        sImageView = new ShadowImageView(mContext);
        GridView.LayoutParams lp = new GridView.LayoutParams(85, 85);
        sImageView.setLayoutParams(lp);

        sImageView.setScaleType(ImageView.ScaleType.CENTER);
        sImageView.setPadding(5,5,5,5);
    } else {
        sImageView = (ShadowImageView) convertView;
    }

    sImageView.setImageBitmap(bitmapList.get(position));
    return sImageView;
}
</code>```

in my ImageView, I still get just a normal ImageView when I run the program.

Any thoughts? Thanks.

EDIT: So I spoke with RomainGuy some in the IRC channel, and I have it working now for plain rectangular images with the below code. It still won't draw the shadow directly to my bitmap's transparency though, so I'm still working on that.

```<code>@Override
protected void onDraw(Canvas canvas)
{
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.omen);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShadowLayer(5.5f, 6.0f, 6.0f, Color.BLACK);
    canvas.drawColor(Color.GRAY);
    canvas.drawRect(50, 50, 50 + bmp.getWidth(), 50 + bmp.getHeight(), paint);
    canvas.drawBitmap(bmp, 50, 50, null);
}
</code>```

答:
Use this class to draw shadow on bitmaps</p>

```<code>public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mIconSize = Utils.convertDpToPixel(context,63);
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }

    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}
</code>```

Title: Custom ImageView with drop shadow

Body:
Okay, I've been reading and searching around, and am now banging my head against the wall trying to figure this out. Here's what I have so far:

package com.pockdroid.sandbox;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.widget.ImageView;

public class ShadowImageView extends ImageView {

private Rect mRect;
private Paint mPaint;

public ShadowImageView(Context context)
{
    super(context);
    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShadowLayer(2f, 1f, 1f, Color.BLACK);
}

@Override
protected void onDraw(Canvas canvas)
{
    Rect r = mRect;
    Paint paint = mPaint;

    canvas.drawRect(r, paint);
    super.onDraw(canvas);
}

@Override
protected void onMeasure(int w, int h)
{
    super.onMeasure(w,h);
    int mH, mW;
    mW = getSuggestedMinimumWidth() < getMeasuredWidth()? getMeasuredWidth() : getSuggestedMinimumWidth();
    mH = getSuggestedMinimumHeight() < getMeasuredHeight()? getMeasuredHeight() : getSuggestedMinimumHeight();
    setMeasuredDimension(mW + 5, mH + 5);
}

}

The "+5" in the measurements are there as temporary; From what I understand I'll need to do some math to determine the size that the drop shadow adds to the canvas, right?

But when I use this:

public View getView(int position, View convertView, ViewGroup parent) {
    ShadowImageView sImageView;
    if (convertView == null) {
        sImageView = new ShadowImageView(mContext);
        GridView.LayoutParams lp = new GridView.LayoutParams(85, 85);
        sImageView.setLayoutParams(lp);

        sImageView.setScaleType(ImageView.ScaleType.CENTER);
        sImageView.setPadding(5,5,5,5);
    } else {
        sImageView = (ShadowImageView) convertView;
    }

    sImageView.setImageBitmap(bitmapList.get(position));
    return sImageView;
}

in my ImageView, I still get just a normal ImageView when I run the program.

Any thoughts? Thanks.

EDIT: So I spoke with RomainGuy some in the IRC channel, and I have it working now for plain rectangular images with the below code. It still won't draw the shadow directly to my bitmap's transparency though, so I'm still working on that.

@Override
protected void onDraw(Canvas canvas)
{
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.omen);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShadowLayer(5.5f, 6.0f, 6.0f, Color.BLACK);
    canvas.drawColor(Color.GRAY);
    canvas.drawRect(50, 50, 50 + bmp.getWidth(), 50 + bmp.getHeight(), paint);
    canvas.drawBitmap(bmp, 50, 50, null);
}

Body:
Use this class to draw shadow on bitmaps

public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mIconSize = Utils.convertDpToPixel(context,63);
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }

    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}