问:
Return prime numbers
The function should return a list of prime numbers between m and n. If m and/or n are prime numbers, they should also be included in the list.

Here's what I have done:

Code

Here's the output that is supposed to be:

Please ignore the first two output as I have done them.
Output file

答:
```<code>def primes(m, n):
    list_of_primes = []        # Keep track of primes
    for num in range(m, n + 1):    # make inclusive of upper bound
        is_prime = True            # Assume number is prime as starting condition
        for i in range(2, num):    # Check remainder from number 2 up to num
            if num % i ==  0:
                is_prime = False
                break
        if is_prime and num > 1:          #EDIT HERE
            list_of_primes.append(num)   #add to the list of primes if True
    return list_of_primes
</code>```

Note there are multiple ways to improve this algorithm, such as not checking even numbers ect, but this fits the criteria defined in your question.

Title: Return prime numbers

Body:
def primes(m, n):
    list_of_primes = []        # Keep track of primes
    for num in range(m, n + 1):    # make inclusive of upper bound
        is_prime = True            # Assume number is prime as starting condition
        for i in range(2, num):    # Check remainder from number 2 up to num
            if num % i ==  0:
                is_prime = False
                break
        if is_prime and num > 1:          #EDIT HERE
            list_of_primes.append(num)   #add to the list of primes if True
    return list_of_primes

Note there are multiple ways to improve this algorithm, such as not checking even numbers ect, but this fits the criteria defined in your question.


来源: stackexchange

问:
Using TPL how do I set a max threadpool size
I am using the TPL to add new tasks to the system thread pool using the function Task.Factory.StartNew(). The only problem is that I am adding a lot of threads and I think it is creating too many for my processor to handle. Is there a way to set a maximum number of threads in this thread pool?

答:
Usually the TPL scheduler should do a good job of choosing how many tasks to run concurrently, but if you really want to have control over it My blog post shows how to do this both with Tasks and with Actions, and provides a sample project you can download and run to see both in action.

An example of when you might want to explicitly limit how many tasks are ran concurrently is when you are calling your own services and do not want to overload your server.

For what you are describing, it sounds like you may benefit more from making sure you are using async/await with your tasks to prevent needless thread consumption. This will depend though on if you are doing CPU-bound work, or IO-bound work in your tasks. If it's IO-bound, then you may benefit greatly from using async/await.

Regardless, you asked how you can limit the number of tasks that run concurrently, so here's some code to show how to do it with both Actions and Tasks.

With Actions

If using Actions, you can use the built-in .Net Parallel.Invoke function. Here we limit it to running at most 3 threads in parallel.

```<code>var listOfActions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    // Note that we create the Action here, but do not start it.
    listOfActions.Add(() => DoSomething());
}

var options = new ParallelOptions {MaxDegreeOfParallelism = 3};
Parallel.Invoke(options, listOfActions.ToArray());
</code>```

With Tasks

Since you are using Tasks here though, there is no built-in function. However, you can use the one that I provide on my blog.

```<code>    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken())
    {
        StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken);
    }

    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="timeoutInMilliseconds">The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken())
    {
        // Convert to a list of tasks so that we don't enumerate over it multiple times needlessly.
        var tasks = tasksToRun.ToList();

        using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel))
        {
            var postTaskTasks = new List<Task>();

            // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running.
            tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release())));

            // Start running each task.
            foreach (var task in tasks)
            {
                // Increment the number of tasks currently running and wait if too many are running.
                throttler.Wait(timeoutInMilliseconds, cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();
                task.Start();
            }

            // Wait for all of the provided tasks to complete.
            // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler's using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object.
            Task.WaitAll(postTaskTasks.ToArray(), cancellationToken);
        }
    }
</code>```

And then creating your list of Tasks and calling the function to have them run, with say a maximum of 3 simultaneous at a time, you could do this:

```<code>var listOfTasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
    var count = i;
    // Note that we create the Task here, but do not start it.
    listOfTasks.Add(new Task(() => Something()));
}
Tasks.StartAndWaitAllThrottled(listOfTasks, 3);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Usually the TPL scheduler should do a good job of choosing how many tasks to run concurrently, but if you really want to have control over it My blog post shows how to do this both with Tasks and with Actions, and provides a sample project you can download and run to see both in action.

An example of when you might want to explicitly limit how many tasks are ran concurrently is when you are calling your own services and do not want to overload your server.

For what you are describing, it sounds like you may benefit more from making sure you are using async/await with your tasks to prevent needless thread consumption. This will depend though on if you are doing CPU-bound work, or IO-bound work in your tasks. If it's IO-bound, then you may benefit greatly from using async/await.

Regardless, you asked how you can limit the number of tasks that run concurrently, so here's some code to show how to do it with both Actions and Tasks.

With Actions

If using Actions, you can use the built-in .Net Parallel.Invoke function. Here we limit it to running at most 3 threads in parallel.

var listOfActions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    // Note that we create the Action here, but do not start it.
    listOfActions.Add(() => DoSomething());
}

var options = new ParallelOptions {MaxDegreeOfParallelism = 3};
Parallel.Invoke(options, listOfActions.ToArray());

With Tasks

Since you are using Tasks here though, there is no built-in function. However, you can use the one that I provide on my blog.

    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken())
    {
        StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken);
    }

    /// <summary>
    /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel.
    /// <para>NOTE: If one of the given tasks has already been started, an exception will be thrown.</para>
    /// </summary>
    /// <param name="tasksToRun">The tasks to run.</param>
    /// <param name="maxTasksToRunInParallel">The maximum number of tasks to run in parallel.</param>
    /// <param name="timeoutInMilliseconds">The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    public static void StartAndWaitAllThrottled(IEnumerable<Task> tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken())
    {
        // Convert to a list of tasks so that we don&#39;t enumerate over it multiple times needlessly.
        var tasks = tasksToRun.ToList();

        using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel))
        {
            var postTaskTasks = new List<Task>();

            // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running.
            tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release())));

            // Start running each task.
            foreach (var task in tasks)
            {
                // Increment the number of tasks currently running and wait if too many are running.
                throttler.Wait(timeoutInMilliseconds, cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();
                task.Start();
            }

            // Wait for all of the provided tasks to complete.
            // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler&#39;s using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object.
            Task.WaitAll(postTaskTasks.ToArray(), cancellationToken);
        }
    }

And then creating your list of Tasks and calling the function to have them run, with say a maximum of 3 simultaneous at a time, you could do this:

var listOfTasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
    var count = i;
    // Note that we create the Task here, but do not start it.
    listOfTasks.Add(new Task(() => Something()));
}
Tasks.StartAndWaitAllThrottled(listOfTasks, 3);


问:
Xcode: code loses syntax coloring
I find that in various situations Objective-C code in Xcode 3.1 (Leopard) can fail to get appropriate syntax coloring after typing or lose coloring that it had.

This isn't just a "refresh" issue with new custom symbols -- but affects Cocoa framework symbols as well.

Sometimes CMD-a to select all text on the code page will make the coloring (re)appear, sometimes double-clicking on a line to select it will work, sometimes I have to add/delete a space in a symbol to get that symbol to (re)color. Rebuilding, or closing/reopening the project may or may not work.

Is this a known issue with Xcode? For something so annoying to me, I'm not finding the plentiful discussions of it on SO and elsewhere I'd expect.

And is there any command to force global syntax recoloring?

答: For someone still have don't know why. Let open with XCode 8.2, it should work

ContentLicense: CC BY-SA 2.5

Title: Xcode: code loses syntax coloring


问:
Issue with API Manager migration from 1.8.0 to 2.1.0: IS migration client 5.1.0 does nothing
I am doing a migration from APIM 1.8.0 to APIM 2.1.0 and facing an issue with one of migration tools.
Naturally, I am following the steps described in migration guide: https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release

My OS is Windows 7 Enterprise x64, Java - Oracle JDK 7u67, DB - MySQL 5.7, user store - LDAP.

I downloaded WSO2 Identity Server 5.1.0 Migration Client (org.wso2.carbon.is.migrate.client-5.1.0-migration.zip SHA1: ece8ff9a33167751268d205293cc1404fbe4c567) from docs.wso2.com/download/attachments/50518205/org.wso2.carbon.is.migrate.client-5.1.0-migration.zip?version=2&modificationDate=1470811755000&api=v2 as described in guide metioned above (step 7).

Then I unzipped it and put necessary DB scripts into directory APIM_2.1.0_HOME/dbscripts/ (steps 7-a, 7-b) and JAR file into directory APIM_2.1.0_HOME/repository/components/dropins/ (step 7-c).

After that when I try to migrate Identity and User Store DBs (step 9) using IS migration client starting APIM instance with command

```<code>wso2server.bat -Dmigrate -DmigrateIdentityDB -Dcomponent=identity
</code>```

it looks like nothing happens.

I've even configured a logger for this client in APIM_2.1.0_HOME/repository/conf/log4j.properties as

```<code>log4j.logger.org.wso2.carbon.is.migration=DEBUG
</code>```

but only two DEBUG rows appear in logs telling me that migration component activated successfully:

```<code>INFO {org.wso2.carbon.databridge.core.internal.DataBridgeDS} -  Successfully deployed Agent Server  {org.wso2.carbon.databridge.core.internal.DataBridgeDS}
DEBUG {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent} -  Setting RealmService to WSO2 IS Migration component {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent}
DEBUG {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent} -  WSO2 IS migration bundle is activated {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent}
INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Configured Registry in 63ms {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService}
</code>```

Moreover, I looked at the source code of the client at github.com/wso2/product-is/tree/v5.1.0/modules/migration/migration-5.0.0_to_5.1.0/wso2-is-migration-client, especially at class org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent and its method activate(ComponentContext context), which in fact does nothing in contrast to similar class github.com/wso2/product-apim/blob/v2.1.0/modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/client/internal/APIMMigrationServiceComponent.java from another migration client, also provided in migration guide mentioned above (step 4).

And finally, I noticed that relevant code was removed in one of the commits: "removing the migration from pack and adding script changes" https://github.com/wso2/product-is/pull/362/files#diff-789b1c66c0ca3e073080a2b8e6c27834L49

So, my questions are:

Why were those lines of code removed?

And the main question is how to trigger migration client properly? What did I do wrong?

I would appreciate any kind of help.

答:
It was an issue with the migration document. Documentation is now changed. you will have to do a migration to 2.0.0 from 1.8.0 and then to 2.1.0.

https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release#8910

Body:
I am doing a migration from APIM 1.8.0 to APIM 2.1.0 and facing an issue with one of migration tools.
Naturally, I am following the steps described in migration guide: https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release

My OS is Windows 7 Enterprise x64, Java - Oracle JDK 7u67, DB - MySQL 5.7, user store - LDAP.

I downloaded WSO2 Identity Server 5.1.0 Migration Client (org.wso2.carbon.is.migrate.client-5.1.0-migration.zip SHA1: ece8ff9a33167751268d205293cc1404fbe4c567) from docs.wso2.com/download/attachments/50518205/org.wso2.carbon.is.migrate.client-5.1.0-migration.zip?version=2&modificationDate=1470811755000&api=v2 as described in guide metioned above (step 7).

Then I unzipped it and put necessary DB scripts into directory APIM_2.1.0_HOME/dbscripts/ (steps 7-a, 7-b) and JAR file into directory APIM_2.1.0_HOME/repository/components/dropins/ (step 7-c).

After that when I try to migrate Identity and User Store DBs (step 9) using IS migration client starting APIM instance with command

wso2server.bat -Dmigrate -DmigrateIdentityDB -Dcomponent=identity

it looks like nothing happens.

I've even configured a logger for this client in APIM_2.1.0_HOME/repository/conf/log4j.properties as

log4j.logger.org.wso2.carbon.is.migration=DEBUG

but only two DEBUG rows appear in logs telling me that migration component activated successfully:

INFO {org.wso2.carbon.databridge.core.internal.DataBridgeDS} -  Successfully deployed Agent Server  {org.wso2.carbon.databridge.core.internal.DataBridgeDS}
DEBUG {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent} -  Setting RealmService to WSO2 IS Migration component {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent}
DEBUG {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent} -  WSO2 IS migration bundle is activated {org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent}
INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Configured Registry in 63ms {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService}

Moreover, I looked at the source code of the client at github.com/wso2/product-is/tree/v5.1.0/modules/migration/migration-5.0.0_to_5.1.0/wso2-is-migration-client, especially at class org.wso2.carbon.is.migration.client.internal.ISMigrationServiceComponent and its method activate(ComponentContext context), which in fact does nothing in contrast to similar class github.com/wso2/product-apim/blob/v2.1.0/modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/client/internal/APIMMigrationServiceComponent.java from another migration client, also provided in migration guide mentioned above (step 4).

And finally, I noticed that relevant code was removed in one of the commits: "removing the migration from pack and adding script changes" https://github.com/wso2/product-is/pull/362/files#diff-789b1c66c0ca3e073080a2b8e6c27834L49

So, my questions are:

Why were those lines of code removed?

And the main question is how to trigger migration client properly? What did I do wrong?

I would appreciate any kind of help.


问:
How to release Outlook objects correctly?
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

```<code>
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}</code>```

Any idea what's wrong?

答:
You can try this: Instead of defining a new MailItem everytime within the For loop, can you define mi outside the For loop or even in your class level, and reuse it for each mailitems? e.g:

```<code>MailItem mi;
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
   mi= (MailItem)selection;
   // your other code...
 }
 }
