问:
Sending a file to a server using sockets in Python
Mainpage displays my front page and upload is supposed to display the page
where you enter the file you wish to store with the server

```<code>def upload():
        path_name = raw_input("Enter your file directory")
        open_file = open(path_name,'rb').read()
        name_split = path_name.split("\\")[-1].split('.')
        at = 1

        s.send("SAVE-"+username+"\\"+"".join(name_split[:-1])+"."+str(at)+"."+name_split[-1]+"-")

        while open_file:
            current = open_file[:1024]
            print current
            open_file = open_file[1024:]
            s.send(current)

def mainpage():
        global R2
        R2=Tk()
        gg="white"
        g="blue"
        R2.geometry('720x720')
        R2.title(username + " Dropbox")
        R2.resizable(width=False,height=False)
        logoutbt= Button(R2,text="Logout",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=deslogout)
        upload = Button(R2,text="Upload",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desupload)
        retrieve = Button(R2,text="Retreive",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desretreive)
        logoutbt.place(x = 220,y = 500)
        retrieve.place(x = 350,y = 500)
        upload.place(x = 480,y = 500)
        R2.mainloop()
        open(path_name,'rb').close()
</code>```

Now when I add the command mainpage() to return back to to my main page after sending the file to the server,the server gets stuck in an infinite loop

```<code>ServerCode

if message[0] == "SAVE":
                    if not os.path.exists("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0]):
                        os.makedirs("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0])
                    file =open("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+ message[1],"wb")
                    content = ""
                    while True:
                        data = current_socket.recv(1024)
                        if not data:
                            break
                        content += data

                    file.write(content)
                    file.close()
</code>```

The file reaches the server fine when I don't try to return, but the moment I add that one extra line, the server doesn't exit its loop where it receives all the file content. Also,if I try to get a response from the server when it's done writing all the data down, the client and the server get stuck.

答:
Firstly, As a general rule, waiting for the socket to return nothing(empty string or whatever), is a bad idea. That is because in python a socket would only return empty data if the other side closed his socket. But if there was a problem or for any reason the socket was not closed properly, the socket.recv method would hang perhaps infinitely.

Secondly, I see that you intend to instantiate your TKinter App more than once.
This is bad practice, and you should consider just hiding your main window.

Hope I was helpful.

Body:
Mainpage displays my front page and upload is supposed to display the page
where you enter the file you wish to store with the server

def upload():
        path_name = raw_input("Enter your file directory")
        open_file = open(path_name,'rb').read()
        name_split = path_name.split("\\")[-1].split('.')
        at = 1

        s.send("SAVE-"+username+"\\"+"".join(name_split[:-1])+"."+str(at)+"."+name_split[-1]+"-")

        while open_file:
            current = open_file[:1024]
            print current
            open_file = open_file[1024:]
            s.send(current)

def mainpage():
        global R2
        R2=Tk()
        gg="white"
        g="blue"
        R2.geometry('720x720')
        R2.title(username + " Dropbox")
        R2.resizable(width=False,height=False)
        logoutbt= Button(R2,text="Logout",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=deslogout)
        upload = Button(R2,text="Upload",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desupload)
        retrieve = Button(R2,text="Retreive",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desretreive)
        logoutbt.place(x = 220,y = 500)
        retrieve.place(x = 350,y = 500)
        upload.place(x = 480,y = 500)
        R2.mainloop()
        open(path_name,'rb').close()

Now when I add the command mainpage() to return back to to my main page after sending the file to the server,the server gets stuck in an infinite loop

ServerCode