mi=null;
GC.Collect();
GC.WaitForPendingFinalizers();
</code>```

EDIT:

Try to create local variable for each references e.g:

```<code>Outlook.Explorer myExplorer=Application.ActiveExplorer();
Outlook.Selection mySelection=myexplorer.Selection;
foreach (var selection in mySelection)
{
}
myExplorer=null;
mySelection=null;
//....
</code>```

EDIT-2:

IF you are using Outlook 2010 check this:
Outlook 2010 addin selection not clearing

ContentLicense: CC BY-SA 4.0

Body:
I just can't release my Outlook MailItems. After opening 200 Mails the Exchange Sever  returns the maximum open Emails is reached.

I'm remove my UserProperty from all selected Mail.

My Code:

foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
  MailItem mi = (MailItem)selection;
  UserProperty up = mi.UserProperties.Find("MyProp");
  if (up != null)
  {
   up.Delete();
   //##################################
   // I also tried :
   //----------------------------------
   //    Marshal.ReleaseComObject(up);
   //    up = null;
   //----------------------------------
  }

  mi.Save();

  //##################################
  // I also tried :
  //----------------------------------
  //     mi.Close(OlInspectorClose.olDiscard);
  //----------------------------------

  // I don't know if this loop is necessary, but I have found it somewhere on the web
  while (Marshal.ReleaseComObject(mi) > 0);
  mi = null;

  //##################################
  // I also tried :
  //----------------------------------
  //    GC.Collect();
  //    GC.WaitForPendingFinalizers();
  //----------------------------------
 }
}

Any idea what's wrong?

Body:
You can try this: Instead of defining a new MailItem everytime within the For loop, can you define mi outside the For loop or even in your class level, and reuse it for each mailitems? e.g:

MailItem mi;
foreach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
{
 if (selection is MailItem)
 {
   mi= (MailItem)selection;
   // your other code...
 }
 }
mi=null;
GC.Collect();
GC.WaitForPendingFinalizers();

EDIT:

Try to create local variable for each references e.g:

Outlook.Explorer myExplorer=Application.ActiveExplorer();
Outlook.Selection mySelection=myexplorer.Selection;
foreach (var selection in mySelection)
{
}
myExplorer=null;
mySelection=null;
//....

EDIT-2:

IF you are using Outlook 2010 check this:
Outlook 2010 addin selection not clearing


问:
Config.groovy in grails
In Config.groovy file we are assigning the value of appName to grails.project.groupId

grails.project.groupId = appName

My question is from where we are getting the value for appName.

Thanks in advance.

答:
To get the appName in a config file that you're including with grails.config.locations you can use-</p>

```<code>appName = grails.util.Metadata.current.'app.name'
</code>```

Title: Config.groovy in grails

Body:
To get the appName in a config file that you're including with grails.config.locations you can use-

appName = grails.util.Metadata.current.'app.name'


问:
Compiling simple openCV project
Attempting to compile a very simple program to test out my recent installation of OpenCV 3.2.0. My program opencvtest.cpp is in a folder called cpp, which also holds the opencv-3.2.0 installation directory.

Here's my program.

```<code>//Include file for every supported OpenCV function
#include <opencv2/opencv.hpp>

int main( int argc, char** argv ) {

  cv::Mat img = cv::imread( argv[1], -1 );

  if( img.empty() ) return -1;

  cv::namedWindow( "Example 2-1", cv::WINDOW_AUTOSIZE );
  cv::imshow( "Example 2-1", img );
  cv::waitKey( 0 );
  cv::destroyWindow( "Example 2-1" );

  return 0;
}
</code>```

Below I've included the call to pkg-config to show what parameters I'm using, and my actual g++ command to try and compile my file.

```<code>asif.ahmed:~/cpp $ pkg-config opencv --cflags --libs
-I/usr/include/opencv -I/usr/include/opencv2 -lopencv_calib3d -lopencv_imgproc -lopencv_contrib -lopencv_legacy -lopencv_core -lopencv_ml -lopencv_features2d -lopencv_objdetect -lopencv_flann -lopencv_video -lopencv_highgui

asif.ahmed:~/cpp $ g++  opencvtest.cpp `pkg-config opencv --cflags --libs` -o main
opencvtest.cpp:2:10: fatal error: 'opencv2/opencv.hpp' file not found
#include <opencv2/opencv.hpp>
         ^