if message[0] == "SAVE":
                    if not os.path.exists("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0]):
                        os.makedirs("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0])
                    file =open("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+ message[1],"wb")
                    content = ""
                    while True:
                        data = current_socket.recv(1024)
                        if not data:
                            break
                        content += data

                    file.write(content)
                    file.close()

The file reaches the server fine when I don't try to return, but the moment I add that one extra line, the server doesn't exit its loop where it receives all the file content. Also,if I try to get a response from the server when it's done writing all the data down, the client and the server get stuck.


来源: stackexchange

问:
foreach not showing results in view
my controller is

```<code><?php

class Blog extends Controller {

function Blog()
    {
        parent::Controller();

    }

    function index()
{

        $data['title']= "this is a blog";
        $data['heading']="Pretty wise";
        $data['query']= $this->db->get('entries');
        $this->load->view('blogview.php',$data);

}

}
?>
</code>```

my view file is

```<code><html>
  <head>
    <title><?= $title ?></title>

</head>
  <body>
    <h1> <?=$heading?></h1>

     <?php foreach($query->result() as $row): ?>

      <h3><?= $row->title ?></h3>
      <p><?= $row->body ?></p>

      <hr>

     <?php endforeach; ?>

   </body>
   </html>
</code>```

the output of this is a page with something like this

```<code>title ?>
body ?>
 ---------------------
title ?>
body ?>
 ---------------------
</code>```

pretty missed up huh ? lol

i am sure about other database connectivity stuff,
i am trying to output two rows in my DB

答:
It looks like you don't have short tags turned on in your apache install.

Short tags allow you to do <?= ?> rather than <?php echo($title); ?>

ContentLicense: CC BY-SA 2.5

Title: foreach not showing results in view

Body:
my controller is

<?php

class Blog extends Controller {

function Blog()
    {
        parent::Controller();

    }

    function index()
{

        $data['title']= "this is a blog";
        $data['heading']="Pretty wise";
        $data['query']= $this->db->get('entries');
        $this->load->view('blogview.php',$data);

}

}
?>

my view file is

    <title><?= $title ?></title>

 <?=$heading?>

     <?php foreach($query->result() as $row): ?>

<?= $row->title ?>

<?= $row->body ?>

     <?php endforeach; ?>

the output of this is a page with something like this

title ?>
body ?>
 ---------------------
title ?>
body ?>
 ---------------------

pretty missed up huh ? lol

i am sure about other database connectivity stuff,
i am trying to output two rows in my DB


问:
How to write unit tests for firebase notification?
I have made the following class to receive firebase messages and create notifications. I have tested it by sending firebase messages to the app and it works perfectly. However, I need to write unit tests to test this feature. But the 2 unit tests I have written for it are failing.
     onMessageReceived() receives data in a RemoteMessage object. It then finds the value of the key type and depending on whether it is 0 or 1, it calls either buildNotificationBigText() or buildNotificationBigPicture() . Hence I have written 2 test methods. In my test methods I have created a RemoteMessage object and passed this to onMessageReceived(). However, these tests are not working correctly and I get the following error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessageBigPicture(MainActivityTest.java:90)

java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
    at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessagesBigText(MainActivityTest.java:80)
</code>```

HandleFirebaseMessages.java

```<code>public class HandleFirebaseMessages extends FirebaseMessagingService {

    /**
     * default id for notification in case specific id is not given in data.
     */
    final int default_id = 42;

    NotificationCompat.Builder builder ;

    /**
     * contains bigTitle value of data in onMessageReceived().
     */
    String bigTitle;

    /**
     * is assigned the bigSummaryText value of data in onMessageReceived().
     */
    String bigSummaryText;

    public HandleFirebaseMessages() {
    }

    /**
     * returns the bitmap image from the url given.
     * @param src image url
     * @return bitmap image at url
     */
    public static Bitmap getBitmapFromURL(final String src) {
        try {
            final URL url = new URL(src);
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            final InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (final IOException e) {
            // Log exception
            Log.e("TAG", "fucked man " + e.getMessage());
            return null;
        }
    }

    /**
     * creates the notification when type is 1 or big text.
     * @param data data to be put in notification
     */
    public void buildNotificationBigText(final Map<String, String> data) {
        Log.e("Tag4", "entered buildNotificationBigText");
        //final String bigTitle = data.get("bigTitle");
        final String bigSubTitle = data.get("bigSubTitle");
        //final String bigSummaryText = data.get("bigSummaryText");

        final NotificationCompat.BigTextStyle notificationBigText = new NotificationCompat.BigTextStyle();

        if (bigTitle != null) {
            notificationBigText.setBigContentTitle(bigTitle);
        }
        if (bigSubTitle != null) {
            notificationBigText.bigText(bigSubTitle);
        }
        if (bigSummaryText != null) {
            notificationBigText.setSummaryText(bigSummaryText);
        }

        builder.setStyle(notificationBigText);
    }

    /**
     * creates the notification when type is 2 or big picture.
     * @param data data to be put in notification
     */
    public void buildNotificationBigPicture(final Map<String, String> data) {
        Log.e("Tag3", "entered buildNotificationBigPicture");
        final String imageUrl = data.get("imageUrl");
        //final String bigSummaryText = data.get("bigSummaryText");
        //final String bigTitle = data.get("bigTitle");

        final NotificationCompat.BigPictureStyle notificationBigPicture = new NotificationCompat.BigPictureStyle();
        if (imageUrl != null) {
            final Bitmap image = getBitmapFromURL(imageUrl);
            if (image != null) {
                notificationBigPicture.bigPicture(image);
            } else {
                //TODO Image is null bt url wasn;t!
            }
        }

        if (bigSummaryText != null) {
            notificationBigPicture.setSummaryText(bigSummaryText);
        }
        if (bigTitle != null) {
            notificationBigPicture.setBigContentTitle(bigTitle);
        }
        //TODO icon
        builder.setStyle(notificationBigPicture);
    }

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.e("Tag1", "onMessageReceived() started");
        final Map<String, String> data = remoteMessage.getData();

        if (data == null) {
            return;
        }

        bigTitle = data.get("bigTitle");
        bigSummaryText = data.get("bigSummaryText");
        final String type = data.get("type");
        final String id = data.get("id");
        final String smallTitle = data.get("smallTitle");
        final String smallSubTitle = data.get("smallSubTitle");
        //final String contentInfo = data.get("contentInfo");
        //final String ticker = data.get("ticker");
        final String link = data.get("link");
        final String className = data.get("className");

        Log.e("Tag2", "type = " + type);

        builder = new NotificationCompat.Builder(this);

        if (type != null) {
            if (type.compareTo("1") == 0) {
                //Large Text Style corresponds to "1"
                buildNotificationBigText(data);
            } else if (type.compareTo("2") == 0) {
                //BigPicture style specific
                buildNotificationBigPicture(data);
            }
        }

        //General things to be added for any kind of notification
        if (smallTitle != null) {
            builder.setContentTitle(smallTitle);
        }
        if (smallSubTitle != null) {
            builder.setContentText(smallSubTitle);
        }

        int notificationId = default_id;
        if (id != null) {
            notificationId = Integer.parseInt(id);
        }
        builder.setContentIntent(addWebsiteLinkPendingIntent(notificationId, link, className));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setCategory(Notification.CATEGORY_SOCIAL);
        }

        builder.setSmallIcon(R.drawable.ic_stat);
        builder.setColor(ContextCompat.getColor(this, R.color.colorPrimary));
        builder.setAutoCancel(true);

        final NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(this);
        mNotificationManager.notify(notificationId, builder.build());

    }

    /**
     * returns the intent for the webpage or activity to open from the notification.
     * @param id notification id
     * @param link webpage link
     * @param className class for the activity to open
     * @return PendingIntent for the webpage ot activity
     */
    private PendingIntent addWebsiteLinkPendingIntent(final int id, final String link, final String className) {
        Intent intent;

        if (link != null) {
            //TODO Change to ChromeCustomTabs later
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
        } else if (className != null) {
            try {
                intent = new Intent(this, Class.forName("com.csatimes.dojma." + className));
                //TODO check for page number
            } catch (final ClassNotFoundException e) {
                intent = new Intent(this, MainActivity.class);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        } else {
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
        }

        return PendingIntent.getActivity(
                this,
                id,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }

}
</code>```

MainActivityTests.java :

```<code>  @RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    private Context context;

    @Mock
    private HandleFirebaseMessages handleFirebaseMessages;

    @Rule
    public ActivityTestRule<MainActivity> activityTestRule =
            new ActivityTestRule<>(MainActivity.class);

    @Before
    public void init() {
        context = InstrumentationRegistry.getTargetContext();
        //MockitoAnnotations.initMocks(this);
        //handleFirebaseMessages = new HandleFirebaseMessages();
    }

     @Test
        public void handleFirebaseMessagesBigText() {
            HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
            RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","1").build();
            handleFirebaseMessages.onMessageReceived(remoteMessage);
            Map<String,String> data = new HashMap<>() ;
            data.put("type","1");
            Mockito.verify(handleFirebaseMessages).buildNotificationBigText(data);
        }

        @Test
        public void handleFirebaseMessagesBigPicture() {
            HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
            RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","2").build();
            handleFirebaseMessages.onMessageReceived(remoteMessage);
            Map<String,String> data = new HashMap<>() ;
            data.put("type","2");
            Mockito.verify(handleFirebaseMessages).buildNotificationBigPicture(data);
        }

}
</code>```

答:
While testing it is advised to limit dependencies that you are testing. You could refactor your code in a way that it would not depend on FirebaseMessagingService.

For example instead of having your logic in onMessageReceived(), you could extract it to separate method preferably in other class (along with other methods from HandleFirebaseMessages) that would not depend on FirebaseMessagingService. It could even be structured so that it relies on plain java code, so that no instrumentation is required to run the test.

This way you would only be testing your code and not other dependencies, which would make it easier to test.

ContentLicense: CC BY-SA 3.0

Body:
I have made the following class to receive firebase messages and create notifications. I have tested it by sending firebase messages to the app and it works perfectly. However, I need to write unit tests to test this feature. But the 2 unit tests I have written for it are failing.
     onMessageReceived() receives data in a RemoteMessage object. It then finds the value of the key type and depending on whether it is 0 or 1, it calls either buildNotificationBigText() or buildNotificationBigPicture() . Hence I have written 2 test methods. In my test methods I have created a RemoteMessage object and passed this to onMessageReceived(). However, these tests are not working correctly and I get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessageBigPicture(MainActivityTest.java:90)

java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
    at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessagesBigText(MainActivityTest.java:80)

HandleFirebaseMessages.java

public class HandleFirebaseMessages extends FirebaseMessagingService {

    /**
     * default id for notification in case specific id is not given in data.
     */
    final int default_id = 42;

    NotificationCompat.Builder builder ;

    /**
     * contains bigTitle value of data in onMessageReceived().
     */
    String bigTitle;

    /**
     * is assigned the bigSummaryText value of data in onMessageReceived().
     */
    String bigSummaryText;

    public HandleFirebaseMessages() {
    }

    /**
     * returns the bitmap image from the url given.
     * @param src image url
     * @return bitmap image at url
     */
    public static Bitmap getBitmapFromURL(final String src) {
        try {
            final URL url = new URL(src);
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            final InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (final IOException e) {
            // Log exception
            Log.e("TAG", "fucked man " + e.getMessage());
            return null;
        }
    }

    /**
     * creates the notification when type is 1 or big text.
     * @param data data to be put in notification
     */
    public void buildNotificationBigText(final Map<String, String> data) {
        Log.e("Tag4", "entered buildNotificationBigText");
        //final String bigTitle = data.get("bigTitle");
        final String bigSubTitle = data.get("bigSubTitle");
        //final String bigSummaryText = data.get("bigSummaryText");

        final NotificationCompat.BigTextStyle notificationBigText = new NotificationCompat.BigTextStyle();

        if (bigTitle != null) {
            notificationBigText.setBigContentTitle(bigTitle);
        }
        if (bigSubTitle != null) {
            notificationBigText.bigText(bigSubTitle);
        }
        if (bigSummaryText != null) {
            notificationBigText.setSummaryText(bigSummaryText);
        }

        builder.setStyle(notificationBigText);
    }

    /**
     * creates the notification when type is 2 or big picture.
     * @param data data to be put in notification
     */
    public void buildNotificationBigPicture(final Map<String, String> data) {
        Log.e("Tag3", "entered buildNotificationBigPicture");
        final String imageUrl = data.get("imageUrl");
        //final String bigSummaryText = data.get("bigSummaryText");
        //final String bigTitle = data.get("bigTitle");

        final NotificationCompat.BigPictureStyle notificationBigPicture = new NotificationCompat.BigPictureStyle();
        if (imageUrl != null) {
            final Bitmap image = getBitmapFromURL(imageUrl);
            if (image != null) {
                notificationBigPicture.bigPicture(image);
            } else {
                //TODO Image is null bt url wasn;t!
            }
        }

        if (bigSummaryText != null) {
            notificationBigPicture.setSummaryText(bigSummaryText);
        }
        if (bigTitle != null) {
            notificationBigPicture.setBigContentTitle(bigTitle);
        }
        //TODO icon
        builder.setStyle(notificationBigPicture);
    }

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.e("Tag1", "onMessageReceived() started");
        final Map<String, String> data = remoteMessage.getData();

        if (data == null) {
            return;
        }

        bigTitle = data.get("bigTitle");
        bigSummaryText = data.get("bigSummaryText");
        final String type = data.get("type");
        final String id = data.get("id");
        final String smallTitle = data.get("smallTitle");
        final String smallSubTitle = data.get("smallSubTitle");
        //final String contentInfo = data.get("contentInfo");
        //final String ticker = data.get("ticker");
        final String link = data.get("link");
        final String className = data.get("className");

        Log.e("Tag2", "type = " + type);

        builder = new NotificationCompat.Builder(this);

        if (type != null) {
            if (type.compareTo("1") == 0) {
                //Large Text Style corresponds to "1"
                buildNotificationBigText(data);
            } else if (type.compareTo("2") == 0) {
                //BigPicture style specific
                buildNotificationBigPicture(data);
            }
        }

        //General things to be added for any kind of notification
        if (smallTitle != null) {
            builder.setContentTitle(smallTitle);
        }
        if (smallSubTitle != null) {
            builder.setContentText(smallSubTitle);
        }

        int notificationId = default_id;
        if (id != null) {
            notificationId = Integer.parseInt(id);
        }
        builder.setContentIntent(addWebsiteLinkPendingIntent(notificationId, link, className));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setCategory(Notification.CATEGORY_SOCIAL);
        }

        builder.setSmallIcon(R.drawable.ic_stat);
        builder.setColor(ContextCompat.getColor(this, R.color.colorPrimary));
        builder.setAutoCancel(true);

        final NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(this);
        mNotificationManager.notify(notificationId, builder.build());

    }

    /**
     * returns the intent for the webpage or activity to open from the notification.
     * @param id notification id
     * @param link webpage link
     * @param className class for the activity to open
     * @return PendingIntent for the webpage ot activity
     */
    private PendingIntent addWebsiteLinkPendingIntent(final int id, final String link, final String className) {
        Intent intent;

        if (link != null) {
            //TODO Change to ChromeCustomTabs later
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
        } else if (className != null) {
            try {
                intent = new Intent(this, Class.forName("com.csatimes.dojma." + className));
                //TODO check for page number
            } catch (final ClassNotFoundException e) {
                intent = new Intent(this, MainActivity.class);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        } else {
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
        }

        return PendingIntent.getActivity(
                this,
                id,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }

}

MainActivityTests.java :

  @RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    private Context context;

    @Mock
    private HandleFirebaseMessages handleFirebaseMessages;

    @Rule
    public ActivityTestRule<MainActivity> activityTestRule =
            new ActivityTestRule<>(MainActivity.class);

    @Before
    public void init() {
        context = InstrumentationRegistry.getTargetContext();
        //MockitoAnnotations.initMocks(this);
        //handleFirebaseMessages = new HandleFirebaseMessages();
    }

     @Test
        public void handleFirebaseMessagesBigText() {
            HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
            RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","1").build();
            handleFirebaseMessages.onMessageReceived(remoteMessage);
            Map<String,String> data = new HashMap<>() ;
            data.put("type","1");
            Mockito.verify(handleFirebaseMessages).buildNotificationBigText(data);
        }

        @Test
        public void handleFirebaseMessagesBigPicture() {
            HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
            RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","2").build();
            handleFirebaseMessages.onMessageReceived(remoteMessage);
            Map<String,String> data = new HashMap<>() ;
            data.put("type","2");
            Mockito.verify(handleFirebaseMessages).buildNotificationBigPicture(data);
        }

}


问:
Support native recursion
I read an article about recursion in Haskell that says:

But the lambda calculus does not appear on the surface to have any
  means of recursion, because of the anonymity of expressions. How do
  you call something without a name? Being able to write recursive
  functions, though, is essential to Turing completeness. We use a
  combinator – known as the Y combinator or fixed-point combinator – to
  write recursive functions in the lambda calculus. Haskell has native
  recursion ability based on the same principle as the Y combinator.

What does native recursion mean?

Consider following code snippet:

```<code>applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)
</code>```

The above code does not conform Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

Please proof my answer, if I wrong.

答:
“Native recursion” just means that Haskell has recursion as a “native” (built-in) language feature, in the form of recursive definitions and let bindings:

```<code>-- Recursive definition
map f (x : xs) = f x : map f xs
                       ---
map _ [] = []

-- Recursive “let” binding
main = let ones = 1 : ones in print (take 10 ones)
                      ----
</code>```

Internally, the compiler could rewrite these using a fixed-point combinator (fix), for example as a simplification before typechecking, but I’m not aware if it actually does this.

```<code>map f xs = let
  map' k (x : xs) = f x : k xs
  map' _ [] = []
  in fix map' xs

main = let
  ones = fix ones'
  ones' k = 1 : k
  in print (take 10 ones)
</code>```

In Haskell, the fixed-point combinator is implemented using the native support for recursive bindings:

```<code>-- Naïve implementation
fix f = f (fix f)

-- Optimisation to improve sharing
fix f = let x = f x in x
</code>```

And any recursive function can be expressed using fix:

```<code>applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)

applyTimes n f b = let
  applyTimes' _ 0 = b
  applyTimes' k n = f (k (n - 1))
  in fix applyTimes' n
</code>```

Note that without native recursion, the Y combinator \ f -> (\ x -> f (x x)) (\ x -> f (x x)) can’t be expressed in simply typed lambda calculus because there is no type for x that would allow it to be a function taking x as an argument. Specifically, it fails the “occurs check”: if x is a function then it must have a type of the form a -> b, but if x is passed as an argument to x then it must have the type a. Clearly a cannot equal a -> b because a occurs in a -> b, so it would expand infinitely: a -> b, (a -> b) -> b, ((a -> b) -> b) -> b, and so on.

While Haskell’s type system is more powerful than STLC, it’s typical for typed functional languages to offer recursion as a primitive part of the language rather than with a fixed-point combinator.

Title: Support native recursion

Body:
I read an article about recursion in Haskell that says:

But the lambda calculus does not appear on the surface to have any
  means of recursion, because of the anonymity of expressions. How do
  you call something without a name? Being able to write recursive
  functions, though, is essential to Turing completeness. We use a
  combinator – known as the Y combinator or fixed-point combinator – to
  write recursive functions in the lambda calculus. Haskell has native
  recursion ability based on the same principle as the Y combinator.

What does native recursion mean?

Consider following code snippet:

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)

The above code does not conform Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

Please proof my answer, if I wrong.

Body:
“Native recursion” just means that Haskell has recursion as a “native” (built-in) language feature, in the form of recursive definitions and let bindings:

-- Recursive definition
map f (x : xs) = f x : map f xs
                       ---
map _ [] = []

-- Recursive “let” binding
main = let ones = 1 : ones in print (take 10 ones)
                      ----

Internally, the compiler could rewrite these using a fixed-point combinator (fix), for example as a simplification before typechecking, but I’m not aware if it actually does this.

map f xs = let
  map' k (x : xs) = f x : k xs
  map' _ [] = []
  in fix map' xs

main = let
  ones = fix ones'
  ones' k = 1 : k
  in print (take 10 ones)

In Haskell, the fixed-point combinator is implemented using the native support for recursive bindings:

-- Naïve implementation
fix f = f (fix f)

-- Optimisation to improve sharing
fix f = let x = f x in x

And any recursive function can be expressed using fix:

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)

applyTimes n f b = let
  applyTimes' _ 0 = b
  applyTimes' k n = f (k (n - 1))
  in fix applyTimes' n

Note that without native recursion, the Y combinator \ f -> (\ x -> f (x x)) (\ x -> f (x x)) can’t be expressed in simply typed lambda calculus because there is no type for x that would allow it to be a function taking x as an argument. Specifically, it fails the “occurs check”: if x is a function then it must have a type of the form a -> b, but if x is passed as an argument to x then it must have the type a. Clearly a cannot equal a -> b because a occurs in a -> b, so it would expand infinitely: a -> b, (a -> b) -> b, ((a -> b) -> b) -> b, and so on.

While Haskell’s type system is more powerful than STLC, it’s typical for typed functional languages to offer recursion as a primitive part of the language rather than with a fixed-point combinator.


问:
Counter in arrays c++
i have a really simple code right there that counts how much values you need in arrays.

```<code>for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };
</code>```

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

答:
Solution without using additional array:

```<code>int twins_counter = 0;
for (int i = 0; i < dm; i++)
{
    int counter = 0; // counter for elements
    for (int j = 0; j < dm; j++)
    {
        if (arr[i] == arr[j])
        {
            if( j < i )
            {
                 break; // we have searched twin for this element already
            }
            counter++;
            if( counter > 2 )
            {
                break; // we meet element third time, it isn't twin
            }
        }
    }

    if( counter == 2 )
    {
          twins_counter++;
     }
};
</code>```

For sorted (upwards or downwards) arrays one cycle is enough:

```<code>int twins_counter = 0;
int counter = 1;

for (int i = 1; i < dm; i++)
{
    if( arr[i] == arr[i-1] )
    {
         counter++;
     }
     else
     {
           if( counter == 2 )
           {
                 twins_counter++;
                 counter = 1;
           }
     }
}

// check last value
if( counter == 2 )
{
    twins_counter++;
}
</code>```

Title: Counter in arrays c++

Body:
i have a really simple code right there that counts how much values you need in arrays.

for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

Body:
Solution without using additional array:

int twins_counter = 0;
for (int i = 0; i < dm; i++)
{
    int counter = 0; // counter for elements
    for (int j = 0; j < dm; j++)
    {
        if (arr[i] == arr[j])
        {
            if( j < i )
            {
                 break; // we have searched twin for this element already
            }
            counter++;
            if( counter > 2 )
            {
                break; // we meet element third time, it isn't twin
            }
        }
    }

    if( counter == 2 )
    {
          twins_counter++;
     }
};

For sorted (upwards or downwards) arrays one cycle is enough:

int twins_counter = 0;
int counter = 1;

for (int i = 1; i < dm; i++)
{
    if( arr[i] == arr[i-1] )
    {
         counter++;
     }
     else
     {
           if( counter == 2 )
           {
                 twins_counter++;
                 counter = 1;
           }
     }
}

// check last value
if( counter == 2 )
{
    twins_counter++;
}


问:
SVG Circles - Animate Segments? (Doughnut Chart)
```<code><svg width="210px" height="210px" viewBox="0 0 210 210" class="donut">
<circle class="donut-ring" cx="105" cy="105" r="95" fill="transparent" stroke="black" stroke-width="20"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#1a1a1a" stroke-width="20" stroke-dasharray="149.22565104551518 447.67695313654554" stroke-dashoffset="150"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#333333" stroke-width="20" stroke-dasharray="149.22565104551518 447.67695313654554" stroke-dashoffset="597.6769531365455"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#434343" stroke-width="20" stroke-dasharray="298.45130209103036 298.45130209103036" stroke-dashoffset="448.45130209103036"></circle>
</svg>
</code>```

Basically my problem is iv'e created a dynamic doughnut chart where the segments are automatically generated (class="donut-segment"). I need to make all the segments animate simultaneously from their start point to their end point. Iv'e done some pretty extensive searching but i can't find a example quite like mine. Any help at all would be greatly appreciated or just a point in the right direction.

I need the end result to have this effect
https://codepen.io/ksksoft/pen/xsnmp

答: Solved, Transitioned Stroke-DashArray from "0 and 600" into their proper values, and also transitioned the strokeDashOffset from 0 to its proper value</p>

Body:
<svg width="210px" height="210px" viewBox="0 0 210 210" class="donut">
<circle class="donut-ring" cx="105" cy="105" r="95" fill="transparent" stroke="black" stroke-width="20"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#1a1a1a" stroke-width="20" stroke-dasharray="149.22565104551518 447.67695313654554" stroke-dashoffset="150"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#333333" stroke-width="20" stroke-dasharray="149.22565104551518 447.67695313654554" stroke-dashoffset="597.6769531365455"></circle>
<circle class="donut-segment" cx="105" cy="105" r="95" fill="transparent" stroke="#434343" stroke-width="20" stroke-dasharray="298.45130209103036 298.45130209103036" stroke-dashoffset="448.45130209103036"></circle>
</svg>

Basically my problem is iv'e created a dynamic doughnut chart where the segments are automatically generated (class="donut-segment"). I need to make all the segments animate simultaneously from their start point to their end point. Iv'e done some pretty extensive searching but i can't find a example quite like mine. Any help at all would be greatly appreciated or just a point in the right direction.

I need the end result to have this effect
https://codepen.io/ksksoft/pen/xsnmp


问:
Get the value of a computed property in Vue.js and use it in a data property
I have a computed property countryName which returns a country name based on a country code and works fine. I need the use the countryName value as the value of the label of the country data property but I get undefined.

```<code>export default {
    props: ['content'],
    data () {
        return {
            countries: require('../../plugins/countries'),
            country: {
                value: this.content.country_code,
                label: this.countryName
            }
        }
    },
    computed: {
        countryName () {
            return this.countries.find(item => item.value === this.content.country_code).label
        }
    }
}
</code>```

答:
When the component is instantiated, the data function is called before the computed properties are added to the component. That's why you get undefined. Try setting it in mounted or created.

```<code>data () {
    return {
        countries: require('../../plugins/countries'),
        country: {
            value: this.content.country_code,
            label: null
        }
    }
},
computed: {
    countryName () {
        return this.countries.find(item => item.value === this.content.country_code).label
    }
},
mounted(){
    this.country.label = this.countryName
}
</code>```

For the curious, this is the initState function as of Vue 2.3.3

```<code>function initState (vm) {
  vm._watchers = [];
  var opts = vm.$options;
  if (opts.props) { initProps(vm, opts.props); }
  if (opts.methods) { initMethods(vm, opts.methods); }
  if (opts.data) {
    initData(vm);
  } else {
    observe(vm._data = {}, true /* asRootData */);
  }
  if (opts.computed) { initComputed(vm, opts.computed); }
  if (opts.watch) { initWatch(vm, opts.watch); }
}
</code>```

Body:
I have a computed property countryName which returns a country name based on a country code and works fine. I need the use the countryName value as the value of the label of the country data property but I get undefined.

export default {
    props: ['content'],
    data () {
        return {
            countries: require('../../plugins/countries'),
            country: {
                value: this.content.country_code,
                label: this.countryName
            }
        }
    },
    computed: {
        countryName () {
            return this.countries.find(item => item.value === this.content.country_code).label
        }
    }
}

Body:
When the component is instantiated, the data function is called before the computed properties are added to the component. That's why you get undefined. Try setting it in mounted or created.

data () {
    return {
        countries: require('../../plugins/countries'),
        country: {
            value: this.content.country_code,
            label: null
        }
    }
},
computed: {
    countryName () {
        return this.countries.find(item => item.value === this.content.country_code).label
    }
},
mounted(){
    this.country.label = this.countryName
}

For the curious, this is the initState function as of Vue 2.3.3

function initState (vm) {
  vm._watchers = [];
  var opts = vm.$options;
  if (opts.props) { initProps(vm, opts.props); }
  if (opts.methods) { initMethods(vm, opts.methods); }
  if (opts.data) {
    initData(vm);
  } else {
    observe(vm._data = {}, true /* asRootData */);
  }
  if (opts.computed) { initComputed(vm, opts.computed); }
  if (opts.watch) { initWatch(vm, opts.watch); }
}


问:
Cocoa - controlTextDidEndEditing issue
I have the following delegate method which is listening for when text changes in an editable field:

-(void)controlTextDidEndEditing:(NSNotification *)aNotification{

Say, I have two NSTextFields declared, how can I find out which is the NSTextField that generated the notification? I want to perform some code when one text field's text did finish editing and other code when the other text field's code finishes editing.

In other words, how can I get the name of the text field that gave the notification?

Thank you!

答:
You could use tags and get the tag field of the object, but first you have to force downcast the object from Any to NSTextField so you can access the tag property (an object of "any" doesn't have a "tag" property) like so:

```<code>let object = aNotification.object as! NSTextField
</code>```

then you can check the tag:

```<code>if object.tag == 99 { do something }
</code>```

That's how I addressed the issue in some of the code I'm working on now.

Title: Cocoa - controlTextDidEndEditing issue

Body:
You could use tags and get the tag field of the object, but first you have to force downcast the object from Any to NSTextField so you can access the tag property (an object of "any" doesn't have a "tag" property) like so:

let object = aNotification.object as! NSTextField

then you can check the tag:

if object.tag == 99 { do something }

That's how I addressed the issue in some of the code I'm working on now.


问:
How to set up kubernetes NGINX ingress in AWS and SSL termination
I set up a kubernetes cluster in AWS using KOPS; now I want to set up an NGINX ingress controller and terminate TLS with AWS managed certificate. The topology in my understanding is AWS ELB is facing the internet and terminates TLS, forwards unencrypted to ingress service which then does dispatches.

I've deployed ingress controller from https://github.com/kubernetes/ingress/tree/master/examples/aws/nginx

Except I used annotations as described on top of https://github.com/kubernetes/ingress/issues/71 to add the certificate.

I add the route to Route53 and open my browser to https address and get a 400 response from NGINX with message "The plain HTTP request was sent to HTTPS port"

What am I doing wrong?

This is my ingress resource:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
  name: dispatcher
  namespace: test
spec:
  rules:
  - host: REDACTED
    http:
      paths:
      - backend:
          serviceName: REDACTED
          servicePort: 80
        path: /api/v0
</code>```