1 error generated.
</code>```

Can anyone else suggest anything to get this to compile? I don't have a great grasp of command line compiling C++.

答: Check path to opencv.hpp (is it really /usr/include/opencv2/opencv2/opencv.hpp?) - If you use -I/usr/include/opencv2 perhaps you need #include "opencv.hpp" instead of #include <opencv2/opencv.hpp>, or better use -I/usr/include/ and #include "opencv2/opencv.hpp"

Title: Compiling simple openCV project

Body:
Attempting to compile a very simple program to test out my recent installation of OpenCV 3.2.0. My program opencvtest.cpp is in a folder called cpp, which also holds the opencv-3.2.0 installation directory.

Here's my program.

//Include file for every supported OpenCV function
#include <opencv2/opencv.hpp>

int main( int argc, char** argv ) {

  cv::Mat img = cv::imread( argv[1], -1 );

  if( img.empty() ) return -1;

  cv::namedWindow( "Example 2-1", cv::WINDOW_AUTOSIZE );
  cv::imshow( "Example 2-1", img );
  cv::waitKey( 0 );
  cv::destroyWindow( "Example 2-1" );

  return 0;
}

Below I've included the call to pkg-config to show what parameters I'm using, and my actual g++ command to try and compile my file.

asif.ahmed:~/cpp $ pkg-config opencv --cflags --libs
-I/usr/include/opencv -I/usr/include/opencv2 -lopencv_calib3d -lopencv_imgproc -lopencv_contrib -lopencv_legacy -lopencv_core -lopencv_ml -lopencv_features2d -lopencv_objdetect -lopencv_flann -lopencv_video -lopencv_highgui

asif.ahmed:~/cpp $ g++  opencvtest.cpp `pkg-config opencv --cflags --libs` -o main
opencvtest.cpp:2:10: fatal error: 'opencv2/opencv.hpp' file not found
#include <opencv2/opencv.hpp>
         ^
1 error generated.

Can anyone else suggest anything to get this to compile? I don't have a great grasp of command line compiling C++.


问:
Unexpected new head created
I am working with Hg and TortoiseHg on a project and pushing every couple of days to a remote repo on Bitbucket. When I tried to push changes today, I got an error saying that I was trying to create a new head. I thought this was odd since I am definitely the only person working on the project and I work from one PC.

I pulled to see what was going on on the remote repo and after pulling the local repo tree looks like so:

At the bitbucket end the repo looks like this:

Can someone help me understand why I got two heads if I'm the only one working on the project and why Hg is not recognising that Rev.40 and Rev.36 are the same revision?

How do I fix this now? If I strip 40 locally, what will happen when I try to push changes to the remote repo? Will it strip the revision at the remote repo too?

答:
you can try this (on a clone repo if you prefer to be sure)

having a clean workgin directory

```<code>hg co 40
hg backout -r 40
hg merge 39
hg push
</code>```

revision 40 would be the one that exists in the remote repo, before the amendment
so, you check it out, you back it out (put the inverse on top of it) then you merge your ongoing work (left at 39) and there should be no merge conflicts at all, since all changes are incoming
then, when satisfied, you push

===

why I got two heads

this part was already addressed in the comments, you realized you amended the commit after pushing it, thus the apparent duplicate of it

How do I fix this now?

you do a merge on your local repo, to get rid of the two heads, so having only one the remote repo won't complain about it
if you like, you can backout the before-amendment commit to be safe (or not, if you really know how to merge the conflicts making your local prevail)
but in both these cases, the non-amended commit survives, therefore it'll show up in your history, beware

If I strip 40 locally, what will happen when I try to push changes to the remote repo?

is gonna be there unless you strip it there (directly on the remote repo)

Will it strip the revision at the remote repo too?

no, it won't

Title: Unexpected new head created

Body:
you can try this (on a clone repo if you prefer to be sure)

having a clean workgin directory

hg co 40
hg backout -r 40
hg merge 39
hg push

revision 40 would be the one that exists in the remote repo, before the amendment
so, you check it out, you back it out (put the inverse on top of it) then you merge your ongoing work (left at 39) and there should be no merge conflicts at all, since all changes are incoming
then, when satisfied, you push

===

why I got two heads

this part was already addressed in the comments, you realized you amended the commit after pushing it, thus the apparent duplicate of it

How do I fix this now?

you do a merge on your local repo, to get rid of the two heads, so having only one the remote repo won't complain about it
if you like, you can backout the before-amendment commit to be safe (or not, if you really know how to merge the conflicts making your local prevail)
but in both these cases, the non-amended commit survives, therefore it'll show up in your history, beware

If I strip 40 locally, what will happen when I try to push changes to the remote repo?

is gonna be there unless you strip it there (directly on the remote repo)

Will it strip the revision at the remote repo too?

no, it won't


问:
How to inject component into a div selector in angular2
I would like to know if there is anyway for me to inject a component into a div selector () using either a class or id.
I know how to inject a component into another component but don't know how to go about it with injecting it into a div selector.</p>

答:
You can use ViewContainerRef to inject components or templates into containers, which can be selected using @ViewChild by either the tag or an ID.

This blog post goes over a couple different ways to inject a template into a view container.

Understanding ViewContainerRef in Angular 2: https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682

There's another post that details creating dynamic components that are injected into a parent component, which can also be done using an element's ID.

Dynamically Creating Components With Angular:
https://netbasal.com/dynamically-creating-components-with-angular-a7346f4a982d


问:
Azure DC/OS cluster. How to change SSH RSA public key
I'm new in Azure and DC/OS. I deployed a DC/OS cluster using the next document: https://learn.microsoft.com/en-us/azure/container-service/container-service-deployment. What should I do in case I want change SSH RSA public key   which I used in deploying? I couldn't find a document with description such situation.

After deploying a DC/OS cluster I have a resource group which contains virtual machine with name like dcos-master-* . I can change public key for this virtual machine using azure web portal: resourcegroup->'dcos-master-* '->Reset password. But as I understand it's not enough. I see also  that my resource group contains virtual machine scale sets like dcos-agent-private-* and dcos-agent-public-*. But I can't find how to reset passwords there.

Explain me please what should I do in such case?

答:
What should I do in case I want change SSH RSA public key which I used
  in deploying?

Sorry, I have not find how to change the public key of VMSS, I will do some search, if I get anything new, I'll keep you updated.

As a workaround, we can add a new public key to VMSS, here is the script:

```<code>$vmssName = "dcos-agent-private-EAF6BCA8-vmss0"
$vmssResourceGroup = "dcos"
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
Add-AzureRmVmssSshPublicKey -VirtualMachineScaleSet $VMSS -KeyData "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr1ftAx4QhtzAeqei9ukw32nrM8kmB6t2UVdBpuUjAeBAI3/cln/0vmekCt2OPJof5/mdaMTYoMleMsPxQWcm19fZviiMS0rkmLU9qwTeJf8+T8RWEUB75wRH5aDdrit1eYZ9bwJGL1LbkECKWoB02HZGLRH24Z5BLLXCkXjGI8LTLTTZobAnM4EC1QGMCsuMUl0mlhchaK0yQifx+GHOsbFuqe+E40akAzzh7tt+O4I/TjigrE4YHUJlmGNlY3grXFPE5oaszzb97/yyglt1cW2KucjAI4qm7ZTQ6wz5asW8IoN+jya4h2O4Au0ymNVgw1EQG1p8UJ2qByyxxJNMSw==" -Path "/home/admin/.ssh/authorized_keys"
</code>```

Here is the result:

By the way, if you don't want user can use your original public key to login VMSS instance, we can login this instance and delete the original public key in authorized_key.

```<code>jason@dcos-agent-public-EAF6BCA8000001:~$ cd .ssh/
jason@dcos-agent-public-EAF6BCA8000001:~/.ssh$ ls
authorized_keys
jason@dcos-agent-public-EAF6BCA8000001:~/.ssh$ cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr1ftAx4QhtzAeqei9ukw32nrM8kmB6t2UVdBpuUjAeBAI3/cln/0vmekCt2OPJof5/mdaMTYoMleMsPxQWcm19fZviiMS0rkmLU9qwTeJf8+T8RWEUB75wRH5aDdrit1eYZ9bwJGL1LbkECKWoB02HZGLRH24Z5BLLXCkXjGI8LTLTTZobAnM4EC1QGMCsuMUl0mlhchaK0yQifx+GHOsbFuqe+E40akAzzh7tt+O4I/TjigrE4YHUJlmGNlY3grXFPE5oaszzb97/yyglt1cW2KucjAI4qm7ZTQ6wz5asW8IoN+jya4h2O4Au0ymNVgw1EQG1p8UJ2qByyxxJNMSw==
</code>```

Update:

we can use this command to list public key.

Body:
What should I do in case I want change SSH RSA public key which I used
  in deploying?

Sorry, I have not find how to change the public key of VMSS, I will do some search, if I get anything new, I'll keep you updated.

As a workaround, we can add a new public key to VMSS, here is the script:

$vmssName = "dcos-agent-private-EAF6BCA8-vmss0"
$vmssResourceGroup = "dcos"
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
Add-AzureRmVmssSshPublicKey -VirtualMachineScaleSet $VMSS -KeyData "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr1ftAx4QhtzAeqei9ukw32nrM8kmB6t2UVdBpuUjAeBAI3/cln/0vmekCt2OPJof5/mdaMTYoMleMsPxQWcm19fZviiMS0rkmLU9qwTeJf8+T8RWEUB75wRH5aDdrit1eYZ9bwJGL1LbkECKWoB02HZGLRH24Z5BLLXCkXjGI8LTLTTZobAnM4EC1QGMCsuMUl0mlhchaK0yQifx+GHOsbFuqe+E40akAzzh7tt+O4I/TjigrE4YHUJlmGNlY3grXFPE5oaszzb97/yyglt1cW2KucjAI4qm7ZTQ6wz5asW8IoN+jya4h2O4Au0ymNVgw1EQG1p8UJ2qByyxxJNMSw==" -Path "/home/admin/.ssh/authorized_keys"

Here is the result:

By the way, if you don't want user can use your original public key to login VMSS instance, we can login this instance and delete the original public key in authorized_key.

jason@dcos-agent-public-EAF6BCA8000001:~$ cd .ssh/
jason@dcos-agent-public-EAF6BCA8000001:~/.ssh$ ls
authorized_keys
jason@dcos-agent-public-EAF6BCA8000001:~/.ssh$ cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr1ftAx4QhtzAeqei9ukw32nrM8kmB6t2UVdBpuUjAeBAI3/cln/0vmekCt2OPJof5/mdaMTYoMleMsPxQWcm19fZviiMS0rkmLU9qwTeJf8+T8RWEUB75wRH5aDdrit1eYZ9bwJGL1LbkECKWoB02HZGLRH24Z5BLLXCkXjGI8LTLTTZobAnM4EC1QGMCsuMUl0mlhchaK0yQifx+GHOsbFuqe+E40akAzzh7tt+O4I/TjigrE4YHUJlmGNlY3grXFPE5oaszzb97/yyglt1cW2KucjAI4qm7ZTQ6wz5asW8IoN+jya4h2O4Au0ymNVgw1EQG1p8UJ2qByyxxJNMSw==

Update:

we can use this command to list public key.


问:
How to display a toast message by clicking on a homescreen widget in android studio?
please tell me what i'm doing wrong

```<code>NewAppWidget.java class