答:
https://github.com/kubernetes/ingress/tree/master/controllers/nginx#https

TL;DR

1) create a secret with your ssl public/private in your namespace

2) add the tls block to your ingress (referencing the secret)

Body:
I set up a kubernetes cluster in AWS using KOPS; now I want to set up an NGINX ingress controller and terminate TLS with AWS managed certificate. The topology in my understanding is AWS ELB is facing the internet and terminates TLS, forwards unencrypted to ingress service which then does dispatches.

I've deployed ingress controller from https://github.com/kubernetes/ingress/tree/master/examples/aws/nginx

Except I used annotations as described on top of https://github.com/kubernetes/ingress/issues/71 to add the certificate.

I add the route to Route53 and open my browser to https address and get a 400 response from NGINX with message "The plain HTTP request was sent to HTTPS port"

What am I doing wrong?

This is my ingress resource:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
  name: dispatcher
  namespace: test
spec:
  rules:
  - host: REDACTED
    http:
      paths:
      - backend:
          serviceName: REDACTED
          servicePort: 80
        path: /api/v0


问:
Android Bluetooth low energy pairing show/hide Pin already loaded dialog

I am trying to write a simple android app that pairs to an nrf52 device(Bluetooth LOW ENERGY, not classic bluetooth). I would like the above image to pop up( I got this image from https://developer.android.com/guide/topics/connectivity/bluetooth.html)

But I am actually getting following image when I try to create bond/pair, how to make the above image show up instead of the below one? Or how do I setpin without any android prompt/notification coming up?

答:
It turns out it is not something you can set on the android app. On the target device you need to make sure Bluetooth 4.2 is enabled, and set pairing option with displayYesNo. Take a look at https://www.rigado.com/inexpensive-secure-ble-devices/

So now on my Google pixel 7.1.2, I will get a notification when I try to pair my target device, and if I click on the notification the 6 digit comfirmation screen would show up, and I can click "pair" or "cancel". But if your android phone is too old, it would fall back to asking you to enter 6 digit pins.


问:
Python: How to combine two SQL queries
As I have limited knowledge about Python how can I crate in Python one query  which will contains both from below where second will be queried for when first will return not results (no email address returned)

Code blow

```<code>bits = sys.argv[1].split('@')
if len(bits) != 2:
    sys.exit(0)

cur.execute("SELECT email FROM notifications WHERE diraddr = %s", (sys.argv[1],))
cur.execute("SELECT email FROM users WHERE (username LIKE %s) AND (domain LIKE %s) and notifications = 'Y'", (bits[0], bits[1]))
</code>```

I have tried to do IF...ELSE for email return results from  first SQL query but it looks like can be done in one query without IF...ELSE statement.

答:
It depends -- what do you mean by "combine?" Do you mean concatenate row-wise? If so, you're looking for UNION ALL:

```<code>cur.execute("SELECT email FROM notifications WHERE diraddr = {0} UNION ALL SELECT email FROM users WHERE (username LIKE {1}) AND (domain LIKE {2}) and notifications = 'Y'".format(sys.argv[1], bits[0], bits[1]))
</code>```

The UNION ALL operator combines the results from multiple queries, as long as they have the same number of columns. This will work even if one (or both) of the subqueries return no results.

Note: I updated your code using Python's .format() method.

Title: Python: How to combine two SQL queries

Body:
As I have limited knowledge about Python how can I crate in Python one query  which will contains both from below where second will be queried for when first will return not results (no email address returned)

Code blow

bits = sys.argv[1].split('@')
if len(bits) != 2:
    sys.exit(0)

cur.execute("SELECT email FROM notifications WHERE diraddr = %s", (sys.argv[1],))
cur.execute("SELECT email FROM users WHERE (username LIKE %s) AND (domain LIKE %s) and notifications = 'Y'", (bits[0], bits[1]))

I have tried to do IF...ELSE for email return results from  first SQL query but it looks like can be done in one query without IF...ELSE statement.

Body:
It depends -- what do you mean by "combine?" Do you mean concatenate row-wise? If so, you're looking for UNION ALL:

cur.execute("SELECT email FROM notifications WHERE diraddr = {0} UNION ALL SELECT email FROM users WHERE (username LIKE {1}) AND (domain LIKE {2}) and notifications = 'Y'".format(sys.argv[1], bits[0], bits[1]))

The UNION ALL operator combines the results from multiple queries, as long as they have the same number of columns. This will work even if one (or both) of the subqueries return no results.

Note: I updated your code using Python's .format() method.


问:
LoadTest on dummy server succeeds after setting Time to Live or TTL in HttpConnPool, but what does it do?
What does the Time to Live (TTL) variable in the HttpConnPool.class from the package org.apache.http.impl.conn; do?

I was running some load tests on a dummy server. When I am passing close to 9 requests per second. I got random NoHttpResponseException, target failed to respond or dummy server failed to respond.

Then I added a property called "TTL" or "TimetoLive" and gave it a value. The HttpResponseException stopped arising. I would like to know what this variable does to prevent the NoHttpResponseException to arise in the first place.

答:
Actually I have figured out the answer myself.

In my load testing, initially we got "NoHttpResponseException, target server @Somelink:PortNumber failed to respond." during loadtest because httpClient maintains persistent connections meaning one and same connection to send multiple requests. It is more efficient this way. There is an evictor thread which we have set for certain milliseconds or seconds. The evictor thread will remove idle connection after certain milliseconds. During production there is a possibility of having a idle connection as we do not have traffic all the time. Now during Load test, the connection will not be idle as we keep sending requests all the time to the client server. Hence the connection will not be evicted and the TTL property was set to Default value of "-1" which means infinite (This is for my application, for every application it depends on the value set by the developer).

TTL is the property that defines how long a connection must be active regardless if its idle or not. If the property is set to "-1", then the connection will remain active forever or at least until the client server closes it. The client server usually closes the connection after certain time. No server maintains a connection forever. A new connection will always be established.

During this time when the client close our connection, our server will assume that the connection is established but the client did not send a response. Hence it returns NoHttpResponseException i.e., the target server failed to respond. Adding TTL property will ensure to remove any persistent connection regardless if it is idle or not. Hence we will always have a new connection preventing an NoHttpResponseException.

I hope this helps.


问:
@font-face printing issue in Firefox
First off, apologies if this is a simple thing, but I did a search here after googling and came up with nothing concrete: http://stackoverflow.com/search?q=[%40font-face]+print%2C+firefox

I have generated an @font-face kit with font squirrel with two licensed open type fonts. The demo works fine in all browsers except for 1 issue. I want the font to print, and it does for IE, but printing the document in Firefox 3.6.12 & Chrome 8.0.552.215.

Should the FS demo font be printable in FF and GC or is this impossible to do?

Thanks!

答:
Been having a similar problem and starting to think the issue in with Firefox.  A few things seem to point to it being a bug in the 3.6.13 version, but it is also possible that the font file has an invalid cmap problem as Firefox stopped rendering those as of 3.5.4.

More Info:

http://support.mozilla.com/ak/questions/769971

http://support.mozilla.com/sq/questions/761014

invalid cmap problem:
https://bugzilla.mozilla.org/show_bug.cgi?id=526869

Title: @font-face printing issue in Firefox


问:
Export Excel Range to Access table VBA
I want to have a button on the Excel spreadsheet and have the data copied to the Access table.
The range is an auto-populated field from another sheet in the same workbook.

I tried few codes to make this happen, but I either get an error 1004: application-defined or object-defined error, or no error but data not being copied in Access DB.

My code is copied below.

```<code>Sub Export_Data()

    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim dbPath
    Dim x As Long, i As Long

    dbPath = "H:\RFD\RequestForData.accdb"

    Set cnn = New ADODB.Connection

    cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    Set rst = New ADODB.Recordset 'assign memory to the recordset

    rst.Open Source:="tblRequests", ActiveConnection:=cnn, _
             CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
             Options:=adCmdTable

    rst.AddNew
    For i = 1 To 13
        rst(Cells(1, i).Value) = Cells(x, i).Value
    Next i
    rst.Update

    rst.Close
    cnn.Close

    Set rst = Nothing
    Set cnn = Nothing

    MsgBox " The data has been successfully sent to the access database"

    Set rst = Nothing
    Set cnn = Nothing

End Sub
</code>```

答:
Looking at your Subroutine I see two things that can make it not to work:

rst(Cells(1, i).Value) = Cells(x, i).Value  <- Where is 'x' initialized?

There is only one loop that moves over the fields but I think it should be another loop for the rows in the Excel.

With this two changes, the loop when the records are save could become something like this:

```<code>    For x = 1 TO lastRow   ' Last row has to be calculated somehow
        rst.AddNew
        For i = 1 To 13
            rst(Cells(1, i).Value) = Cells(x, i).Value
        Next i
        rst.Update
    Next x
</code>```

Hope it helps.

Title: Export Excel Range to Access table VBA

Body:
I want to have a button on the Excel spreadsheet and have the data copied to the Access table.
The range is an auto-populated field from another sheet in the same workbook.

I tried few codes to make this happen, but I either get an error 1004: application-defined or object-defined error, or no error but data not being copied in Access DB.

My code is copied below.

Sub Export_Data()

    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim dbPath
    Dim x As Long, i As Long

    dbPath = "H:\RFD\RequestForData.accdb"

    Set cnn = New ADODB.Connection

    cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    Set rst = New ADODB.Recordset 'assign memory to the recordset

    rst.Open Source:="tblRequests", ActiveConnection:=cnn, _
             CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
             Options:=adCmdTable

    rst.AddNew
    For i = 1 To 13
        rst(Cells(1, i).Value) = Cells(x, i).Value
    Next i
    rst.Update

    rst.Close
    cnn.Close

    Set rst = Nothing
    Set cnn = Nothing

    MsgBox " The data has been successfully sent to the access database"

    Set rst = Nothing
    Set cnn = Nothing

End Sub

Body:
Looking at your Subroutine I see two things that can make it not to work:

rst(Cells(1, i).Value) = Cells(x, i).Value  <- Where is 'x' initialized?

There is only one loop that moves over the fields but I think it should be another loop for the rows in the Excel.

With this two changes, the loop when the records are save could become something like this:

    For x = 1 TO lastRow   ' Last row has to be calculated somehow
        rst.AddNew
        For i = 1 To 13
            rst(Cells(1, i).Value) = Cells(x, i).Value
        Next i
        rst.Update
    Next x

Hope it helps.


问:
Cannot resolve corresponding jni function opencv Android
this is where i get error.I loaded correctly opencv library but i get this error.If i go in the ximgproc all native methods are red marked with "Cannot resolve corresponding jni function name_function".How can i resolve?

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            //Log.i("prova",uri.toString());
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
           // imageView.setImageBitmap(bitmap);
            Mat g=new Mat(bitmap.getHeight(),bitmap.getWidth(), CvType.CV_8UC1);
            Utils.bitmapToMat(bitmap,g,true);
            SuperpixelSLIC x=Ximgproc.createSuperpixelSLIC(g,Ximgproc.SLIC,100,3);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

and this is the error that i get:

```<code>06-07 19:24:01.370 21090-21090/com.example.jt1995.provaemo E/art: No implementation found for long org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(long, int, int, float) (tried Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF)
06-07 19:24:01.370 21090-21090/com.example.jt1995.provaemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.jt1995.provaemo, PID: 21090
                                                                             java.lang.UnsatisfiedLinkError: No implementation found for long org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(long, int, int, float) (tried Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF)
                                                                                at org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(Native Method)
                                                                                at org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC(Ximgproc.java:452)
                                                                                at com.example.jt1995.provaemo.MainActivity.onActivityResult(MainActivity.java:108)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6303)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3818)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3865)
                                                                                at android.app.ActivityThread.access$1700(ActivityThread.java:159)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5569)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:931)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:726)
</code>```

答:
As I explained elsewhere, don't expect Android Studio to resolve magically the native method declarations into a library that is not built with gradle in integrated externalNativeBuild.

You can simply ignore this error message: your APK will still install the prebuilt library, and the native methods will be resolved at run time, even if Android Studio marks them red.

You can add @SuppressWarnings("JniMissingFunction") annotation for this method, or for the entire class:

```<code>@SuppressWarnings("JniMissingFunction")
public class Ximgproc {
</code>```

or configure this kind of Lint inspections for the given project, or for all projects:

But this does not resolve your runtime problem. You presumably have built your C++ code to produce a native shared library, say its name is libXimgproc-native.so. If it is packed correctly into your APK, it will be extracted to /data/app-lib/com.example.jt1995.provaemo/ (you can check this path with getContext().getApplicationInfo().nativeLibraryDir).

Your Java code should load this library before it tries to call the native methods of the org.opencv.ximgproc.Ximgproc class:

```<code>System.load("Ximgproc-native");
</code>```

If all above assumptions are correct, the linker did not find an exported function in that library that implements the createSuperpixelSLIC_0 native method. It tried both Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF.

To check which methods are exported by the library, you can use the nm tool which is part of the NDK gcc toolchain. E.g. on my Mac this executable can be found at ~/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-nm.

Run …nm -D Ximgproc-native.so and it will list, with T, all exported functions of your library.

I believe you will not find your function in this list. Maybe, the name is slightly wrong. Maybe, you set CFLAGS to -fvisibility=hidden, and did not explicitly declare the function as JNIEXPORT (or __attribute__ ((visibility ("default")))). Maybe, the C++ function is not declared with extern "C", and its name is mangled by the compiler.

If you use static libraries (xxx.a) as intermediates to assemble the resulting shared library, you should know that the linker can throw away unused external functions. In such case, using LOCAL_WHOLE_STATIC_LIBRARIES instead of LOCAL_STATIC_LIBRARIES may help.

Body:
this is where i get error.I loaded correctly opencv library but i get this error.If i go in the ximgproc all native methods are red marked with "Cannot resolve corresponding jni function name_function".How can i resolve?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            //Log.i("prova",uri.toString());
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
           // imageView.setImageBitmap(bitmap);
            Mat g=new Mat(bitmap.getHeight(),bitmap.getWidth(), CvType.CV_8UC1);
            Utils.bitmapToMat(bitmap,g,true);
            SuperpixelSLIC x=Ximgproc.createSuperpixelSLIC(g,Ximgproc.SLIC,100,3);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

and this is the error that i get:

06-07 19:24:01.370 21090-21090/com.example.jt1995.provaemo E/art: No implementation found for long org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(long, int, int, float) (tried Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF)
06-07 19:24:01.370 21090-21090/com.example.jt1995.provaemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.jt1995.provaemo, PID: 21090
                                                                             java.lang.UnsatisfiedLinkError: No implementation found for long org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(long, int, int, float) (tried Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF)
                                                                                at org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC_0(Native Method)
                                                                                at org.opencv.ximgproc.Ximgproc.createSuperpixelSLIC(Ximgproc.java:452)
                                                                                at com.example.jt1995.provaemo.MainActivity.onActivityResult(MainActivity.java:108)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6303)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3818)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3865)
                                                                                at android.app.ActivityThread.access$1700(ActivityThread.java:159)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5569)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:931)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:726)