package com.example.kinjolnath.alert;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Implementation of App Widget functionality.
 */

public class NewAppWidget extends AppWidgetProvider {
    private static final String TAG = NewAppWidget.class.getSimpleName();

void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    Log.d(TAG, "Inside updateAppWidget");
    Log.i(TAG, "Inside updateAppWidget");
    Log.e(TAG, "Inside updateAppWidget");

//        Toast.makeText(context,
//                "Should appear at widget click", Toast.LENGTH_SHORT).show();

    // Construct the RemoteViews object
    Intent intent = new Intent(context, MapsActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            intent,PendingIntent.FLAG_UPDATE_CURRENT);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    views.setOnClickPendingIntent(R.id.imageButton, pendingIntent);
    Intent sendingIntent = new Intent(context, SendingService.class);
    sendingIntent.setAction(SendingService.ACTION_SEND_MESSAGE);
    PendingIntent sendingPendingIntent = PendingIntent.getService(context, 0, sendingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    views.setOnClickPendingIntent(R.id.imageButton, sendingPendingIntent);
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    Log.d(TAG, "Inside onUpdate");
    Log.i(TAG, "Inside onUpdate");
    Log.e(TAG, "Inside onUpdate");
    SendingService.startActionSendMessage(context);
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created
    Log.d(TAG, "Inside onEnabled");
    Log.i(TAG, "Inside onEnabled");
    Log.e(TAG, "Inside onEnabled");
}

@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
    Log.d(TAG, "Inside onDisabled");
    Log.i(TAG, "Inside onDisabled");
    Log.e(TAG, "Inside onDisabled");
    }
}
</code>```

SendingService.java class

```<code>package com.example.kinjolnath.alert;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by kinjolnath on 01-06-2017.
 */

public class SendingService extends IntentService{
    private static final String TAG = NewAppWidget.class.getSimpleName();
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
 * @param name Used to name the worker thread, important only for debugging.
 */
public static final String ACTION_SEND_MESSAGE = "com.example.MapsActivity.action.send_message";

public SendingService(String name) {
    super(name);
}

public static void startActionSendMessage(Context context){
    Intent intent = new Intent(context, SendingService.class);
    intent.setAction(ACTION_SEND_MESSAGE);
    context.startService(intent);
    Log.d(TAG, "Inside startActionSendMessage");
    Log.i(TAG, "Inside startActionSendMessage");
    Log.e(TAG, "Inside startActionSendMessage");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent != null){
        final String action = intent.getAction();
        Log.d(TAG, action + "inside onHandleIntent");
        if(ACTION_SEND_MESSAGE.equals(action)){
            handleActionSend();
        }
    }
}
//handleActionSend method:
private void handleActionSend() {
    Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "Inside handleActionSend");
    Log.i(TAG, "Inside handleActionSend");
    Log.e(TAG, "Inside handleActionSend");
    }
}
</code>```

I followed a tutorial from Udacity and ended up at this stage but it still doesn't work
I am new to android development so any help would be appreciated.

答:
Please see this: Android: Toast in a thread

If toast is not showing then its probably not using the UI thread. You can try using applicationContext instead of this, though I'm not sure that will work. I don't like to run Toasts when the UI isn't visible but have run across this to use for specific testing without having to look at logs.

Body:
please tell me what i'm doing wrong

NewAppWidget.java class

package com.example.kinjolnath.alert;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Implementation of App Widget functionality.
 */

public class NewAppWidget extends AppWidgetProvider {
    private static final String TAG = NewAppWidget.class.getSimpleName();

void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    Log.d(TAG, "Inside updateAppWidget");
    Log.i(TAG, "Inside updateAppWidget");
    Log.e(TAG, "Inside updateAppWidget");

//        Toast.makeText(context,
//                "Should appear at widget click", Toast.LENGTH_SHORT).show();

    // Construct the RemoteViews object
    Intent intent = new Intent(context, MapsActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            intent,PendingIntent.FLAG_UPDATE_CURRENT);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    views.setOnClickPendingIntent(R.id.imageButton, pendingIntent);
    Intent sendingIntent = new Intent(context, SendingService.class);
    sendingIntent.setAction(SendingService.ACTION_SEND_MESSAGE);
    PendingIntent sendingPendingIntent = PendingIntent.getService(context, 0, sendingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    views.setOnClickPendingIntent(R.id.imageButton, sendingPendingIntent);
    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    Log.d(TAG, "Inside onUpdate");
    Log.i(TAG, "Inside onUpdate");
    Log.e(TAG, "Inside onUpdate");
    SendingService.startActionSendMessage(context);
    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
    }
}

@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created
    Log.d(TAG, "Inside onEnabled");
    Log.i(TAG, "Inside onEnabled");
    Log.e(TAG, "Inside onEnabled");
}

@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
    Log.d(TAG, "Inside onDisabled");
    Log.i(TAG, "Inside onDisabled");
    Log.e(TAG, "Inside onDisabled");
    }
}

SendingService.java class

package com.example.kinjolnath.alert;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by kinjolnath on 01-06-2017.
 */

public class SendingService extends IntentService{
    private static final String TAG = NewAppWidget.class.getSimpleName();
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
 * @param name Used to name the worker thread, important only for debugging.
 */
public static final String ACTION_SEND_MESSAGE = "com.example.MapsActivity.action.send_message";

public SendingService(String name) {
    super(name);
}

public static void startActionSendMessage(Context context){
    Intent intent = new Intent(context, SendingService.class);
    intent.setAction(ACTION_SEND_MESSAGE);
    context.startService(intent);
    Log.d(TAG, "Inside startActionSendMessage");
    Log.i(TAG, "Inside startActionSendMessage");
    Log.e(TAG, "Inside startActionSendMessage");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent != null){
        final String action = intent.getAction();
        Log.d(TAG, action + "inside onHandleIntent");
        if(ACTION_SEND_MESSAGE.equals(action)){
            handleActionSend();
        }
    }
}
//handleActionSend method:
private void handleActionSend() {
    Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "Inside handleActionSend");
    Log.i(TAG, "Inside handleActionSend");
    Log.e(TAG, "Inside handleActionSend");
    }
}

I followed a tutorial from Udacity and ended up at this stage but it still doesn't work
I am new to android development so any help would be appreciated.


问:
how to get the header files for graphicsmagick
i am developing an image processing tool using QT. Am new to both QT & graphicsmagick(magick++) c++ library. i have planned to use c++ as my development language. can anyone suggest me how to get the  graphicsmagick header files?</p>

答: You download the graphicsmagick package for your platform from sourceforge.</p>


问:
Can anybody explain this statement - "The point of all lambdas is deferred execution"
I was going through an example in "Java SE 8 for the Really Impatient: Programming with Lambdas".

Let us look at a simple example. Suppose you log an event:

```<code>logger.info("x: " + x + ", y: " + y);
</code>```

What happens if the log level is set to suppress INFO messages? The message string is computed and passed to the info method, which then decides to throw it away. Wouldn’t it be nicer if the string concatenation only happened when necessary?

Running code only when necessary is a use case for lambdas. The standard idiom is to wrap the code in a no-arg lambda:

```<code>() -> "x: " + x + ", y: " + y
</code>```

The following method provides lazy logging:

```<code>public static void info(Logger logger, Supplier<String> message) {
if (logger.isLoggable(Level.INFO))
  logger.info(message.get());
}
</code>```

We use the isLoggable method of the Logger class to decide whether INFO messages should be logged. If so, we invoke the lambda by calling its abstract method, which happens to be called get.

So what I don't understand is - we could have used the logger.isLoggable(Level.INFO) in the Example 1 (the code which does not use lambdas) and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

```<code>logger.info("x: " + x + ", y: " + y);
</code>```

What was the use of using lambdas in this case?

答:
As far as I can tell this is entirely about Supplier and the way you can postponed the execution. The much better example IMO would be the Optional two methods: orElse and orElseGet.

orElse returns T or in your example case a String; on the other hand orElseGet returns a Supplier<T>, computed only when needed (when the Optional is actually missing):

```<code>public T orElseGet(Supplier<? extends T> supplier) {
    return value != null ? value : supplier.get();
}
</code>```

The difference here is that orElse computes the value always, sort of like eagerly; even if it's not needed.

Body:
I was going through an example in "Java SE 8 for the Really Impatient: Programming with Lambdas".

Let us look at a simple example. Suppose you log an event:

logger.info("x: " + x + ", y: " + y);

What happens if the log level is set to suppress INFO messages? The message string is computed and passed to the info method, which then decides to throw it away. Wouldn’t it be nicer if the string concatenation only happened when necessary?

Running code only when necessary is a use case for lambdas. The standard idiom is to wrap the code in a no-arg lambda:

() -> "x: " + x + ", y: " + y

The following method provides lazy logging:

public static void info(Logger logger, Supplier<String> message) {
if (logger.isLoggable(Level.INFO))
  logger.info(message.get());
}

We use the isLoggable method of the Logger class to decide whether INFO messages should be logged. If so, we invoke the lambda by calling its abstract method, which happens to be called get.

So what I don't understand is - we could have used the logger.isLoggable(Level.INFO) in the Example 1 (the code which does not use lambdas) and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

logger.info("x: " + x + ", y: " + y);

What was the use of using lambdas in this case?

Body:
As far as I can tell this is entirely about Supplier and the way you can postponed the execution. The much better example IMO would be the Optional two methods: orElse and orElseGet.

orElse returns T or in your example case a String; on the other hand orElseGet returns a Supplier<T>, computed only when needed (when the Optional is actually missing):

public T orElseGet(Supplier<? extends T> supplier) {
    return value != null ? value : supplier.get();
}

The difference here is that orElse computes the value always, sort of like eagerly; even if it's not needed.


问:
How do I "preserve" an entity when changing its parent in the DOM?
I have a "variable assignment" component that looks like the following (the blue diamond with the yellow sphere attached):

http://i.imgur.com/nJotPgW.gif (unfortunately I don't have enough reputation to inline the image)

Here the yellow sphere that things can snap into is created in the initialization of the variable assignment component like so

```<code>AFRAME.registerComponent('variable-assignment', {
  schema: {
    grabbable: {default: true}
  },
  init: function () {
    this.el.innerHTML = `
    <a-sphere
    snap-site="controller:#right-hand"
    radius=".1"
    color="yellow"
    material="transparent:true; opacity:.5;"
    position=".22 0 0">
    </a-sphere>
    `;
    this.label = 'x';
    this.el.setAttribute('geometry', {
      primitive: 'octahedron',
      radius: .1,
      color: 'blue'
    });
    ...
</code>```

The snap-site component has code that detects a collision with the red sphere and then makes it a child element. So the DOM looks something like this before the collision.

```<code><a-sphere color=red></a-sphere>
<a-entity variable-assignment>
    <a-sphere snap-site>
    <a-sphere>
</a-entity>
</code>```

and after

```<code><a-entity variable-assignment>
    <a-sphere snap-site>
        <a-sphere color=red></a-sphere>
    <a-sphere>
</a-entity>
</code>```

The problem is when I want to move the entity with variable-assignment inside another DOM element using appendChild the initialization function for the variable-assignment called again the innerHTML is reset. So for example if we have

```<code><a-entity container></a-entity>
<a-entity variable-assignment>
    <a-sphere snap-site>
        <a-sphere color=red></a-sphere>
    <a-sphere>
</a-entity>
</code>```

And we want to move variable-assignment into container using something like containerElement.appendChild(variableAssignmentEntity) the inner red sphere gets removed

```<code><a-entity container>
    <a-entity variable-assignment>
        <a-sphere snap-site>
        <a-sphere>
    </a-entity>
</a-entity>
</code>```

As a work around/hack I was thinking about using a flag of some sort to see if initialize had already been called before for the element/entity the component was a property of and then not run the initialization code, something like

```<code>  init: function () {
    if (this.el.getAttribute('initialized')) {
        return;
    }
    this.el.setAttribute('initialized', true);
    ...
</code>```

but this seems like a bad way to do it and also looking into the A-Frame source it seems appendChild causes all components to be removed then added again so it doesn't actually work either or at least causes other things to break.

Is there a good way to do this or is there a different way to define the variable-assignment component so the yellow sphere snap-site component isn't a child set in the initialization?

答:
You're correct that appendChild causes components to be re-initialized, and might not work as expected. Here are a couple alternatives:

After removing the element, call el = el.cloneNode() to make a clean copy and append that, instead.

Don't actually make the sphere a child of your variable-assignment component, but instead just have the 'parent' component update the position/rotation of the child in the tick() function.

Use the underlying three.js API to pass around the THREE.Object3D, without actually changing the parent of any elements.

An example of (3):

```<code>var mesh = el.getObject3D('mesh)';
el.removeObject3D('mesh');
otherEl.setObject3D('mesh', mesh);
</code>```

Body:
I have a "variable assignment" component that looks like the following (the blue diamond with the yellow sphere attached):

http://i.imgur.com/nJotPgW.gif (unfortunately I don't have enough reputation to inline the image)

Here the yellow sphere that things can snap into is created in the initialization of the variable assignment component like so

AFRAME.registerComponent('variable-assignment', {
  schema: {
    grabbable: {default: true}
  },
  init: function () {
    this.el.innerHTML = `

    `;
    this.label = 'x';
    this.el.setAttribute('geometry', {
      primitive: 'octahedron',
      radius: .1,
      color: 'blue'
    });
    ...

The snap-site component has code that detects a collision with the red sphere and then makes it a child element. So the DOM looks something like this before the collision.

and after

The problem is when I want to move the entity with variable-assignment inside another DOM element using appendChild the initialization function for the variable-assignment called again the innerHTML is reset. So for example if we have

And we want to move variable-assignment into container using something like containerElement.appendChild(variableAssignmentEntity) the inner red sphere gets removed

As a work around/hack I was thinking about using a flag of some sort to see if initialize had already been called before for the element/entity the component was a property of and then not run the initialization code, something like

  init: function () {
    if (this.el.getAttribute('initialized')) {
        return;
    }
    this.el.setAttribute('initialized', true);
    ...

but this seems like a bad way to do it and also looking into the A-Frame source it seems appendChild causes all components to be removed then added again so it doesn't actually work either or at least causes other things to break.

Is there a good way to do this or is there a different way to define the variable-assignment component so the yellow sphere snap-site component isn't a child set in the initialization?

Body:
You're correct that appendChild causes components to be re-initialized, and might not work as expected. Here are a couple alternatives:

After removing the element, call el = el.cloneNode() to make a clean copy and append that, instead.

Don't actually make the sphere a child of your variable-assignment component, but instead just have the 'parent' component update the position/rotation of the child in the tick() function.

Use the underlying three.js API to pass around the THREE.Object3D, without actually changing the parent of any elements.

An example of (3):

var mesh = el.getObject3D('mesh)';
el.removeObject3D('mesh');
otherEl.setObject3D('mesh', mesh);


问:
React.JS simple component not rendering nested html tag
This is a simple piece of code. I am trying to get my first component to run and I followed the tutorial and this is their code for creating the component.

It works in that it does inject the first  into the html document but the  is missing.

For some reason it worked perfectly for the instructor in the video, as you can see here: https://youtu.be/G40iHC-h0c0?t=392

```<code>import React from "react";
import { render } from "react-dom";

class basicDiv extends React.Component {
    render(){
        return(
            <div>
                <h1>Hi my friend</h1>
            </div>
        );
    }
}

render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));
</code>```

here is the index.html file:

```<code><!doctype html>

<html>

<head>

</head>
<body>
    <div class="componentPlaceHolder" style="border:1px solid black;min-height:100px;">

    </div>

    <script src="/app/bundle.js"></script>
</body>

</html>
</code>```

答:
D-reaper is correct. You should also return the render function to an ID in your html rather than to a .class

In your html change:

```<code><div class=componentPlacholder>
to <div id="componentPlaceholder">`
</code>```

Then at the bottom of your React component change:

```<code>render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));
to render(<BasicDiv />, getElementById(componentPlacholder));
</code>```

Don't forget to rename your component from basicDiv to BasicDiv as D-reaper mentioned

You can technically return to a .class but since it looks like you are learning it seemed helpful to alert you that you will cause yourself a lot of issues if you are not returning to an ID.

Body:
This is a simple piece of code. I am trying to get my first component to run and I followed the tutorial and this is their code for creating the component.

It works in that it does inject the first  into the html document but the  is missing.

For some reason it worked perfectly for the instructor in the video, as you can see here: https://youtu.be/G40iHC-h0c0?t=392

import React from "react";
import { render } from "react-dom";

class basicDiv extends React.Component {
    render(){
        return(

Hi my friend

        );
    }
}

render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));

here is the index.html file:

<!doctype html>

Body:
D-reaper is correct. You should also return the render function to an ID in your html rather than to a .class

In your html change:

<div class=componentPlacholder>
to <div id="componentPlaceholder">`

Then at the bottom of your React component change:

render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));
to render(<BasicDiv />, getElementById(componentPlacholder));

Don't forget to rename your component from basicDiv to BasicDiv as D-reaper mentioned

You can technically return to a .class but since it looks like you are learning it seemed helpful to alert you that you will cause yourself a lot of issues if you are not returning to an ID.


问:
Share extension app store upload issue
Hello fellow developers,

I'm uploading an app with share extension, extension should only accept images.

For some reason when I'm uploading app for beta testing i get an warning as  below.

No values under NSExtensionActivationRule in bundle APPNAME.app/PlugIns/ShareOnAPPNAME.appex appear to trigger activation.

Also I got email saying below

Dear developer,

We have discovered one or more issues with your recent delivery for "APPNAME". Your delivery was successful, but you may wish to correct the following issues in your next delivery:

Unreachable Activation - No values under NSExtensionActivationRule in bundle APPNAME.app/PlugIns/ShareOnAPPNAME.appex appear to trigger activation.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

My plist file in extension target looks like this...I tried adding all support key with value 0 except image and only image key with value 1...but warning persists...

```<code><key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key> NSExtensionActivationSupportsImageWithMaxCount </key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsText</key>
            <false/>
        </dict>
    </dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
    <key>NSExtensionPrincipalClass</key>
    <string>ShareOnAPPNAMEVC</string>
</dict>
</code>```

Also App shows sharing option to each and every type i.e. movies, text, webpage etc. along with images.

答:
I would suggest you to use this:</p>

```<code><key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key>NSExtensionActivationRule</key>
            <string>TRUEPREDICATE</string>
            <key>NSExtensionActivationSupportsFileWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsImageWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsMovieWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsText</key>
            <false/>
            <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
            <integer>1</integer>
        </dict>
    </dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
</dict>
</code>```

Title: Share extension app store upload issue

Body:
Hello fellow developers,

I'm uploading an app with share extension, extension should only accept images.

For some reason when I'm uploading app for beta testing i get an warning as  below.

No values under NSExtensionActivationRule in bundle APPNAME.app/PlugIns/ShareOnAPPNAME.appex appear to trigger activation.

Also I got email saying below

Dear developer,

We have discovered one or more issues with your recent delivery for "APPNAME". Your delivery was successful, but you may wish to correct the following issues in your next delivery:

Unreachable Activation - No values under NSExtensionActivationRule in bundle APPNAME.app/PlugIns/ShareOnAPPNAME.appex appear to trigger activation.

After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

My plist file in extension target looks like this...I tried adding all support key with value 0 except image and only image key with value 1...but warning persists...

<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key> NSExtensionActivationSupportsImageWithMaxCount </key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsText</key>
            <false/>
        </dict>
    </dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
    <key>NSExtensionPrincipalClass</key>
    <string>ShareOnAPPNAMEVC</string>
</dict>

Also App shows sharing option to each and every type i.e. movies, text, webpage etc. along with images.

Body:
I would suggest you to use this:

<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key>NSExtensionActivationRule</key>
            <string>TRUEPREDICATE</string>
            <key>NSExtensionActivationSupportsFileWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsImageWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsMovieWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsText</key>
            <false/>
            <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
            <integer>1</integer>
        </dict>
    </dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
</dict>


问:
Trouble displaying code on screen
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help. </p>

```<code>function convertToRoman(num) {
var romans = {
    M:  1000,
    CM: 900,
    D:  500,
    CD: 400,
    C:  100,
    XC: 90,
    L:  50,
    XL: 40,
    X:  10,
    IX: 9,
    V:  5,
    IV: 4,
    I:  1,
};

var result = '';

for (var key in romans) {
    if (num >= romans[key]) {
        result += key.repeat(Math.trunc(num / romans[key]));
        num -= romans[key] * Math.trunc(num / romans[key]);
    }
}

return result;

}
</code>```

答:
You are missing the part where you attach the result to the html. See working code below as an example.

function convertToRoman(num) {
  var romans = {
      M:  1000,
      CM: 900,
      D:  500,
      CD: 400,
      C:  100,
      XC: 90,
      L:  50,
      XL: 40,
      X:  10,
      IX: 9,
      V:  5,
      IV: 4,
      I:  1,
  };

  var result = '';

  for (var key in romans) {
      if (num >= romans[key]) {
          result += key.repeat(Math.trunc(num / romans[key]));
          num -= romans[key] * Math.trunc(num / romans[key]);
      }
  }

  document.getElementById('output').innerHTML = result;
}

convertToRoman(12345);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div> my result <span id="output"></span></div></code>```

Title: Trouble displaying code on screen

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

function convertToRoman(num) {
var romans = {
    M:  1000,
    CM: 900,
    D:  500,
    CD: 400,
    C:  100,
    XC: 90,
    L:  50,
    XL: 40,
    X:  10,
    IX: 9,
    V:  5,
    IV: 4,
    I:  1,
};

var result = '';

for (var key in romans) {
    if (num >= romans[key]) {
        result += key.repeat(Math.trunc(num / romans[key]));
        num -= romans[key] * Math.trunc(num / romans[key]);
    }
}

return result;

}

Body:
You are missing the part where you attach the result to the html. See working code below as an example.

function convertToRoman(num) {
  var romans = {
      M:  1000,
      CM: 900,
      D:  500,
      CD: 400,
      C:  100,
      XC: 90,
      L:  50,
      XL: 40,
      X:  10,
      IX: 9,
      V:  5,
      IV: 4,
      I:  1,
  };

  var result = '';

  for (var key in romans) {
      if (num >= romans[key]) {
          result += key.repeat(Math.trunc(num / romans[key]));
          num -= romans[key] * Math.trunc(num / romans[key]);
      }
  }

  document.getElementById('output').innerHTML = result;
}

convertToRoman(12345);

<div> my result <span id="output"></span></div>


问:
Python Dictionary Syntax Error [learn python the hard way -ex39]
```<code>states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon
</code>```

<p>Why is this code showing syntax error in line 2?
Running on python 2.7.12 (default on ubuntu) </p>

答:
First of all, for a dictionary in python you should use the brackets {} and not []. In addition, if you want to access an element of a dictionary in python, you should write:</p>

```<code>states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }

print states['Oregon']
</code>```

Body:
states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon

Why is this code showing syntax error in line 2?
Running on python 2.7.12 (default on ubuntu)

Body:
First of all, for a dictionary in python you should use the brackets {} and not []. In addition, if you want to access an element of a dictionary in python, you should write:

states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }

print states['Oregon']


问:
ppt paste from excel clipboard to slide
I have a chart range copied from excel. Now I want to paste it as picture in slide 5 of active presentation, but it is giving me below error.

"Shapes(unknown member):Invalid request.Clipboard is empty or contains data which may not be pasted here."

Please help, code below.

```<code>Sub UpdateCharts()
Dim oPP As PowerPoint.Slide
Dim shp As PowerPoint.shape
ActivePresentation.Slides(5).Shapes.Paste
End Sub
</code>```

答:
Try this: </p>

```<code>  mySlide.Shapes.PasteSpecial DataType:=2  '2 = ppPasteEnhancedMetafile
  Set myShape = mySlide.Shapes(mySlide.Shapes.(5))
</code>```

Title: ppt paste from excel clipboard to slide

Body:
I have a chart range copied from excel. Now I want to paste it as picture in slide 5 of active presentation, but it is giving me below error.

"Shapes(unknown member):Invalid request.Clipboard is empty or contains data which may not be pasted here."

Please help, code below.

Sub UpdateCharts()
Dim oPP As PowerPoint.Slide
Dim shp As PowerPoint.shape
ActivePresentation.Slides(5).Shapes.Paste
End Sub

Body:
Try this:

  mySlide.Shapes.PasteSpecial DataType:=2  '2 = ppPasteEnhancedMetafile
  Set myShape = mySlide.Shapes(mySlide.Shapes.(5))


问:
group_rows() function in kableExtra package not grouping rows
I am trying to output a table in rmarkdown using the kable() as a part of the knitr package.  Below is one table that shows what I am trying to output with a built in data set.  The other is a subset of my data set.  When using my data set the output is not lining up and the code is basically the same.  I feel like I a missing something basic?  Please let me know! My code is below, and a picture of the output is below that.

```<code>```{r, results="asis"}
Table = kable(mtcars[1:10, 1:6], caption = "GOOD TABLE", booktabs = T, format="latex")
Table = kable_styling(Table)
Table = group_rows(Table, "Group 1", 2, 4)
group_rows(Table, "Group 2", 5, 6)
```

```{r, results="asis"}
Table = data.frame(MYDATA)
Table = kable(Table, caption = "BAD TABLE", booktabs = T, format="latex")
Table = kable_styling(Table)
Table = group_rows(Table, "Group 1", 2, 4)
group_rows(Table, "Group 2", 5, 6)
```
</code>```

答:
Thanks for reporting!

This bug was produced by a mishandling of backslash in front of special inline symbols. It has been fixed in the current github version. Please use devtools::install_github("haozhu233/kableExtra") and install the latest version. Or you can wait for the CRAN version which will be release in about 2 weeks.

Body:
I am trying to output a table in rmarkdown using the kable() as a part of the knitr package.  Below is one table that shows what I am trying to output with a built in data set.  The other is a subset of my data set.  When using my data set the output is not lining up and the code is basically the same.  I feel like I a missing something basic?  Please let me know! My code is below, and a picture of the output is below that.

```{r, results="asis"}
Table = kable(mtcars[1:10, 1:6], caption = "GOOD TABLE", booktabs = T, format="latex")
Table = kable_styling(Table)
Table = group_rows(Table, "Group 1", 2, 4)
group_rows(Table, "Group 2", 5, 6)
```

```{r, results="asis"}
Table = data.frame(MYDATA)
Table = kable(Table, caption = "BAD TABLE", booktabs = T, format="latex")
Table = kable_styling(Table)
Table = group_rows(Table, "Group 1", 2, 4)
group_rows(Table, "Group 2", 5, 6)
```


问:
How identifiers are stored in memory?
any value assigned to a variable (e.g. int i=5) is stored in memory in hexadecimal form at some address.
So will the variable name(i) associated with the value is converted to ASCII code in memory while storing?</p>

答:
I can't speak to Java.

In C, variable identifiers are (usually) not preserved in the generated machine code.  Instead, you'll (usually) see objects referred to via an offset from a register.

For example, on my system, given the source line

```<code>i = 5;
</code>```

my compiler generates the machine code

```<code>movl $5, -4(%rbp)
</code>```

%rbp is the base pointer register - it stores the base address of a stack frame, which includes space for function arguments (if any), local variables (if any), and the address of the next instruction following the function call.  On my system, local variables are stored "below" the value in the base pointer register (negative offset), while function arguments are stored "above" it (positive offset).  The identifier associated with the function argument or variable is not preserved at all.

Title: How identifiers are stored in memory?

Body:
I can't speak to Java.

In C, variable identifiers are (usually) not preserved in the generated machine code.  Instead, you'll (usually) see objects referred to via an offset from a register.

For example, on my system, given the source line

i = 5;

my compiler generates the machine code

movl $5, -4(%rbp)

%rbp is the base pointer register - it stores the base address of a stack frame, which includes space for function arguments (if any), local variables (if any), and the address of the next instruction following the function call.  On my system, local variables are stored "below" the value in the base pointer register (negative offset), while function arguments are stored "above" it (positive offset).  The identifier associated with the function argument or variable is not preserved at all.