Body:
As I explained elsewhere, don't expect Android Studio to resolve magically the native method declarations into a library that is not built with gradle in integrated externalNativeBuild.

You can simply ignore this error message: your APK will still install the prebuilt library, and the native methods will be resolved at run time, even if Android Studio marks them red.

You can add @SuppressWarnings("JniMissingFunction") annotation for this method, or for the entire class:

@SuppressWarnings("JniMissingFunction")
public class Ximgproc {

or configure this kind of Lint inspections for the given project, or for all projects:

But this does not resolve your runtime problem. You presumably have built your C++ code to produce a native shared library, say its name is libXimgproc-native.so. If it is packed correctly into your APK, it will be extracted to /data/app-lib/com.example.jt1995.provaemo/ (you can check this path with getContext().getApplicationInfo().nativeLibraryDir).

Your Java code should load this library before it tries to call the native methods of the org.opencv.ximgproc.Ximgproc class:

System.load("Ximgproc-native");

If all above assumptions are correct, the linker did not find an exported function in that library that implements the createSuperpixelSLIC_0 native method. It tried both Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10 and Java_org_opencv_ximgproc_Ximgproc_createSuperpixelSLIC_10__JIIF.

To check which methods are exported by the library, you can use the nm tool which is part of the NDK gcc toolchain. E.g. on my Mac this executable can be found at ~/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-nm.

Run …nm -D Ximgproc-native.so and it will list, with T, all exported functions of your library.

I believe you will not find your function in this list. Maybe, the name is slightly wrong. Maybe, you set CFLAGS to -fvisibility=hidden, and did not explicitly declare the function as JNIEXPORT (or __attribute__ ((visibility ("default")))). Maybe, the C++ function is not declared with extern "C", and its name is mangled by the compiler.

If you use static libraries (xxx.a) as intermediates to assemble the resulting shared library, you should know that the linker can throw away unused external functions. In such case, using LOCAL_WHOLE_STATIC_LIBRARIES instead of LOCAL_STATIC_LIBRARIES may help.


问:
How to print escaped HTML characters in Oracle XML Publisher
I am using Oracle's XML Publisher (based on Oracle XML Parser 10.1.0.5.0) to generate reports from my db using an .RTF template.

In my front end the user enters some values in a CK Editor like the following image:

In the database the values are saved correctly as shown below:

When I print the report in PDF format using XML Publisher I get the escaped HTML characters like this:

Is there a way to fix this and print the normal characters instead of the escaped ones?

Thanks a lot in advance

答:
Starting with Oracle 11g you are able to use the PL/SQL package UTL_I18N.

UTL_I18N is a set of services that provides additional globalization functionality for applications.

One of the relevant methods in this context is "UTL_I18N.UNESCAPE_REFERENCE":

SELECT UTL_I18N.UNESCAPE_REFERENCE('ABC < & "') FROM DUAL;
```

With this you will get an output like: ABC < & "

Here are some more information provided by Oracle:
https://docs.oracle.com/database/121/ARPLS/u_i18n.htm#ARPLS71170

Body:
Starting with Oracle 11g you are able to use the PL/SQL package UTL_I18N.

UTL_I18N is a set of services that provides additional globalization functionality for applications.

One of the relevant methods in this context is "UTL_I18N.UNESCAPE_REFERENCE":

SELECT UTL_I18N.UNESCAPE_REFERENCE('ABC &lt; &#38; &#34;') FROM DUAL;

With this you will get an output like: ABC < & "

Here are some more information provided by Oracle:
https://docs.oracle.com/database/121/ARPLS/u_i18n.htm#ARPLS71170


问:
Calculate Derivative of Function at a Point in R
Reading through this documentation in R, I don't understand how to take a derivative of the function at a specific point.

They do it here in C (with gsl_deriv_central/forward/backward), but I was wondering if there is an equivalent in R?

答:
Just install the package numDeriv and use the grad function. Here are a few simple examples that are easy to check.

```<code>library(numDeriv)

grad(sin, 1:3)
[1]  0.5403023 -0.4161468 -0.9899925
cos(1:3)
[1]  0.5403023 -0.4161468 -0.9899925

f = function(x) x^2 + 2*x +3
grad(f, 1:3)
[1] 4 6 8
2*(1:3) + 2
[1] 4 6 8
</code>```

Body:
Just install the package numDeriv and use the grad function. Here are a few simple examples that are easy to check.

library(numDeriv)

grad(sin, 1:3)
[1]  0.5403023 -0.4161468 -0.9899925
cos(1:3)
[1]  0.5403023 -0.4161468 -0.9899925

f = function(x) x^2 + 2*x +3
grad(f, 1:3)
[1] 4 6 8
2*(1:3) + 2
[1] 4 6 8


答:
"Native recursion" means the language itself supports recursive definitions. Unlike the bare-bones lambda calculus, where all terms are anonymous, Haskell does have a way to name expressions; and moreover when giving a definition for a name, you may use that name itself. You observed this yourself: while defining applyTimes you used the name applyTimes, and consequently took advantage of Haskell's native support for recursion.

You could also imagine a different language which supported named expressions but not recursion; indeed many functional languages have distinguished "letrec" and "let" forms for definitions which are recursive and which are not recursive, respectively. In such a language, your definition for applyTimes would be rejected if it used the "let" form, and accepted if it used the "letrec" form.

Title: Support native recursion

Body:
I read an article about recursion in Haskell that says:

But the lambda calculus does not appear on the surface to have any
  means of recursion, because of the anonymity of expressions. How do
  you call something without a name? Being able to write recursive
  functions, though, is essential to Turing completeness. We use a
  combinator – known as the Y combinator or fixed-point combinator – to
  write recursive functions in the lambda calculus. Haskell has native
  recursion ability based on the same principle as the Y combinator.

What does native recursion mean?

Consider following code snippet:

applyTimes :: (Eq a, Num a) => a -> (b -> b) -> b -> b
applyTimes 0 f b = b
applyTimes n f b = f (applyTimes (n-1) f b)

The above code does not conform Y combinator principle, because applyTimes is called in function body itself and it does not defined before.

Please proof my answer, if I wrong.


问:
Show list of angular components v2 or v4
I need to display a list of angular components from a ts file. How I can doing?

```<code>  // file ResolventePage.ts