问:
Listen to any changes (caused by code) in value of an HTML element
I can use some events like "oninput", "onchange" ... to detect if an HTML element change its value. But these events occurs only when user manually change the value (By keyboard, mouse...)

But sometimes HTML elements's values are changed by my code (not by users) or by form's reset() method and I also want to listen to these change events.

So how can I detect when a value of an element changes? (In all situations)

答:
You can try DOMSubtreeModified event

```<code>$('element').on("DOMSubtreeModified",function(){
  alert('changed');
});
</code>```

*Depending of the version of jquery instead of .on can be .bind

Or you can work with MutationObserver which detects changes in the DOM and is the most recommended.

Body:
You can try DOMSubtreeModified event

$('element').on("DOMSubtreeModified",function(){
  alert('changed');
});

*Depending of the version of jquery instead of .on can be .bind

Or you can work with MutationObserver which detects changes in the DOM and is the most recommended.


问:
How to use strpos() to check a variable's path?
I have a home page that shows some uploaded images.

I take it from the database and I use strpos() to check the URL due to directory problems, and it works fine:

```<code>if(strpos($row['cImage'],"http://") === FALSE){
    echo "<img src='serintercement/".$row['cImage']."' style='width: 107px; height:102px;' />";
}else{
    echo "<img src='".$row['cImage']."' style='width: 107px; height:102px;' />";
}
</code>```

I need to use the same logic in a page that shows the clicked image, but it has a variable for it and I'm struggling to fix this since it's a different way to write:

```<code><img src='<?php echo $resultData->cImage; ?>'/>
</code>```

I can't fix the directory problem. How can I use strpos() similarly for this second code?

答:
If these cImage strings are coming from your database, you could just correct them in the query call.

For example, if you are using MySQL, you could prepare the data using LOCATE() AND CONCAT() like this:

```<code>SELECT
    IF(LOCATE('http',`cImage`)!=1,CONCAT('serintercement/',`cImage`),`cImage`) `new_cImage`
FROM ...
</code>```

Moving the conditional process to your query, will make your "displaying" code read more smoothly because all of the preparations are completed ahead of time.

Outside of that, you can make your code more DRY by not repeating the html parts that come before and after the image variable...

This is an echo with an inline condition (not everyone likes this style):

```<code>echo "<img src=\"",(strpos($resultData->cImage,"http")===0?'':'serintercement/'),"{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
</code>```

This is a separated conditional:

```<code>echo "<img src=\"";
    if(strpos($resultData->cImage,"http")!==0){
        echo 'serintercement/'
    }
echo "{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
</code>```

This is a function call if you have to do this multiple times in the same script:

```<code>function fixPath($img){
    if(strpos($img,"http")===0){
        return $img;
    }
    return "serintercement/$img";
}
echo "<img src=\"",fixPath($resultData->cImage),"\" style=\"width:107px;height:102px;\" />\n";
</code>```

Notice that I am only checking for http and that I am very accurately checking that it comes from the first position in the string.  Across all these alternatives, the point I am making is DRYness (which is a typical pursuit of all programmers).  How you chose to implement it comes down to your personal preference.

Body:
I have a home page that shows some uploaded images.

I take it from the database and I use strpos() to check the URL due to directory problems, and it works fine:

if(strpos($row['cImage'],"http://") === FALSE){
    echo "";
}else{
    echo "";
}

I need to use the same logic in a page that shows the clicked image, but it has a variable for it and I'm struggling to fix this since it's a different way to write:

<img src='<?php echo $resultData->cImage; ?>'/>

I can't fix the directory problem. How can I use strpos() similarly for this second code?

Body:
If these cImage strings are coming from your database, you could just correct them in the query call.

For example, if you are using MySQL, you could prepare the data using LOCATE() AND CONCAT() like this:

SELECT
    IF(LOCATE('http',`cImage`)!=1,CONCAT('serintercement/',`cImage`),`cImage`) `new_cImage`
FROM ...

Moving the conditional process to your query, will make your "displaying" code read more smoothly because all of the preparations are completed ahead of time.

Outside of that, you can make your code more DRY by not repeating the html parts that come before and after the image variable...

This is an echo with an inline condition (not everyone likes this style):

echo "<img src=\"",(strpos($resultData->cImage,"http")===0?'':'serintercement/'),"{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";

This is a separated conditional:

echo "<img src=\"";
    if(strpos($resultData->cImage,"http")!==0){
        echo 'serintercement/'
    }
echo "{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";

This is a function call if you have to do this multiple times in the same script:

function fixPath($img){
    if(strpos($img,"http")===0){
        return $img;
    }
    return "serintercement/$img";
}
echo "<img src=\"",fixPath($resultData->cImage),"\" style=\"width:107px;height:102px;\" />\n";

Notice that I am only checking for http and that I am very accurately checking that it comes from the first position in the string.  Across all these alternatives, the point I am making is DRYness (which is a typical pursuit of all programmers).  How you chose to implement it comes down to your personal preference.


问:
How to publish B2B Android apps to external Enterprise
Apple has the B2B App Store which allows a developer to "distribute tailored solutions directly to business customers". With this the app does not have to be visible to the general public.

Does Google Play have a similar setup that allows me to do the same thing? The Managed Google Play documentation has details for distribution (consumer end), but nothing detailing whether the publisher can restrict the app to particular business customers (as Windows Business Store and iOS B2B Store).

答:
You can do this by using Google play private Chanel I am also doing the same thing for one of my customer below is link:

https://support.google.com/googleplay/android-developer/answer/6145139?hl=en


问:
Matrimony website in Joomla
we have got a new project related to Matrimony and our management wants to use Joomla for this. I suggested that it can be done well in core php or any framework, but my boss asks why cant we do it in Joomla.

But i oppose it to the point that Joomla is not suited for a site like matrimony.
I think it would be very complex for developing the design and functionality in Joomla, than with a normal php site.

I doubt whether it would be fair to go ahead with Joomla for this purpose.
Can anyone tell me what i needed to do this in Joomla, if it is a feasible solution.
I especially want to know how to do the design of inner pages with joomla.

答: Joomla in its core has good template and CMS functionality. If your site is all about publishing content and requires good template then you can chose joomla as your choice. Learning i guess would not be tough.</p>

Title: Matrimony website in Joomla


问:
Finding index funtion returns zero (0) Matlab
I use this function in matlab to find the index of two values in matrix A matching two values in matrix B:

```<code>[~, ind] = ismember(A(:, [1 2]), B(:, [1 2]), 'rows');
</code>```

However, i get some values 0 returned as output.

Does this mean that certain pairs of values in matrix B are not present in matrix A?

答:
Read the documentation part, MATLAB is very rich in documentation. Check the below example:

```<code>A = [1 2 3; 4 5 6; 7 -9 0] ;
B = [3 4 5 ; 1 2 3 ] ;
[Lia, Locb] = ismember(A,B, 'rows')
Lia =

     1
     0
     0

Locb =

     2
     0
     0
</code>```

The result, Lia is logical and Locb is double. Lia gives logical indices in A which are common rows in A and B. (In the example the first row in A [1 2 3], is common), so the logical indices would be [1 0 0]'. Locb gives the indices/ location of common rows in B. (Here common row [ 1 2 3], this occurs in B at second row) so the result [2  0 0]'.

In your case, you said the result ind are zeroes, so there are no common rows.

Body:
I use this function in matlab to find the index of two values in matrix A matching two values in matrix B:

[~, ind] = ismember(A(:, [1 2]), B(:, [1 2]), 'rows');

However, i get some values 0 returned as output.

Does this mean that certain pairs of values in matrix B are not present in matrix A?

Body:
Read the documentation part, MATLAB is very rich in documentation. Check the below example:

A = [1 2 3; 4 5 6; 7 -9 0] ;
B = [3 4 5 ; 1 2 3 ] ;
[Lia, Locb] = ismember(A,B, 'rows')
Lia =

     1
     0
     0

Locb =

     2
     0
     0

The result, Lia is logical and Locb is double. Lia gives logical indices in A which are common rows in A and B. (In the example the first row in A [1 2 3], is common), so the logical indices would be [1 0 0]'. Locb gives the indices/ location of common rows in B. (Here common row [ 1 2 3], this occurs in B at second row) so the result [2  0 0]'.

In your case, you said the result ind are zeroes, so there are no common rows.


问:
C# FtpWebRequest with SSL to Ubuntu VSFTPD
I have spent hours trying to get the .NET FtpWebRequest library to communicate with my Ubuntu 16.04 FTP server using vsftpd over SSL.

No matter what I try, I always end up with the exception "A call to SSPI failed. The message received was unexpected or badly formatted."

I have tried generating client and server certificates, installing them in windows, loading them with the X509 class in .NET, toggling various client and server side options. No matter what I do, it's always the same error. I believe this has something to do with my certificate not being verified by an authority. Here are my basic questions:

1) Can .NET just ACCEPT a suspicious certificate?! Installing it 30 different ways seems to have no affect?

2) What does "a call to SSPI failed" really mean? I've read conflicting answers. I have no problem connecting with TLS/SSL via FileZilla, but .NET 4.5 just won't have it.

3) Can someone give the minimum amount of steps to have a Windows 7 client using the .NET framework connect to a Linux server using vsftpd over SSL? I strongly believe the problem lies in my Windows/.NET settings since FileZilla on my Windows machine has no problem connecting.

Thank you in advance.

答:
Insert the line below in your vsftpd.conf:</p>

```<code>ssl_ciphers=AES128-SHA
</code>```

Body:
Insert the line below in your vsftpd.conf:

ssl_ciphers=AES128-SHA


问:
How to create Tamil Language Based Web Application in Laravel 5.4
I planed to create Departmental Store Laravel Web Application in Tamil Language Not Using English. How to do it?</p>

答: In your encoding defined at DB and front end use - UTF-8 encoding which supports most of the international languages</p>


问:
reduce the access level of a function in a derived class
Is there any possibility to reduce the access level of a function in a derived class in PHP?

example (... means more code)

```<code>class foo
{
  public function myFunction() { ... }
  public function myOtherFunction() { ... }
}

class bar extends foo
{
  private function myFunction() { ... }
}
</code>```

Now I should'nt be able to call MyFunc ion a bar object. But doing it this way doesn't seem to be valid in PHP. Any other way? I know I could implement an empty function but I don't want to expose the function in the interface at all.

答:
Its not valid in OOP anyway. If you implement a public method, you promise, that this class and all children provides this functionality. To remove a public method means, that you break your promises ;) Because all public methods and properties define the interface of the class and breaking an interface is never a good idea.

Without any clearer information about what you are going to do I suggest to just throw an exception, something like "Not supported".

Body:
Is there any possibility to reduce the access level of a function in a derived class in PHP?

example (... means more code)

class foo
{
  public function myFunction() { ... }
  public function myOtherFunction() { ... }
}

class bar extends foo
{
  private function myFunction() { ... }
}

Now I should'nt be able to call MyFunc ion a bar object. But doing it this way doesn't seem to be valid in PHP. Any other way? I know I could implement an empty function but I don't want to expose the function in the interface at all.


问:
Set DateTimePicker Control to format YYYYMMDD?
I am putting together a simple C# Windows Forms Application. I am setting my DateTimePicker control on load to the current DateTime, example "11/12/2013 9:49:49 AM". I then use this value in a query to my 400 system, but I am getting an error because the field I query against the DateTimePicker Controls value is in format 'YYYYMMDD'.

How do I format the value of my DateTimePicker Control to 'YYYYMMDD' to use it in my query?

答:
This worked for me...</p>

```<code>string dt = dateTimePicker1.Value.ToString("yyyy/MM/dd");
</code>```

Body:
This worked for me...

string dt = dateTimePicker1.Value.ToString("yyyy/MM/dd");


问:
Rendering ReactJS component based on a list of objects
I have the following component:

articles_list.jsx

```<code>import React from 'react';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  render() {

    var teste = () => {
      if (this.state.articles === null) {
        return(<div>No articles</div>)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            return <div key={index}>{element.title}</div>;
          })}
      }
    }

    return(
      <div className="articles_list">
        <div className="articles_list_title">
          ARTICLES
        </div>
        <div>{teste()}</div>
      </div>
    );
  }
}
</code>```

Although the JSON request is working fine and returning an array with five JSON objects, they just don't render!

I am new to ReactJS and read (and watched) lots of tutorials, but it seems I am missing something.

Any suggestions?

答:
You may try something like this.

```<code>import _ from 'lodash';
renderArticles() {
  return _.map(this.state.articles, article => {
    return (
      <li className="list-group-item" key={article.id}>
          {article.title}
      </li>
    );
  });
}

  render() {
    return (
      <div>
        <h3>Articles</h3>
        <ul className="list-group">
          {this.renderArticles()}
        </ul>
      </div>
    );
  }
</code>```

Map over the list and render it one by one. Here I am using lodash map helper to get this done. Hope this helps. Happy coding.

Body:
I have the following component:

articles_list.jsx

import React from 'react';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  render() {

    var teste = () => {
      if (this.state.articles === null) {
        return(
No articles
)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            return
{element.title}
;
          })}
      }
    }

    return(

          ARTICLES

{teste()}

    );
  }
}

Although the JSON request is working fine and returning an array with five JSON objects, they just don't render!

I am new to ReactJS and read (and watched) lots of tutorials, but it seems I am missing something.

Any suggestions?

Body:
You may try something like this.

import _ from 'lodash';
renderArticles() {
  return _.map(this.state.articles, article => {
    return (
      <li className="list-group-item" key={article.id}>
          {article.title}
      </li>
    );
  });
}

  render() {
    return (
      <div>
        <h3>Articles</h3>
        <ul className="list-group">
          {this.renderArticles()}
        </ul>
      </div>
    );
  }

Map over the list and render it one by one. Here I am using lodash map helper to get this done. Hope this helps. Happy coding.


问:
Android React - Getting "Requiring unknown module react"
I keep getting this error when running the app on mobile android device, can anyone help.

The actual error:

```<code>Error: Requiring unknown module "react". If you are sure the module is there, try restarting the package or running "npm install". (index.android.bundle:93)
</code>```

答:
Try deleting the node_modules folder and run npm install in command line at project root directory.

If it still fails, try to run npm install react --save

Body:
I keep getting this error when running the app on mobile android device, can anyone help.

The actual error:

Error: Requiring unknown module "react". If you are sure the module is there, try restarting the package or running "npm install". (index.android.bundle:93)


问:
babel taking a long time to copy a entire html-template
I'm build a project with Node+Electron and it's being built with Babel with this command:

"private:compile": "babel app/ --copy-files --out-dir build",

It's working fine. The problem started when I downloaded a HTML template that has 40mb of JS and CSS and put everything in public assets dir. Now babel takes a long to compile project because it's many many many files.

Is there any way to make babel ignores compiling and simply copy some certain files? Or make babel ignore files that hasn't changed?

thanks!

答:
Babel usually looks for a .babelrc in the current folder and if it finds one it searches for a setting like:-

```<code>{
 "ignore": [
    "foo.js",
    "bar/**/*.js"
  ]
}
</code>```

That setting will ignore the files being looked up.
If .babelrc does not exist, it will travel up the directory tree until it finds either a .babelrc, or a package.json with a "babel": {} hash within.

Hope this helps.

Body:
Babel usually looks for a .babelrc in the current folder and if it finds one it searches for a setting like:-

{
 "ignore": [
    "foo.js",
    "bar/**/*.js"
  ]
}

That setting will ignore the files being looked up.
If .babelrc does not exist, it will travel up the directory tree until it finds either a .babelrc, or a package.json with a "babel": {} hash within.

Hope this helps.


答:
return statement inside a forEach doesn't return the value instead it acts like a continue statement, you need  to make use of map

```<code>var teste = () => {
  if (this.state.articles === null) {
    return(<div>No articles</div>)
  } else {
      {this.state.articles.map( function(element, index) {
        console.log(element);
        return <div key={index}>{element.title}</div>;
      })}
  }
}
</code>```

else if you want to go with forEach you need to modify your code like

```<code>render() {

    var teste = []

      if (this.state.articles === null) {
        teste.push(<div>No articles</div>)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            teste.push( <div key={index}>{element.title}</div>);
          })}
      }
    }

    return(
      <div className="articles_list">
        <div className="articles_list_title">
          ARTICLES
        </div>
        <div>{teste}</div>
      </div>
    );
  }
</code>```

Title: Rendering ReactJS component based on a list of objects

Body:
return statement inside a forEach doesn't return the value instead it acts like a continue statement, you need  to make use of map

var teste = () => {
  if (this.state.articles === null) {
    return(<div>No articles</div>)
  } else {
      {this.state.articles.map( function(element, index) {
        console.log(element);
        return <div key={index}>{element.title}</div>;
      })}
  }
}

else if you want to go with forEach you need to modify your code like

render() {

    var teste = []

      if (this.state.articles === null) {
        teste.push(<div>No articles</div>)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            teste.push( <div key={index}>{element.title}</div>);
          })}
      }
    }

    return(
      <div className="articles_list">
        <div className="articles_list_title">
          ARTICLES
        </div>
        <div>{teste}</div>
      </div>
    );
  }


问:
JPA very strange error when change query parameter
I'm having an strange issue in this query.
Code:

```<code>em2=getNewEntityManager();
(...)
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '"+dni+"'") ;
                List <Long> permisos = query2.getResultList();
(...)
</code>```

If "dni" equals to: "%" the query goes normal, but if "dni" is "%123456789" gives this error

javax.persistence.PersistenceException: Exception [EclipseLink-4002]
  (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
  org.eclipse.persistence.exceptions.DatabaseException
          Internal Exception: java.sql.SQLException: sql string is not a dml statement
          Error Code: 17129
          Call: SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'
          Query: DataReadQuery(sql="SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'")

And if I copy the exact query above in my SQL developer, it works as magic.
I've tried with the "createQuery" with the entities and all the stuff, same error.

Thanks a lot

答:
Try assigning the value to a parameter, such as:

```<code>String dni = "some value";
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like :param") ;
query2.setParamter("param", dni);
List <Long> permisos = query2.getResultList();
</code>```

Update: In EclipseLink, Only indexed parameters are supported, named parameters are not supported.

Body:
I'm having an strange issue in this query.
Code:

em2=getNewEntityManager();
(...)
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '"+dni+"'") ;
                List <Long> permisos = query2.getResultList();
(...)

If "dni" equals to: "%" the query goes normal, but if "dni" is "%123456789" gives this error

javax.persistence.PersistenceException: Exception [EclipseLink-4002]
  (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
  org.eclipse.persistence.exceptions.DatabaseException
          Internal Exception: java.sql.SQLException: sql string is not a dml statement
          Error Code: 17129
          Call: SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'
          Query: DataReadQuery(sql="SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'")

And if I copy the exact query above in my SQL developer, it works as magic.
I've tried with the "createQuery" with the entities and all the stuff, same error.

Thanks a lot

Body:
Try assigning the value to a parameter, such as:

String dni = "some value";
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like :param") ;
query2.setParamter("param", dni);
List <Long> permisos = query2.getResultList();

Update: In EclipseLink, Only indexed parameters are supported, named parameters are not supported.