  listFormulas: IFormula[] = [{
     name: "Formula 1",
     description: "a description",
     element: AComponent1
  }, {
     name: "Formula 2",
     description: "a description 2",
     element: AComponent2
  }, ... ]
</code>```

But I do not know how to place it dynamically within the cycle:

```<code> <ion-item *ngFor="let item of listFormulas">
   <ion-label>{{ item.name }}</ion-label>

   <!-- Here I need to render the component "item.element" -->
 </ion-item>
</code>```

Thank you very much for any help.

答:
If I understood correctly each element in your listFormulas is and angular Component.

Option 1

First import all components in your .ts file, for example:

import { AComponent1} from './AComponent1';
import { AComponent2} from './AComponent2';
// ...
```

<p>Then try this quick hack:</p>

<pre class="lang-html prettyprint-override"><code><ion-item *ngFor="let item of listFormulas">
  <ion-label>{{ item.name }}</ion-label>

  <{{item.element.name}}></{{item.element.name}}>
</ion-item>
</code>```

Option 2

If this doesn't work then here's a plunker of the proper but kind of advanced way to do this. This is a demo from the very detailed official documentation for loading components dynamically.

Body:
I need to display a list of angular components from a ts file. How I can doing?

  // file ResolventePage.ts

  listFormulas: IFormula[] = [{
     name: "Formula 1",
     description: "a description",
     element: AComponent1
  }, {
     name: "Formula 2",
     description: "a description 2",
     element: AComponent2
  }, ... ]

But I do not know how to place it dynamically within the cycle:

 <ion-item *ngFor="let item of listFormulas">
   <ion-label>{{ item.name }}</ion-label>

 </ion-item>

Thank you very much for any help.

Body:
If I understood correctly each element in your listFormulas is and angular Component.

Option 1

First import all components in your .ts file, for example:

import { AComponent1} from './AComponent1';
import { AComponent2} from './AComponent2';
// ...

Then try this quick hack:

<ion-item *ngFor="let item of listFormulas">
  <ion-label>{{ item.name }}</ion-label>

  <{{item.element.name}}></{{item.element.name}}>
</ion-item>

Option 2

If this doesn't work then here's a plunker of the proper but kind of advanced way to do this. This is a demo from the very detailed official documentation for loading components dynamically.


问:
How to know the declaration kind of symbol in TypeScript compiler?
I am trying to build a code analysis tool following the Compiler API.

Right now the app below can print out p, Person, age, walk.

But how to know Person is interface, walk is function, etc.? Thanks

// app.ts

```<code>import * as ts from 'typescript';

const userAppFile = './user-app.ts';
const apiFile = './api.d.ts';

const program = ts.createProgram([userAppFile, apiFile], ts.getDefaultCompilerOptions());
const checker = program.getTypeChecker();
const sourceFile = program.getSourceFile(userAppFile);

function printApi(node) {
  const symbol = checker.getSymbolAtLocation(node);

  if (symbol) console.log(symbol.name);

  ts.forEachChild(node, printApi);
}

printApi(sourceFile);
</code>```

// api.d.ts

```<code>interface Person {
  age: number;
}

declare function walk(speed: number): void;
</code>```

// user-app.ts

```<code>const p: Person = { age: 10 };
walk(3);
</code>```

答:
You check the flags on the symbol.

I.e.:

```<code>if(symbol.flags & ts.SymbolFlags.Class) {
   // this symbol is a class
} else if (symbol.flags & ts.SymbolFlags.Interface) {
   // this is an interface
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build a code analysis tool following the Compiler API.

Right now the app below can print out p, Person, age, walk.

But how to know Person is interface, walk is function, etc.? Thanks

// app.ts

import * as ts from 'typescript';

const userAppFile = './user-app.ts';
const apiFile = './api.d.ts';

const program = ts.createProgram([userAppFile, apiFile], ts.getDefaultCompilerOptions());
const checker = program.getTypeChecker();
const sourceFile = program.getSourceFile(userAppFile);

function printApi(node) {
  const symbol = checker.getSymbolAtLocation(node);

  if (symbol) console.log(symbol.name);

  ts.forEachChild(node, printApi);
}

printApi(sourceFile);

// api.d.ts

interface Person {
  age: number;
}

declare function walk(speed: number): void;

// user-app.ts

const p: Person = { age: 10 };
walk(3);

Body:
You check the flags on the symbol.

I.e.:

if(symbol.flags & ts.SymbolFlags.Class) {
   // this symbol is a class
} else if (symbol.flags & ts.SymbolFlags.Interface) {
   // this is an interface
}


问:
Firebase offline capabilities in ionic / cordova
Has anybody implemented a native app with Firebase with full offline capabilities in Android/iOS?

Could this be done in Cordova/Ionic with a plugin that uses the native Firebase SDKs?

We are building an app that has connection at download and first start but then we have to assume there is no more internet connection for a while and all content from the database has to be available offline. Is Firebase suitable for this requirement or do we have to use CouchDB/PouchDB or any other alternative?

EDIT:

This question referred to the firebase realtime database. I believe that with the new firebase Cloud Firestore offline capabilities for ionic are supported out of the box:

https://firebase.google.com/docs/database/rtdb-vs-firestore

Realtime Database: Offline support for mobile clients on iOS and Android only.

Cloud Firestore: Offline support for iOS, Android, and web clients.

答:
You can use the following project -
AngularFire2-offline

It's purpose is to enable offline data access for supporting browsers (that supports service workers) -
List of browsers (and matching versions) that support service workers

It works this way -

While online, Firebase data is stored locally (as data changes the local store is updated)

While offline, local data is served if available, and writes are stored locally

On reconnect, app updates with new Firebase data, and writes are sent to Firebase

Even while online, local data is used first when available which results in a faster load


问:
Consumer<T> mapped Class<T> in HashMap
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

```<code>private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();
</code>```

but it sucks because then I have to cast the object in the lamba when using it.

Example:

```<code>interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});
</code>```

What I would like to do is

```<code>private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();
</code>```

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

答:
I can just let the IdentityHashMap with the usual Class<?> and Consumer<?>

```<code>private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();
</code>```

And then I wrap the put operation in a method. This method accepts a type and a consumer of the same generic.

```<code>public <T> void intercept(Class<T> type, Consumer<T> consumer)
{
    interceptor.put(type, consumer);
}
</code>```

This lets me write

```<code>intercept(Train.class, train -> {
    System.out.println(train.getSpeed());
});
</code>```

Title: Consumer<T> mapped Class<T> in HashMap

Body:
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();

but it sucks because then I have to cast the object in the lamba when using it.

Example:

interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});

What I would like to do is

private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

Body:
I can just let the IdentityHashMap with the usual Class<?> and Consumer<?>

private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();

And then I wrap the put operation in a method. This method accepts a type and a consumer of the same generic.

public <T> void intercept(Class<T> type, Consumer<T> consumer)
{
    interceptor.put(type, consumer);
}

This lets me write

intercept(Train.class, train -> {
    System.out.println(train.getSpeed());
});


问:
How does npm scripts prioritise local dependency over global ones?
I understand npm scripts adds ./node_modules/.bin to your PATH, therefore you can simply run npm test using the package.json below, and npm will automagically use the local version of mocha found in ./node_modules/.bin

```<code>"scripts": {
    "test": "mocha"
}
</code>```

This is a nice feature, because it saves me writing package.json files like this:

```<code>"scripts": {
    "test": "./node_modules/.bin/mocha"
}
</code>```

BUT what if I bring on a new developer who has mocha installed globally? or I need to push this to an environment with preconfigured global packages? If I am using the short-hand mocha, rather than ./node_modules/.bin/mocha in my package.json, What takes precedence, the global or local package?

答:
Node.js will try to run first your locally installed packages.

If you require a module, Node.js looks for it by going through all node_modules/ directories in ancestor directories (./node_modules/, ../node_modules/, ../../node_modules/, etc.). The first appropriate module that is found is used.

For a more detailed explanation about how Node.js resolves required modules, here is a nice breakdown.

Body:
I understand npm scripts adds ./node_modules/.bin to your PATH, therefore you can simply run npm test using the package.json below, and npm will automagically use the local version of mocha found in ./node_modules/.bin

"scripts": {
    "test": "mocha"
}

This is a nice feature, because it saves me writing package.json files like this:

"scripts": {
    "test": "./node_modules/.bin/mocha"
}

BUT what if I bring on a new developer who has mocha installed globally? or I need to push this to an environment with preconfigured global packages? If I am using the short-hand mocha, rather than ./node_modules/.bin/mocha in my package.json, What takes precedence, the global or local package?


问:
PHP Foreach Tree Alternatives
This is a foreach tree that is common in my workflows when parsing JSON, but I can't help but think there is a better way. I've tried to look this up and I've found some people referring to array_walk but I don't see how that would eliminate the need to do foreach inside foreach inside foreach. Any help? If there's a better way, I'd love to learn because this is not always convenient and feels quite messy.

As requested in comments, the expected result would be to generate a page for each degree, but that page's template would use all of the name variables from the foreach tree (and some others that I didn't include). I stripped my PHP to keep the example simple, although I understand that my use case could effect how the question is answered so that's why I added that information.

Here's some PHP to parse the array:

```<code>foreach ($programs as $program) {
  $program_name = $program['name'];
  $degrees = program['degrees'];
  foreach ($degrees as $degree) {
    $degree_name = $degree['name'];
    $courses = $degree['courses'];
    foreach ($courses as $course) {
      $course_name = $course['name'];
      echo $course_name;
    }
  }
}
</code>```

Here's the JSON:

```<code>{
  "programs":{
    "undergraduate":{
      "name":"undergraduate",
      "degrees":{
        "elementary education":{
          "name":"elementary education",
          "courses":{
            "math":{
              "name":"math"
            }
          }
        }
      }
    }
  }
}
</code>```

答:
Not sure how this fits in overall, but it recursively extracts the name items in order:

```<code>$result = array();
array_walk_recursive($array, function($v, $k) use(&$result) {
                                 if($k == 'name') { $result[] = $v; }
                             });

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

Yields:

```<code>Array
(
    [0] => undergraduate
    [1] => elementary education
    [2] => math
)
</code>```

Title: PHP Foreach Tree Alternatives

Body:
This is a foreach tree that is common in my workflows when parsing JSON, but I can't help but think there is a better way. I've tried to look this up and I've found some people referring to array_walk but I don't see how that would eliminate the need to do foreach inside foreach inside foreach. Any help? If there's a better way, I'd love to learn because this is not always convenient and feels quite messy.

As requested in comments, the expected result would be to generate a page for each degree, but that page's template would use all of the name variables from the foreach tree (and some others that I didn't include). I stripped my PHP to keep the example simple, although I understand that my use case could effect how the question is answered so that's why I added that information.

Here's some PHP to parse the array:

foreach ($programs as $program) {
  $program_name = $program['name'];
  $degrees = program['degrees'];
  foreach ($degrees as $degree) {
    $degree_name = $degree['name'];
    $courses = $degree['courses'];
    foreach ($courses as $course) {
      $course_name = $course['name'];
      echo $course_name;
    }
  }
}

Here's the JSON:

{
  "programs":{
    "undergraduate":{
      "name":"undergraduate",
      "degrees":{
        "elementary education":{
          "name":"elementary education",
          "courses":{
            "math":{
              "name":"math"
            }
          }
        }
      }
    }
  }
}

Body:
Not sure how this fits in overall, but it recursively extracts the name items in order:

$result = array();
array_walk_recursive($array, function($v, $k) use(&$result) {
                                 if($k == 'name') { $result[] = $v; }
                             });

print_r($result);

Yields:

Array
(
    [0] => undergraduate
    [1] => elementary education
    [2] => math
)


问:
An intelligent Javascript back button that doesnt use history()
Im developing on a platform that has some limitations on how i can implement a proper back button.

So i need to create a button that does more then just "javascript:history.back()"

Let me explain:

page1...clicks through to...

page2...fill in the fields and submit to itself...

page2?something=else... here is where the back button is needed

on page2?something=else i want the back button to take the user back to page1

page1 = could be any page (so cant link directly)

is there a function that will know changes in the URL as well as remember the  URL when the page is submitted?

Please lety me know if you would like more info.

Thanks

答:
There are a couple of different ways you could solve this problem.

The first of these depends on the assumption that the number of history pages between Page1 and page2?something=else is always the same.

```<code>javascript: window.history.go(-2)
</code>```

Notice the -2 this tells the browser how many pages to go back.

The second option which would be more laborious, but ultimately a lot more reliable, would be to store the current users breadcrumb (i.e. the pages they have transitted through) in a session and then use the session data to construct your back link.

A third option would be to pass the page/address the back link should point to as post/get parameters through all pages.  When the user hits the page that the back link appears on you can then use that data to construct the back link.

A fourth option would be to combine the first with either the second or third solution.  i.e. pass the history count through on sessions/get/post and then use that to populate the number that goes into the Javascript .go(x) function

Body:
There are a couple of different ways you could solve this problem.

The first of these depends on the assumption that the number of history pages between Page1 and page2?something=else is always the same.

javascript: window.history.go(-2)

Notice the -2 this tells the browser how many pages to go back.

The second option which would be more laborious, but ultimately a lot more reliable, would be to store the current users breadcrumb (i.e. the pages they have transitted through) in a session and then use the session data to construct your back link.

A third option would be to pass the page/address the back link should point to as post/get parameters through all pages.  When the user hits the page that the back link appears on you can then use that data to construct the back link.

A fourth option would be to combine the first with either the second or third solution.  i.e. pass the history count through on sessions/get/post and then use that to populate the number that goes into the Javascript .go(x) function