问:
Add data to dynamically created Chart.js dataset
I feel like I'm very close but I can't seem to get the last bit right. I'm trying to create a line chart in Chart.js with dynamic datasets from a JSON file.

My JSON is as following:

```<code>{
  "source":"Google Trends",
  "keywords":
  [
    {
      "value":"Keyword 1",
      "data":
      [
        {
          "month":"Dec",
          "popularity":"10"
        },
        {
          "month":"Jan",
          "popularity":"35"
        }
      ]
    },
    {
      "value":"Keyword 2",
      data:
      [
        ...
      ]
    }
  ]
}
</code>```

Then I have the following jQuery:

```<code>var source = "Google Trends";
var trendDataset = [];
var trendData = [];

$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

    });
  }
});
</code>```

This is working fine, it's creating a new dataset for each keyword that is in the JSON file. But I'm having trouble filling those datasets.

I'm trying to pass it a data array (trendData[]) which is filled with the popularity data for each keyword. I know I need to loop through the data array of each keyword, so I added this $.each loop in the existing loop:

```<code>$.each(keyword.data, function(index, data) {
  trendData.push(data.popularity);
});
</code>```

Creating this in total:

```<code>$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

      $.each(keyword.data, function(index, data) {
        trendData.push(data.popularity);
      });

    });
  }
});
</code>```

Obviously, this is adding all the popularity data from all keywords, creating one big trendData[]. Replacing trendData.push(data.popularity) with trendData[index] = data.popularity does the right thing, but again, obviously only for the last keyword since it keeps on getting overwritten.

How can I create a seperate trendData[] for each trendDataset[]?

I guess I need something like this in the second $.each:

```<code>$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
  trendDataset[index].push(trendData);
});
</code>```

This however gives me an error: trendDataset[index].push is not a function

edit:
Walking through it step by step, it makes sense that this doesn't work. It loops through the first array once, creating the first dataset. Then it loops through the 2nd array three times, and then that pattern repeats itself.

I somehow need to be able to access the 2nd array's property, in the first array, like so:

```<code>trendDataset[index] = {
  data: trendData.data.popularity
}
</code>```

But how..?

edit2:
The more I'm trying to find a solution, the more clueless I'm getting. Whenever I console.log trendData after setting it like this:

```<code>$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
});

console.log(trendData);
</code>```

It shows the object with the correct values 3 times, but upon opening it's only showing me the values of the last iteration???

Screenshot

答:
I finally figured it out. It was much easier then I thought and I have no idea why I didn't figure this out sooner..

Simply create seperate arrays within the first $.each loop and set the values..

```<code>var trendDataset = [];

$.each(trends.keywords, function(index, keyword) {
  // Create an Array for each data object
  trendData = [];
  trendLabels = [];
    $.each(keyword.data, function(index, data) {
      trendLabels[index] = data.month,
      trendData[index] = data.popularity
    });
  // Push the array with data to another array
  trendDataset[index].data = trendData;
});
</code>```

Body:
I feel like I'm very close but I can't seem to get the last bit right. I'm trying to create a line chart in Chart.js with dynamic datasets from a JSON file.

My JSON is as following:

{
  "source":"Google Trends",
  "keywords":
  [
    {
      "value":"Keyword 1",
      "data":
      [
        {
          "month":"Dec",
          "popularity":"10"
        },
        {
          "month":"Jan",
          "popularity":"35"
        }
      ]
    },
    {
      "value":"Keyword 2",
      data:
      [
        ...
      ]
    }
  ]
}

Then I have the following jQuery:

var source = "Google Trends";
var trendDataset = [];
var trendData = [];

$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

    });
  }
});

This is working fine, it's creating a new dataset for each keyword that is in the JSON file. But I'm having trouble filling those datasets.

I'm trying to pass it a data array (trendData[]) which is filled with the popularity data for each keyword. I know I need to loop through the data array of each keyword, so I added this $.each loop in the existing loop:

$.each(keyword.data, function(index, data) {
  trendData.push(data.popularity);
});

Creating this in total:

$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

      $.each(keyword.data, function(index, data) {
        trendData.push(data.popularity);
      });

    });
  }
});

Obviously, this is adding all the popularity data from all keywords, creating one big trendData[]. Replacing trendData.push(data.popularity) with trendData[index] = data.popularity does the right thing, but again, obviously only for the last keyword since it keeps on getting overwritten.

How can I create a seperate trendData[] for each trendDataset[]?

I guess I need something like this in the second $.each:

$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
  trendDataset[index].push(trendData);
});

This however gives me an error: trendDataset[index].push is not a function

edit:
Walking through it step by step, it makes sense that this doesn't work. It loops through the first array once, creating the first dataset. Then it loops through the 2nd array three times, and then that pattern repeats itself.

I somehow need to be able to access the 2nd array's property, in the first array, like so:

trendDataset[index] = {
  data: trendData.data.popularity
}

But how..?

edit2:
The more I'm trying to find a solution, the more clueless I'm getting. Whenever I console.log trendData after setting it like this:

$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
});

console.log(trendData);

It shows the object with the correct values 3 times, but upon opening it's only showing me the values of the last iteration???

Screenshot

Body:
I finally figured it out. It was much easier then I thought and I have no idea why I didn't figure this out sooner..

Simply create seperate arrays within the first $.each loop and set the values..

var trendDataset = [];

$.each(trends.keywords, function(index, keyword) {
  // Create an Array for each data object
  trendData = [];
  trendLabels = [];
    $.each(keyword.data, function(index, data) {
      trendLabels[index] = data.month,
      trendData[index] = data.popularity
    });
  // Push the array with data to another array
  trendDataset[index].data = trendData;
});


来源: stackexchange

问:
C# How to use Directory White Spaces into process.arguements?
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

```<code>            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();
</code>```

答:
Perhaps

```<code>process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
</code>```

should be

```<code>process.StartInfo.Arguments = @"-r ""C:\test\ftk\ntuser.dat"" -d ""C:\System Volume Information\""" + restoreFolder.Name + " -p runmru";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

Body:
Perhaps

process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";

should be

process.StartInfo.Arguments = @"-r ""C:\test\ftk\ntuser.dat"" -d ""C:\System Volume Information\""" + restoreFolder.Name + " -p runmru";


问:
OWIN Katana middleware: How to block an user if claims returned doesn't have a specific role in them?
I am successfully authenticating the user at the Identity Server and getting back the claims (along with roles as claims). All is well when I do not consider roles. I want to restrict the user unless he has a specific role and redirect him to a specifically created "Unauthorised" or "Access denied" page. The following code below doesn't raise an unauthorised exception.

```<code>var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP");
if (!canAccessPortal)
{
    throw new UnauthorizedAccessException();
}
</code>```

Complete app.UseOpenIdConnectAuthentication code is below:

```<code>app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    ClientId = ClientId,
    Authority = IdServBaseUri,
    RedirectUri = ClientUri,
    PostLogoutRedirectUri = ClientUri,
    ResponseType = "code id_token token",
    Scope = "openid profile roles clef",
    TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    },
    SignInAsAuthenticationType = "Cookies",

    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        AuthorizationCodeReceived = async n =>
        {
            // use the code to get the access and refresh token
            var tokenClient = new TokenClient(
                TokenEndpoint,
                ClientId,
                ClientSecret);

            var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            // use the access token to retrieve claims from userinfo
            var userInfoClient = new UserInfoClient(UserInfoEndpoint);

            var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

            // create new identity
            var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
            id.AddClaims(userInfoResponse.Claims);
            id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
            id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
            id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
            id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

            var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP");
            if (!canAccessPortal)
            {
                throw new UnauthorizedAccessException();
            }

            n.AuthenticationTicket = new AuthenticationTicket(
                new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                n.AuthenticationTicket.Properties);
        },

        RedirectToIdentityProvider = n =>
        {
            // if signing out, add the id_token_hint
            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
            {
                var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                if (idTokenHint != null)
                {
                    n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                }
            }

            return Task.FromResult(0);
        }
    }
});
</code>```

Custom error node in web.config file:

```<code><customErrors mode="On" defaultRedirect="~/account/error">
  <error statusCode="401" redirect="~/account/unauthorized" />
</customErrors>
</code>```

答:
The best place to implement authorization in the mvc pipeline is by implementing AuthorizationAttribute. Here you have full control over the request context. Make sure if you are authorizing for MVC you should implement System.Web.MVC .AuthorizeAttribute and implement override AuthorizeCore.</p>

```<code>    protected override bool AuthorizeCore(HttpContextBase httpContext) {

        if (!base.AuthorizeCore(httpContext)) {
            return false;
        }
        //Check roles from DB service
        return roleservice.UserInRole && UserClaims.Count > 0;
    }

    /// <summary>
    /// Processes HTTP requests that fail authorization.
    /// </summary>
    /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />. The <paramref name="filterContext" /> object contains the controller, HTTP context, request context, action result, and route data.</param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        filterContext.Result = new RedirectResult("~/main/unauthorized");
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am successfully authenticating the user at the Identity Server and getting back the claims (along with roles as claims). All is well when I do not consider roles. I want to restrict the user unless he has a specific role and redirect him to a specifically created "Unauthorised" or "Access denied" page. The following code below doesn't raise an unauthorised exception.

var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP");
if (!canAccessPortal)
{
    throw new UnauthorizedAccessException();
}

Complete app.UseOpenIdConnectAuthentication code is below:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    ClientId = ClientId,
    Authority = IdServBaseUri,
    RedirectUri = ClientUri,
    PostLogoutRedirectUri = ClientUri,
    ResponseType = "code id_token token",
    Scope = "openid profile roles clef",
    TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    },
    SignInAsAuthenticationType = "Cookies",

    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        AuthorizationCodeReceived = async n =>
        {
            // use the code to get the access and refresh token
            var tokenClient = new TokenClient(
                TokenEndpoint,
                ClientId,
                ClientSecret);

            var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            // use the access token to retrieve claims from userinfo
            var userInfoClient = new UserInfoClient(UserInfoEndpoint);

            var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

            // create new identity
            var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
            id.AddClaims(userInfoResponse.Claims);
            id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
            id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
            id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
            id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));

            var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP");
            if (!canAccessPortal)
            {
                throw new UnauthorizedAccessException();
            }

            n.AuthenticationTicket = new AuthenticationTicket(
                new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
                n.AuthenticationTicket.Properties);
        },

        RedirectToIdentityProvider = n =>
        {
            // if signing out, add the id_token_hint
            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
            {
                var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                if (idTokenHint != null)
                {
                    n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                }
            }

            return Task.FromResult(0);
        }
    }
});

Custom error node in web.config file:

<customErrors mode="On" defaultRedirect="~/account/error">
  <error statusCode="401" redirect="~/account/unauthorized" />
</customErrors>

Body:
The best place to implement authorization in the mvc pipeline is by implementing AuthorizationAttribute. Here you have full control over the request context. Make sure if you are authorizing for MVC you should implement System.Web.MVC .AuthorizeAttribute and implement override AuthorizeCore.

    protected override bool AuthorizeCore(HttpContextBase httpContext) {

        if (!base.AuthorizeCore(httpContext)) {
            return false;
        }
        //Check roles from DB service
        return roleservice.UserInRole && UserClaims.Count > 0;
    }

    /// <summary>
    /// Processes HTTP requests that fail authorization.
    /// </summary>
    /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />. The <paramref name="filterContext" /> object contains the controller, HTTP context, request context, action result, and route data.</param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        filterContext.Result = new RedirectResult("~/main/unauthorized");
    }


问:
Problems Building Application as Release in Visual Studio 2008 - C++
I'm having a little trouble building my application as Release in Visual Studio 2008.  It builds fine without any errors or warning as Debug.  The application is primarily Win32 with a little MFC and ATL mixed in here and there.  Most of the projects in the solution generate a LIB and DLL.

This is one of the errors I am getting:

fatal error C1189: #error :  Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]

My application is a multithreaded DLL, so the /MD needs to stay.  The only Windows includes are these:

```<code>#include "stdafx.h"
#include "afx.h"
#include "WMIQuery.h"
#include "SerialPort.h"
</code>```

The other error is this:

fatal error C1083: Cannot open include file: 'WMIQuery.h': No such file or directory

This one really doesn't make sense to me because, the environment has no problem finding this file building for Debug.

Does anyone know how to fix this?  If any additional information is needed, just say so, and I'll post.  Thanks.

答:
The project property changes you've made to get it to build in the Debug configuration are not automatically applied to the Release configuration as well.  Note the "Configuration" combo in the upper left corner of the dialog.  Altered property values are shown in bold type.

If you cannot remember what changes you've made then open the .vcproj file in a text editor like Notepad.exe.  The settings that were changed from their default value are listed in the Debug|Win32 configuration section.

Body:
I'm having a little trouble building my application as Release in Visual Studio 2008.  It builds fine without any errors or warning as Debug.  The application is primarily Win32 with a little MFC and ATL mixed in here and there.  Most of the projects in the solution generate a LIB and DLL.

This is one of the errors I am getting:

fatal error C1189: #error :  Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]

My application is a multithreaded DLL, so the /MD needs to stay.  The only Windows includes are these:

#include "stdafx.h"
#include "afx.h"
#include "WMIQuery.h"
#include "SerialPort.h"

The other error is this:

fatal error C1083: Cannot open include file: 'WMIQuery.h': No such file or directory

This one really doesn't make sense to me because, the environment has no problem finding this file building for Debug.

Does anyone know how to fix this?  If any additional information is needed, just say so, and I'll post.  Thanks.


问:
provide s3fs mount to docker as volume
I´d Like to use a mounted S3 Bucket (using s3fs) as a volume within a docker container.

I have:
a mounted S3 Bucket (with s3fs) at /mnt/bucketname on my ec2 Machine
using:

```<code>sudo /usr/bin/s3fs -o allow_other,uid=500,umask=227,gid=500 bucketname /mnt/bucketname
</code>```

and can read all files/folders in /mnt/bucketname.

This is the command i use to run my Docker Image (with interactive terminal):

```<code>sudo docker run -v /mnt/bucketname:/test -it Imagename /bin/bash
</code>```

Within the Docker Container, the files (which should appear in /test/) are not present.

What might be the problem here?

Did someone use a s3fs mount and provide it to docker as a volume before or is this entirely the wrong way to do it?

Thanks for any answers.

答:
Sorry for Self-Answering - but i solved the problem by restarting the docker service:

```<code>sudo service docker stop
sudo service docker start
</code>```

and voila: the s3fs volume is accessible.

best

Flo

Title: provide s3fs mount to docker as volume

Body:
I´d Like to use a mounted S3 Bucket (using s3fs) as a volume within a docker container.

I have:
a mounted S3 Bucket (with s3fs) at /mnt/bucketname on my ec2 Machine
using:

sudo /usr/bin/s3fs -o allow_other,uid=500,umask=227,gid=500 bucketname /mnt/bucketname

and can read all files/folders in /mnt/bucketname.

This is the command i use to run my Docker Image (with interactive terminal):

sudo docker run -v /mnt/bucketname:/test -it Imagename /bin/bash

Within the Docker Container, the files (which should appear in /test/) are not present.

What might be the problem here?

Did someone use a s3fs mount and provide it to docker as a volume before or is this entirely the wrong way to do it?

Thanks for any answers.

Body:
Sorry for Self-Answering - but i solved the problem by restarting the docker service:

sudo service docker stop
sudo service docker start

and voila: the s3fs volume is accessible.

best

Flo


问:
C warning with char array: "warning: array subscript has type 'char'"
I am confused as to why this error occurs.
My code execute fine and the results is exactly what I want but on compiling my c file with the command:
"gcc -std=c99 -Wall -o assignment2 assignment2.c"

Here is the code:

Here is the output error:

I would just use this but i'm sure it might have some reasons why an error shows and also because my assignment marker probably want accept it if there is this warning on compilation.

答: i should be evaluated so that i < 500 is fullfilled


问:
What is the best way to clean the cache without running the console command?
In the admin panel of my project, I programmed the ability to change the database name to use. I wrote the new database name in the parameters.ini, and after that the cache had to be cleaned to load the new config.

What is the best way to clean the cache without running the console command?

Or is there another best practise how to change the current db.

答:
@HelpNeeder's answer is good but the ClearCache command is not using the --env option given. It is instead using the current kernel the application is running on.

So for it to work with another environnement than the environnement you call the controller from, you need to tweak the code a bit (I can't edit his answer, it's saying the edit queue is full) so here is a more complete answer:

```<code>//YourBundle:YourController

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Output\BufferedOutput;

public function clearCacheAction($env = 'dev', $debug = true)
{
    $kernel = new \AppKernel($env, $debug);

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput([
        'command' => 'cache:clear'
    ]);

    $output = new BufferedOutput();
    $application->run($input, $output);

    return $this->render('someTwigTemplateHere', array('output' => $output->fetch()));
}
</code>```

Then you configure the routes :

```<code>cache_clear_dev:
    path:     /_cache/clear/dev
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'dev', debug: true }

cache_clear_prod:
    path:     /_cache/clear/prod
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'prod', debug: false }
</code>```

And you can now output the result of the command using {{ output }} in your twig template.

If you have an access control, don't forget to set the permission for this route to a SUPER_ADMIN or something, you wouldn't want anyone other than an admin able to clear the cache.

Body:
@HelpNeeder's answer is good but the ClearCache command is not using the --env option given. It is instead using the current kernel the application is running on.

So for it to work with another environnement than the environnement you call the controller from, you need to tweak the code a bit (I can't edit his answer, it's saying the edit queue is full) so here is a more complete answer:

//YourBundle:YourController

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Output\BufferedOutput;

public function clearCacheAction($env = 'dev', $debug = true)
{
    $kernel = new \AppKernel($env, $debug);

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $input = new ArrayInput([
        'command' => 'cache:clear'
    ]);

    $output = new BufferedOutput();
    $application->run($input, $output);

    return $this->render('someTwigTemplateHere', array('output' => $output->fetch()));
}

Then you configure the routes :

cache_clear_dev:
    path:     /_cache/clear/dev
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'dev', debug: true }

cache_clear_prod:
    path:     /_cache/clear/prod
    defaults: { _controller: YourBundle:YourController:clearCache, env: 'prod', debug: false }

And you can now output the result of the command using {{ output }} in your twig template.

If you have an access control, don't forget to set the permission for this route to a SUPER_ADMIN or something, you wouldn't want anyone other than an admin able to clear the cache.


问:
How to use BindableProperty.Create in Xamarin.Forms?
In xaml in Xamarin.Forms, I have a custom control, I want to add property of type int. I think I have to use Bindable properties, so later I can bind a property from ViewModel.

I found this topic, but I'm not sure how to use it.. there is:

```<code>BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);
</code>```

what's "BindablePicker"? Is it the view where property is declared?

Here's my try:

```<code>    public int WedgeRating
    {
        get
        {
            return (int)GetValue(WedgeRatingProperty);
        }
        set
        {
            try
            {
                SetValue(WedgeRatingProperty, value);
            }
            catch (ArgumentException ex)
            {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }
        }
    }

    public static readonly BindableProperty WedgeRatingProperty =
       BindableProperty.Create(nameof(WedgeRating), typeof(int), typeof(GameCocosSharpView), null, propertyChanged: OnItemsSourcePropertyChanged);

    private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
    }
</code>```

I didn't even use it in xaml, and it already doesn't work. No particular exception. Only the page where the custom control is initialized doesn't loead. When I comment line I pasted here, it works.

答:
Here is the example for Bindable Property</p>

```<code>public class GameCocosSharpView : View
    {
       public int WedgeRating
        {
            get { return (int)GetValue(WedgeRatingProperty); }
            set { SetValue(WedgeRatingProperty, value); }
        }
        public static void WedgeRatingChanged(BindableObject bindable, object oldValue, object newValue)
        {

        }
        public static readonly BindableProperty WedgeRatingProperty =
            BindableProperty.Create("WedgeRating", typeof(int), typeof(GameCocosSharpView), 1, BindingMode.Default, null, WedgeRatingChanged);

    }
</code>```

Body:
In xaml in Xamarin.Forms, I have a custom control, I want to add property of type int. I think I have to use Bindable properties, so later I can bind a property from ViewModel.

I found this topic, but I'm not sure how to use it.. there is:

BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);

what's "BindablePicker"? Is it the view where property is declared?

Here's my try:

    public int WedgeRating
    {
        get
        {
            return (int)GetValue(WedgeRatingProperty);
        }
        set
        {
            try
            {
                SetValue(WedgeRatingProperty, value);
            }
            catch (ArgumentException ex)
            {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }
        }
    }

    public static readonly BindableProperty WedgeRatingProperty =
       BindableProperty.Create(nameof(WedgeRating), typeof(int), typeof(GameCocosSharpView), null, propertyChanged: OnItemsSourcePropertyChanged);

    private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
    }

I didn't even use it in xaml, and it already doesn't work. No particular exception. Only the page where the custom control is initialized doesn't loead. When I comment line I pasted here, it works.

Body:
Here is the example for Bindable Property

public class GameCocosSharpView : View
    {
       public int WedgeRating
        {
            get { return (int)GetValue(WedgeRatingProperty); }
            set { SetValue(WedgeRatingProperty, value); }
        }
        public static void WedgeRatingChanged(BindableObject bindable, object oldValue, object newValue)
        {

        }
        public static readonly BindableProperty WedgeRatingProperty =
            BindableProperty.Create("WedgeRating", typeof(int), typeof(GameCocosSharpView), 1, BindingMode.Default, null, WedgeRatingChanged);

    }


问:
Binding DataTemplate controls in DataGridTemplateColumn
I have bounded DataGrid where Items are ObservableCollection of pairs {Prop1, Prop2}

```<code><DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
                   <DataGrid.Columns>
                        <DataGridTemplateColumn>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBox >
                                        <TextBox.Text>
                                            <Binding Path="Prop1">
                                            </Binding>
                                        </TextBox.Text>
                                    </TextBox>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
</code>```

How to bind TextBox Text property to Prop1? I tried as shown above but its not working (looks like data context of TextBox is set to main window).

答:
I've managed to reproduce the issue in question (I assume that "it's not working" means that the value entered in the TextBox is not pushed to your view-model). I am not sure about the exact reasons, but it seems that in this particular scenario, if you don't explicitly set Binding.UpdateSourceTrigger, it defaults (or at least acts like it) to UpdateSourceTrigger.Explicit. So the solution to this problem is to explicitly set the UpdateSourceTrigger on the binding to either UpdateSourceTrigger.LostFocus or UpdateSourceTrigger.PropertyChanged:

```<code><DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Prop1, UpdateSourceTrigger=LostFocus}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I have bounded DataGrid where Items are ObservableCollection of pairs {Prop1, Prop2}

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
                   <DataGrid.Columns>
                        <DataGridTemplateColumn>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBox >
                                        <TextBox.Text>
                                            <Binding Path="Prop1">
                                            </Binding>
                                        </TextBox.Text>
                                    </TextBox>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

How to bind TextBox Text property to Prop1? I tried as shown above but its not working (looks like data context of TextBox is set to main window).

Body:
I've managed to reproduce the issue in question (I assume that "it's not working" means that the value entered in the TextBox is not pushed to your view-model). I am not sure about the exact reasons, but it seems that in this particular scenario, if you don't explicitly set Binding.UpdateSourceTrigger, it defaults (or at least acts like it) to UpdateSourceTrigger.Explicit. So the solution to this problem is to explicitly set the UpdateSourceTrigger on the binding to either UpdateSourceTrigger.LostFocus or UpdateSourceTrigger.PropertyChanged:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Prop1, UpdateSourceTrigger=LostFocus}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>


问:
Access export file Missing wizzard
Access 2010  - Export query to text or Excel.
 Missing wizard.
 One of my Access apps has a window with buttons with VBA Do.
Cmd to export queries to Text or Excel which works.
 I have created a new App using the same database from scratch and imported the window.
Now I get the error

"Specification does not exist"

Previously I just ran the export manually and a wizard appeared to allow me to save the specification.

Now when exporting manually no wizard appears.
I have researched and only found a suggestion that the accwiz.dll is required.
 Microsoft do not have it available for download. Any ideas?

答:
While importing the objects to the new database, click "Options" and select Import/Export Specs (3rd option).

The export specification will then be available.

Title: Access export file Missing wizzard


问:
Angular 4 templateUrl file not found
I am using Angular 4.1.3 with Rails 5.1

I am trying to implement the app component and if I use template and write my html, everything works, but I want to use templateUrl.

Here is my component.

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})
export class AppComponent {}
</code>```

And this is my file structure

```<code>├── app
|   ├── app.component.html
|   └── app.component.ts
|   └── app.module.ts
</code>```

I understand that in the @Component you can add moduleId: module.id but I thought this is no longer needed in angular 4.1.3.

If I do add it, it tells me:
moduleId should be a string in "AppComponent"

I also thought that if you do not include the moduleId angular just grabs from root directory, but if I do an absolute path, it should work right?

If you guys could help, that would be awesome.

答:
If you would like to keep templateUrl you could use angular2-template-loader webpack plugin:

```<code># add plugins to project
yarn add angular2-template-loader raw-loader
</code>```

and configure it:

```<code># edit config/webpack/loaders/angular.js with
module.exports = {
    test: /.ts$/,
    loaders: ['ts-loader', 'angular2-template-loader'],
    exclude: [/\.(spec|e2e)\.ts$/]
}

# create a new loader for htmls config/webpack/loaders/html.js
module.exports = {
    test: /\.(html)$/,
    loader: 'raw-loader',
    exclude: /\.async\.(html)$/
}
</code>```

Title: Angular 4 templateUrl file not found

Body:
I am using Angular 4.1.3 with Rails 5.1

I am trying to implement the app component and if I use template and write my html, everything works, but I want to use templateUrl.

Here is my component.

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})
export class AppComponent {}

And this is my file structure

├── app
|   ├── app.component.html
|   └── app.component.ts
|   └── app.module.ts

I understand that in the @Component you can add moduleId: module.id but I thought this is no longer needed in angular 4.1.3.

If I do add it, it tells me:
moduleId should be a string in "AppComponent"

I also thought that if you do not include the moduleId angular just grabs from root directory, but if I do an absolute path, it should work right?

If you guys could help, that would be awesome.

Body:
If you would like to keep templateUrl you could use angular2-template-loader webpack plugin:

# add plugins to project
yarn add angular2-template-loader raw-loader

and configure it:

# edit config/webpack/loaders/angular.js with
module.exports = {
    test: /.ts$/,
    loaders: ['ts-loader', 'angular2-template-loader'],
    exclude: [/\.(spec|e2e)\.ts$/]
}

# create a new loader for htmls config/webpack/loaders/html.js
module.exports = {
    test: /\.(html)$/,
    loader: 'raw-loader',
    exclude: /\.async\.(html)$/
}


问:
Composer install with only composer.lock
I freshly installed a PHP application given with a composer.lock file.

When running composer install, command line tool is still asking for a composer.json.... I don't have.

In composer documentation, it's said that install command first look for a composer.lock and then for a composer.json.

Why composer is still asking for a file it doesn't need to install my dependencies ?

composer install > returns :
Composer could not find a composer.json file

答:
You still need the composer.json file to install or update any dependencies.
Having a composer.lock file means that composer will not search for the latest commits of the dependencies

A few weeks ago on Twitter, I noticed that the OpenCFP project doesn’t have a composer.lock file in it’s repository. “So what,” you might say, “just composer install and away you go. You’ll get the same dependencies, right?”
  Wrong.

The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.

Source: Composer: It's all about Lock File


问:
why data is not inserting to database?
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

```<code><html>
<head>
    <title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
    <table border="2px" width="500px">
        <tr>
            <th colspan="2" align="center">create menu</th>
        </tr>
        <tr>
            <td align="right">menu name</td>
            <td><input type="text" name="menu"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
        </tr>
    </table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "<h1 align='center'>DATA INSERTED</h1>";
    }
    else{
        echo "<h1>data not inserted</h1>";
    }
}
?>
</code>```

where am i wrong please help data is not inserting to database

答:
First thing which version of php you are using, because mysql_connect() is not supported in newer version of php.
If your php version doesn't support this function you should get error on submit.

so i suggest you to replace mysql_xxx with mysqli_xxx (as you can see here mysql_connect)

replace these 2  lines

```<code>mysql_connect("localhost","root","");
mysql_select_db("coupons");
</code>```

with these lines of code

```<code>$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");
</code>```

And

update if condition with this mysqli_xxx() as

```<code>if(mysqli_query($query))
</code>```

For more detail please read mysqli_connect

Title: why data is not inserting to database?

Body:
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

    <title>create menu</title>

create menu

Dont create more than 7 menu

<form method="post">

            create menu

            menu name
            <input type="text" name="menu">

            <input type="submit" name="submit" value="create">

</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "
DATA INSERTED
";
    }
    else{
        echo "
data not inserted
";
    }
}
?>

where am i wrong please help data is not inserting to database

Body:
First thing which version of php you are using, because mysql_connect() is not supported in newer version of php.
If your php version doesn't support this function you should get error on submit.

so i suggest you to replace mysql_xxx with mysqli_xxx (as you can see here mysql_connect)

replace these 2  lines

mysql_connect("localhost","root","");
mysql_select_db("coupons");

with these lines of code

$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");

And

update if condition with this mysqli_xxx() as

if(mysqli_query($query))

For more detail please read mysqli_connect


问:
Multiple Files download with urlStream + fileStream
Using Flash Builder 4 (with 4.1 flex) and found/modified a script that works with a single file without prompting.  Now I need to modify it to download and save more than one file.

The originator of the code said to introduce an array, but don't know exactly how to.
Ideally you push the button once and it initiates the function and then the function reads the array and runs through the commands with the variables defined from the first result of the array, then changes to next.

The values would only change on the name of the files not on the location, locally or remotely.

I know how to do this in php but not flex.  Anyone able to complete this?

```<code><s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="200"
                   title="Updater"
                   showStatusBar="false">
<fx:Style source="Main.css"/>
<fx:Script>
    <![CDATA[

        protected function download_clickHandler(event:MouseEvent):void
        {
            var remoteFile = "http://domain/01.jpg";
            var localFile = "C:/01.jpg";

            var urlStream = new URLStream();
            var request = new URLRequest(remoteFile);

            var fileStream = new FileStream();

            var file = File.desktopDirectory.resolvePath(localFile);

            var writeFile = function()
            {
                // Write to file
                if (urlStream.bytesAvailable > 51200)
                {
                    var dataBuffer = new ByteArray();
                    urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                    fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                }
                return true;
            }

            var finishWriteFile = function()
            {
                if(urlStream.bytesAvailable > 0)
                {
                    var dataBuffer = new ByteArray();
                    urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                    fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                }

                fileStream.close();
                urlStream.close();

                return true;
            }

            fileStream.openAsync(file, FileMode.WRITE);
            urlStream.load(request);

            urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
            urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
        }
    ]]>
</fx:Script>

<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" label="Update" id="download" click="download_clickHandler(event)" color="#FFFFFF" fontSize="30"/></s:WindowedApplication>
</code>```

Thanks for any input!

答:
This is what I have now, and it works.  Anyone see any issues with how it is done?</p>

```<code><s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="200"
                       title=" Updater"
                       showStatusBar="false">
    <fx:Style source="Main.css"/>
    <fx:Script>
        <![CDATA[

        private function download_clickHandler(event:MouseEvent):void
        {
            var filearray:Array = new Array();
            filearray[0]="pregame.jpg";
            filearray[1]="01.jpg";
            filearray[2]="02.jpg";
            filearray[3]="03.jpg";
            filearray[4]="04.jpg";
            filearray[5]="05.jpg";
            filearray[6]="06.jpg";
            filearray[7]="07.jpg";
            filearray[8]="08.jpg";
            filearray[9]="09.jpg";
            filearray[10]="10.jpg";
            for (var i:uint; i < filearray.length; i++) {
                var remoteURL = "http://www.domain.com/" + filearray[i];
                var localURL = "C:/dir/" + filearray[i];
                downloadFile(remoteURL, localURL);
            }

            function downloadFile(url, fileName) {
                // Create the stream for the data request
                var urlStream = new URLStream();

                // Used to initiate request for remote file
                var request = new URLRequest(url);

                // Create file stream
                var fileStream = new FileStream();

                // Create a reference to a location on disk
                var file = File.desktopDirectory.resolvePath(fileName);

                // Called as download progresses
                var writeFile = function()
                {
                    // Write to file
                    if (urlStream.bytesAvailable > 51200)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }
                    return true;
                }

                // Called when download completes
                var finishWriteFile = function()
                {
                    // Write to file
                    if(urlStream.bytesAvailable > 0)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }

                    // Close streams
                    fileStream.close();
                    urlStream.close();

                    return true;
                }

                // Initiate download
                fileStream.openAsync(file, FileMode.WRITE);
                urlStream.load(request);

                // Add event listeners
                urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
                urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
        }
    ]]>
</fx:Script>

<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" label="Update" id="download" click="download_clickHandler(event)" color="#FFFFFF" fontSize="30"/>
</code>```

Body:
Using Flash Builder 4 (with 4.1 flex) and found/modified a script that works with a single file without prompting.  Now I need to modify it to download and save more than one file.

The originator of the code said to introduce an array, but don't know exactly how to.
Ideally you push the button once and it initiates the function and then the function reads the array and runs through the commands with the variables defined from the first result of the array, then changes to next.

The values would only change on the name of the files not on the location, locally or remotely.

I know how to do this in php but not flex.  Anyone able to complete this?

<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="200"
                   title="Updater"
                   showStatusBar="false">
<fx:Style source="Main.css"/>
<fx:Script>
    <![CDATA[

        protected function download_clickHandler(event:MouseEvent):void
        {
            var remoteFile = "http://domain/01.jpg";
            var localFile = "C:/01.jpg";

            var urlStream = new URLStream();
            var request = new URLRequest(remoteFile);

            var fileStream = new FileStream();

            var file = File.desktopDirectory.resolvePath(localFile);

            var writeFile = function()
            {
                // Write to file
                if (urlStream.bytesAvailable > 51200)
                {
                    var dataBuffer = new ByteArray();
                    urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                    fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                }
                return true;
            }

            var finishWriteFile = function()
            {
                if(urlStream.bytesAvailable > 0)
                {
                    var dataBuffer = new ByteArray();
                    urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                    fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                }

                fileStream.close();
                urlStream.close();

                return true;
            }

            fileStream.openAsync(file, FileMode.WRITE);
            urlStream.load(request);

            urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
            urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
        }
    ]]>
</fx:Script>

<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" label="Update" id="download" click="download_clickHandler(event)" color="#FFFFFF" fontSize="30"/></s:WindowedApplication>

Thanks for any input!

Body:
This is what I have now, and it works.  Anyone see any issues with how it is done?

<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="200"
                       title=" Updater"
                       showStatusBar="false">
    <fx:Style source="Main.css"/>
    <fx:Script>
        <![CDATA[

        private function download_clickHandler(event:MouseEvent):void
        {
            var filearray:Array = new Array();
            filearray[0]="pregame.jpg";
            filearray[1]="01.jpg";
            filearray[2]="02.jpg";
            filearray[3]="03.jpg";
            filearray[4]="04.jpg";
            filearray[5]="05.jpg";
            filearray[6]="06.jpg";
            filearray[7]="07.jpg";
            filearray[8]="08.jpg";
            filearray[9]="09.jpg";
            filearray[10]="10.jpg";
            for (var i:uint; i < filearray.length; i++) {
                var remoteURL = "http://www.domain.com/" + filearray[i];
                var localURL = "C:/dir/" + filearray[i];
                downloadFile(remoteURL, localURL);
            }

            function downloadFile(url, fileName) {
                // Create the stream for the data request
                var urlStream = new URLStream();

                // Used to initiate request for remote file
                var request = new URLRequest(url);

                // Create file stream
                var fileStream = new FileStream();

                // Create a reference to a location on disk
                var file = File.desktopDirectory.resolvePath(fileName);

                // Called as download progresses
                var writeFile = function()
                {
                    // Write to file
                    if (urlStream.bytesAvailable > 51200)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }
                    return true;
                }

                // Called when download completes
                var finishWriteFile = function()
                {
                    // Write to file
                    if(urlStream.bytesAvailable > 0)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }

                    // Close streams
                    fileStream.close();
                    urlStream.close();

                    return true;
                }

                // Initiate download
                fileStream.openAsync(file, FileMode.WRITE);
                urlStream.load(request);

                // Add event listeners
                urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
                urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
        }
    ]]>
</fx:Script>

<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" label="Update" id="download" click="download_clickHandler(event)" color="#FFFFFF" fontSize="30"/>


答:
You must have a composer.json to install dependencies, because it's the file where dependencies theirself are listed. Refer to the documentation.

composer.lock lists dependencies which has already been installed. The composer looks first into it in order to keep versions consistent.

The (documentation states)[https://getcomposer.org/doc/01-basic-usage.md#installing-with-composer-lock]:

running install when a composer.lock file is present resolves and installs all dependencies that you listed in composer.json, but Composer uses the exact versions listed in composer.lock to ensure that the package versions are consistent for everyone working on your project.

If you have lost your composer.json you can reverse engineering your composer.lock. Open it and read all the packages installed, then create a composer.json which requires them. Not every single package will be a direct dependency for your problem: you should identify and remove those which are not.

Title: Composer install with only composer.lock

Body:
I freshly installed a PHP application given with a composer.lock file.

When running composer install, command line tool is still asking for a composer.json.... I don't have.

In composer documentation, it's said that install command first look for a composer.lock and then for a composer.json.

Why composer is still asking for a file it doesn't need to install my dependencies ?

composer install > returns :
Composer could not find a composer.json file


问:
magento installation error - reset.php is missing
Any idea about the below error

Fatal error: require_once(): Failed opening required '/home/inhyshoper/public_html/app/design/frontend/default/default/etc/reset.php' (include_path='/home/inhyshoper/public_html/includes/src:.:/usr/lib/php:/usr/local/lib/php') in /public_html/includes/src/EM_Themeframework_Model_Observer.php on line 287

答:
Its looks like permission issue. put 777 permission to your theme folder, it may works.
Please let me know if not work.</p>


问:
Cursor returns null when getting filepath from URI
```<code>Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();
</code>```

cursor.getString(columnIndex) Returns Null
Where as the selectedImage is not null.

Any suggestion on how I can create file from URI?

答:
Use this method to get path:

```<code>public String getPath(Uri uri) {
    // just some safety built in
    if (uri == null) {
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}
</code>```

And in onACtivityResult use this:

```<code>Uri selectedImage = data.getData();
</code>```

Body:
Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

cursor.getString(columnIndex) Returns Null
Where as the selectedImage is not null.

Any suggestion on how I can create file from URI?

Body:
Use this method to get path:

public String getPath(Uri uri) {
    // just some safety built in
    if (uri == null) {
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}

And in onACtivityResult use this:

Uri selectedImage = data.getData();


问:
Extract $item code from array in k2store
I try to extract and to show on the page with echo product code field in K2store cart page (store extension for K2 for Joomla) but without success. The right value is "product_code" or "code" (is the same value): 26910.

Both "echo $item->product_name" and "echo $item->product_id" works, but "echo $item->code" and "echo $item->product_code" return NULL.

var_dump($item) show me this:

```<code>object(stdClass)#381 (13) {
  ["key"]=>
  int(9928417)
  ["product_id"]=>
  string(7) "9928417"
  ["product_name"]=>
  string(71) "some title"
  ["product_model"]=>
  NULL
  ["product_total"]=>
  int(1)
  ["product_options"]=>
  object(stdClass)#382 (0) {
  }
  ["quantity"]=>
  int(1)
  ["stock"]=>
  object(JObject)#378 (18) {
    ["_errors":protected]=>
    array(0) {
    }
    ["item_enabled"]=>
    string(1) "1"
    ["item_sku"]=>
    NULL
    ["item_price"]=>
    NULL
    ["special_price"]=>
    NULL
    ["item_tax_id"]=>
    NULL
    ["item_shipping"]=>
    NULL
    ["item_qty"]=>
    NULL
    ["item_cart_text"]=>
    NULL
    ["product_id"]=>
    string(7) "9928417"
    ["product_name"]=>
    string(71) "some title"
    ["product_code"]=>
    string(5) "26910"
    ["price"]=>
    NULL
    ["product_sku"]=>
    NULL
    ["tax_profile_id"]=>
    NULL
    ["item_minimum"]=>
    string(1) "1"
    ["stock"]=>
    *RECURSION*
    ["product"]=>
    object(stdClass)#354 (38) {
      ["id"]=>
      string(7) "9928417"
      ["code"]=>
      string(5) "26910"
      ["title"]=>
      string(71) "some title"
      ["alias"]=>
      string(71) "some title"
      ["catid"]=>
      string(3) "694"
      ["published"]=>
      string(1) "1"
      ["introtext"]=>
      string(0) ""
      ["fulltext"]=>
      string(0) ""
      ["video"]=>
      NULL
      ["gallery"]=>
      NULL
      ["extra_fields"]=>
      string(29) "[{"id":"1","value":"25\/40"}]"
      ["extra_fields_search"]=>
      string(6) "25/40 "
      ["created"]=>
      string(19) "2012-09-14 10:20:09"
      ["created_by"]=>
      string(2) "52"
      ["created_by_alias"]=>
      string(0) ""
      ["checked_out"]=>
      string(1) "0"
      ["checked_out_time"]=>
      string(19) "0000-00-00 00:00:00"
      ["modified"]=>
      string(19) "2012-09-14 10:30:46"
      ["modified_by"]=>
      string(2) "52"
      ["publish_up"]=>
      string(19) "2012-09-14 10:20:09"
      ["publish_down"]=>
      string(19) "0000-00-00 00:00:00"
      ["trash"]=>
      string(1) "0"
      ["access"]=>
      string(1) "1"
      ["ordering"]=>
      string(1) "1"
      ["featured"]=>
      string(1) "0"
      ["featured_ordering"]=>
      string(1) "0"
      ["image_caption"]=>
      string(0) ""
      ["image_credits"]=>
      string(0) ""
      ["video_caption"]=>
      string(0) ""
      ["video_credits"]=>
      string(0) ""
      ["hits"]=>
      string(5) "17852"
      ["params"]=>
      string(1190) "catItemTitle=
catItemTitleLinked=
catItemFeaturedNotice=
catItemAuthor=
catItemDateCreated=
catItemRating=
catItemImage=
catItemIntroText=
catItemExtraFields=
catItemHits=
catItemCategory=
catItemTags=
catItemAttachments=
catItemAttachmentsCounter=
catItemVideo=
catItemVideoWidth=
catItemVideoHeight=
catItemVideoAutoPlay=
catItemImageGallery=
catItemDateModified=
catItemReadMore=
catItemCommentsAnchor=
catItemK2Plugins=
itemDateCreated=
itemTitle=
itemFeaturedNotice=
itemAuthor=
itemFontResizer=
itemPrintButton=
itemEmailButton=
itemSocialButton=
itemVideoAnchor=
itemImageGalleryAnchor=
itemCommentsAnchor=
itemRating=
itemImage=
itemImgSize=
itemImageMainCaption=
itemImageMainCredits=
itemIntroText=
itemFullText=
itemExtraFields=
itemDateModified=
itemHits=
itemTwitterLink=
itemCategory=
itemTags=
itemShareLinks=
itemAttachments=
itemAttachmentsCounter=
itemRelated=
itemRelatedLimit=
itemVideo=
itemVideoWidth=
itemVideoHeight=
itemVideoAutoPlay=
itemVideoCaption=
itemVideoCredits=
itemImageGallery=
itemNavigation=
itemComments=
itemAuthorBlock=
itemAuthorImage=
itemAuthorDescription=
itemAuthorURL=
itemAuthorEmail=
itemAuthorLatest=
itemAuthorLatestLimit=
itemK2Plugins=

"
      ["metadesc"]=>
      string(0) ""
      ["metadata"]=>
      string(15) "robots=
author="
      ["metakey"]=>
      string(0) ""
      ["plugins"]=>
      string(27) "{"k2storeitem_enabled":"1"}"
      ["code_search"]=>
      string(0) ""
      ["language"]=>
      string(0) ""
    }
  }
  ["tax_amount"]=>
  int(0)
  ["price"]=>
  int(0)
  ["price_without_tax"]=>
  int(0)
  ["total"]=>
  int(0)
  ["total_without_tax"]=>
  int(0)
}
</code>```

答: The solution is: $item->stock->product_code

Body:
I try to extract and to show on the page with echo product code field in K2store cart page (store extension for K2 for Joomla) but without success. The right value is "product_code" or "code" (is the same value): 26910.

Both "echo $item->product_name" and "echo $item->product_id" works, but "echo $item->code" and "echo $item->product_code" return NULL.

var_dump($item) show me this:

object(stdClass)#381 (13) {
  ["key"]=>
  int(9928417)
  ["product_id"]=>
  string(7) "9928417"
  ["product_name"]=>
  string(71) "some title"
  ["product_model"]=>
  NULL
  ["product_total"]=>
  int(1)
  ["product_options"]=>
  object(stdClass)#382 (0) {
  }
  ["quantity"]=>
  int(1)
  ["stock"]=>
  object(JObject)#378 (18) {
    ["_errors":protected]=>
    array(0) {
    }
    ["item_enabled"]=>
    string(1) "1"
    ["item_sku"]=>
    NULL
    ["item_price"]=>
    NULL
    ["special_price"]=>
    NULL
    ["item_tax_id"]=>
    NULL
    ["item_shipping"]=>
    NULL
    ["item_qty"]=>
    NULL
    ["item_cart_text"]=>
    NULL
    ["product_id"]=>
    string(7) "9928417"
    ["product_name"]=>
    string(71) "some title"
    ["product_code"]=>
    string(5) "26910"
    ["price"]=>
    NULL
    ["product_sku"]=>
    NULL
    ["tax_profile_id"]=>
    NULL
    ["item_minimum"]=>
    string(1) "1"
    ["stock"]=>
    *RECURSION*
    ["product"]=>
    object(stdClass)#354 (38) {
      ["id"]=>
      string(7) "9928417"
      ["code"]=>
      string(5) "26910"
      ["title"]=>
      string(71) "some title"
      ["alias"]=>
      string(71) "some title"
      ["catid"]=>
      string(3) "694"
      ["published"]=>
      string(1) "1"
      ["introtext"]=>
      string(0) ""
      ["fulltext"]=>
      string(0) ""
      ["video"]=>
      NULL
      ["gallery"]=>
      NULL
      ["extra_fields"]=>
      string(29) "[{"id":"1","value":"25\/40"}]"
      ["extra_fields_search"]=>
      string(6) "25/40 "
      ["created"]=>
      string(19) "2012-09-14 10:20:09"
      ["created_by"]=>
      string(2) "52"
      ["created_by_alias"]=>
      string(0) ""
      ["checked_out"]=>
      string(1) "0"
      ["checked_out_time"]=>
      string(19) "0000-00-00 00:00:00"
      ["modified"]=>
      string(19) "2012-09-14 10:30:46"
      ["modified_by"]=>
      string(2) "52"
      ["publish_up"]=>
      string(19) "2012-09-14 10:20:09"
      ["publish_down"]=>
      string(19) "0000-00-00 00:00:00"
      ["trash"]=>
      string(1) "0"
      ["access"]=>
      string(1) "1"
      ["ordering"]=>
      string(1) "1"
      ["featured"]=>
      string(1) "0"
      ["featured_ordering"]=>
      string(1) "0"
      ["image_caption"]=>
      string(0) ""
      ["image_credits"]=>
      string(0) ""
      ["video_caption"]=>
      string(0) ""
      ["video_credits"]=>
      string(0) ""
      ["hits"]=>
      string(5) "17852"
      ["params"]=>
      string(1190) "catItemTitle=
catItemTitleLinked=
catItemFeaturedNotice=
catItemAuthor=
catItemDateCreated=
catItemRating=
catItemImage=
catItemIntroText=
catItemExtraFields=
catItemHits=
catItemCategory=
catItemTags=
catItemAttachments=
catItemAttachmentsCounter=
catItemVideo=
catItemVideoWidth=
catItemVideoHeight=
catItemVideoAutoPlay=
catItemImageGallery=
catItemDateModified=
catItemReadMore=
catItemCommentsAnchor=
catItemK2Plugins=
itemDateCreated=
itemTitle=
itemFeaturedNotice=
itemAuthor=
itemFontResizer=
itemPrintButton=
itemEmailButton=
itemSocialButton=
itemVideoAnchor=
itemImageGalleryAnchor=
itemCommentsAnchor=
itemRating=
itemImage=
itemImgSize=
itemImageMainCaption=
itemImageMainCredits=
itemIntroText=
itemFullText=
itemExtraFields=
itemDateModified=
itemHits=
itemTwitterLink=
itemCategory=
itemTags=
itemShareLinks=
itemAttachments=
itemAttachmentsCounter=
itemRelated=
itemRelatedLimit=
itemVideo=
itemVideoWidth=
itemVideoHeight=
itemVideoAutoPlay=
itemVideoCaption=
itemVideoCredits=
itemImageGallery=
itemNavigation=
itemComments=
itemAuthorBlock=
itemAuthorImage=
itemAuthorDescription=
itemAuthorURL=
itemAuthorEmail=
itemAuthorLatest=
itemAuthorLatestLimit=
itemK2Plugins=

"
      ["metadesc"]=>
      string(0) ""
      ["metadata"]=>
      string(15) "robots=
author="
      ["metakey"]=>
      string(0) ""
      ["plugins"]=>
      string(27) "{"k2storeitem_enabled":"1"}"
      ["code_search"]=>
      string(0) ""
      ["language"]=>
      string(0) ""
    }
  }
  ["tax_amount"]=>
  int(0)
  ["price"]=>
  int(0)
  ["price_without_tax"]=>
  int(0)
  ["total"]=>
  int(0)
  ["total_without_tax"]=>
  int(0)
}


问:
Error when using read.gml or read.graph to read a GML file
I am trying to load a file from the spanish building census (any of the files there will serve as an example, I'm using the 03001-ADSUBIA buildings one).

I have tried the read.gml function from the Multiplex package and get the following error:
read.gml("A.ES.SDGC.BU.03001.building.gml")
Error in which(("node" == arx) == TRUE)[1]:which(("edge" == arx) == TRUE)[1] :
  NA/NaN argument

Then I tried the read.graph from the igraph package and also got an error:
read.graph("A.ES.SDGC.BU.46900.building.gml", format=c("gml"))
Error in .Call("R_igraph_read_graph_gml", file, PACKAGE = "igraph") :
  At foreign.c:1127 : Parse error in GML file, line 1 (syntax error, unexpected STRING, expecting $end), Parse error

What am I doing wrong, and what can I do to fix it?

答: igraph and multiplex do not work because that is a different GML: Graph Modelling Language, as the name suggests, is for graphs (or networks). Your GML is Geography Markup Language.


问:
Spring boot: how to match all routes?
I'm developing a simple web application on Spring boot 1.5.3 and I need all the routes to send static index.html file. Now, I have this:

```<code>@Controller
public class IndexController {

    @RequestMapping("/*")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}
</code>```

My application contains only static assets and REST API. But the problem is that the controller shown above only matches the first-level url like /index, /department etc. I want to match all url levels like /index/some/other/staff etc. How can I do that?

PS. I've tried to use the template /** in @RequestMapping, but my application has broken with the StackOverflow error.

UPDATE

If add one more level to url, then all will work as expected:

```<code>@Controller
public class IndexController {

    @RequestMapping("/test/**")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}
</code>```

All requests to /test, /test/some/other/staff will return index.html, but I need to start with /.

答:
You can try this:</p>
```<code>@Controller
public class IndexController {

@RequestMapping(value = "/**/{path:[^\\.]*}")
public String index(final HttpServletRequest request) {
    final String url = request.getRequestURI();

    if (url.startsWith("/static")) {
        return String.format("forward:/%s", url);
    }

    return "forward:/static/index.html";
}
}
</code>```

Title: Spring boot: how to match all routes?

Body:
I'm developing a simple web application on Spring boot 1.5.3 and I need all the routes to send static index.html file. Now, I have this:

@Controller
public class IndexController {

    @RequestMapping("/*")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}

My application contains only static assets and REST API. But the problem is that the controller shown above only matches the first-level url like /index, /department etc. I want to match all url levels like /index/some/other/staff etc. How can I do that?

PS. I've tried to use the template /** in @RequestMapping, but my application has broken with the StackOverflow error.

UPDATE

If add one more level to url, then all will work as expected:

@Controller
public class IndexController {

    @RequestMapping("/test/**")
    public String index(final HttpServletRequest request) {
        final String url = request.getRequestURI();

        if (url.startsWith("/static")) {
            return String.format("forward:/%s", url);
        }

        return "forward:/static/index.html";
    }
}

All requests to /test, /test/some/other/staff will return index.html, but I need to start with /.

Body:
You can try this:

@Controller
public class IndexController {

@RequestMapping(value = "/**/{path:[^\\.]*}")
public String index(final HttpServletRequest request) {
    final String url = request.getRequestURI();

    if (url.startsWith("/static")) {
        return String.format("forward:/%s", url);
    }

    return "forward:/static/index.html";
}
}

ContentLicense: CC BY-SA 4.0


问:
Can WCF REST services support deserialisation of XML messages with arbitrary element order?
I have a C# WCF REST Service which allows the addition of a bookmark, by sending an HTTP POST request with the bookmark serialised in XML. I have specified the operation contract for the service, which picks up the xml and automatically deserialises the object for me. My problem is that the deserialisation only works correctly if the XML elements in the request are given in alphabetical order, and the values for any elements that are out of order are not populated.

This behaviour has been reported elsewhere.

I find this to be quite unsatisfactory; I consider the requirement to construct the XML in a specific order to be unnecessary, and a major headache. This is a major requirement to add to all clients of the service, and a source of potentially difficult problems to debug.

Is it possible to direct WCF to be XML element order agnostic?

Some further details for clarification purposes:

My operation contract looks like this:

```<code>[OperationContract]
[WebInvoke(Method="POST", UriTemplate = "/{username}/bookmarks", ResponseFormat = WebMessageFormat.Xml)]
public void PostBookmark(string username, RestBookmark newBookmark);
</code>```

The RestMessage looks as follows:

```<code>[DataContract(Name = "Bookmark", Namespace = "")]
public class RestBookmark
{
    [DataMember]
    public string BookmarkMd5 { get; set; }

    [DataMember]
    public string Url { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public string Description { get; set; }
}
</code>```

If I send the following XML message, then only the UserName property of the RestMessage object will be populated when PostBookmark() is invoked:

```<code><?xml version="1.0"?><Bookmark><UserName>nick.street</UserName><Url>http://www.stackoverflow.com</Url><BookmarkMd5>f184eb3347cf94f6ce5f5fc2844e3bdd</BookmarkMd5><Description>Developer Forum</Description><Title>Stack Overflow</Title></Bookmark>
</code>```

答:
I haven't tried to do this myself, but I'll take a guess.

Would it help to create a [OnDeserializing] event on your DataContract that would fire just before deserialization?  At that point maybe you could reorder the xml however it needs to be ordered so that deserialization would work properly.

If you have Juval Lowy's Programming WCF Services 2nd Edition, that's covered starting on page 107.

Here's the MSDN help page.

Body:
I have a C# WCF REST Service which allows the addition of a bookmark, by sending an HTTP POST request with the bookmark serialised in XML. I have specified the operation contract for the service, which picks up the xml and automatically deserialises the object for me. My problem is that the deserialisation only works correctly if the XML elements in the request are given in alphabetical order, and the values for any elements that are out of order are not populated.

This behaviour has been reported elsewhere.

I find this to be quite unsatisfactory; I consider the requirement to construct the XML in a specific order to be unnecessary, and a major headache. This is a major requirement to add to all clients of the service, and a source of potentially difficult problems to debug.

Is it possible to direct WCF to be XML element order agnostic?

Some further details for clarification purposes:

My operation contract looks like this:

[OperationContract]
[WebInvoke(Method="POST", UriTemplate = "/{username}/bookmarks", ResponseFormat = WebMessageFormat.Xml)]
public void PostBookmark(string username, RestBookmark newBookmark);

The RestMessage looks as follows:

[DataContract(Name = "Bookmark", Namespace = "")]
public class RestBookmark
{
    [DataMember]
    public string BookmarkMd5 { get; set; }

    [DataMember]
    public string Url { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public string Description { get; set; }
}

If I send the following XML message, then only the UserName property of the RestMessage object will be populated when PostBookmark() is invoked:

<?xml version="1.0"?><Bookmark><UserName>nick.street</UserName><Url>http://www.stackoverflow.com</Url><BookmarkMd5>f184eb3347cf94f6ce5f5fc2844e3bdd</BookmarkMd5><Description>Developer Forum</Description><Title>Stack Overflow</Title></Bookmark>

OwnerDisplayName: Terry Donaghe


问:
Given an array of uint8_t what is a good way to extract any subsequence of bits as a uint32_t?
I have run into an interesting problem lately:

Lets say I have an array of bytes (uint8_t to be exact) of length at least one. Now i need a function that will get a subsequence of bits from this array, starting with bit X (zero based index, inclusive) and having length L and will return this as an uint32_t. If L is smaller than 32 the remaining high bits should be zero.

Although this is not very hard to solve, my current thoughts on how to do this seem a bit cumbersome to me. I'm thinking of a table of all the possible masks for a given byte (start with bit 0-7, take 1-8 bits) and then construct the number one byte at a time using this table.

Can somebody come up with a nicer solution? Note that i cannot use Boost or STL for this - and no, it is not a homework, its a problem i run into at work and we do not use Boost or STL in the code where this thing goes. You can assume that: 0 < L <= 32 and that the byte array is large enough to hold the subsequence.

One example of correct input/output:

array: 00110011 1010 1010 11110011 01 101100

subsequence: X = 12 (zero based index), L = 14

resulting uint32_t = 00000000 00000000 00 101011 11001101

答:
Only the first and last bytes in the subsequence will involve some bit slicing to get the required bits out, while the intermediate bytes can be shifted in whole into the result. Here's some sample code, absolutely untested -- it does what I described, but some of the bit indices could be off by one:</p>

```<code>uint8_t bytes[];
int X, L;

uint32_t result;

int startByte  = X / 8,  /* starting byte number */
    startBit   = 7 - X % 8,  /* bit index within starting byte, from LSB */
    endByte    = (X + L) / 8, /* ending byte number */
    endBit     = 7 - (X + L) % 8; /* bit index within ending byte, from LSB */

/* Special case where start and end are within same byte:
   just get bits from startBit to endBit */
if (startByte == endByte) {
  uint8_t byte = bytes[startByte];
  result = (byte >> endBit) & ((1 << (startBit - endBit)) - 1);
}
/* All other cases: get ending bits of starting byte,
                    all other bytes in between,
                    starting bits of ending byte */
else {
  uint8_t byte = bytes[startByte];
  result = byte & ((1 << startBit) - 1);

  for (int i = startByte + 1; i < endByte; i++)
    result = (result << 8) | bytes[i];

  byte = bytes[endByte];
  result = (result << (8 - endBit)) | (byte >> endBit);
}
</code>```

Body:
Only the first and last bytes in the subsequence will involve some bit slicing to get the required bits out, while the intermediate bytes can be shifted in whole into the result. Here's some sample code, absolutely untested -- it does what I described, but some of the bit indices could be off by one:

uint8_t bytes[];
int X, L;

uint32_t result;

int startByte  = X / 8,  /* starting byte number */
    startBit   = 7 - X % 8,  /* bit index within starting byte, from LSB */
    endByte    = (X + L) / 8, /* ending byte number */
    endBit     = 7 - (X + L) % 8; /* bit index within ending byte, from LSB */

/* Special case where start and end are within same byte:
   just get bits from startBit to endBit */
if (startByte == endByte) {
  uint8_t byte = bytes[startByte];
  result = (byte >> endBit) & ((1 << (startBit - endBit)) - 1);
}
/* All other cases: get ending bits of starting byte,
                    all other bytes in between,
                    starting bits of ending byte */
else {
  uint8_t byte = bytes[startByte];
  result = byte & ((1 << startBit) - 1);

  for (int i = startByte + 1; i < endByte; i++)
    result = (result << 8) | bytes[i];

  byte = bytes[endByte];
  result = (result << (8 - endBit)) | (byte >> endBit);
}


问:
How do i work with windows media player from another form?
So i have 2 forms, one is called "musica" and its playing a music (this form is invisible) and the other is called "Form1" and gives the option to stop and start the music with radio buttons.

The problem is that the radio buttons are working, but the video continues even if i click on "radionButton2" and if i use the "stop()" function on "musica_load" the music stops so i don't think the problem is from there either.

What is my mistake here?

Form1 code:

```<code>musica mus = new musica();
private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            mus.play();

        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.stop();

        }
    }
</code>```

musica code:

```<code>    public void play()
    {
            axWindowsMediaPlayer1.Ctlcontrols.play();
    }
    public void stop()
    {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
    }
</code>```

答:
// Form1.cs

```<code>    musica mus;
    public Form1()
    {
        InitializeComponent();
        mus = new musica();
    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {

        if (radioButton1.Checked == true)
        {
            mus.Play(); ;
        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.Stop();
        }
    }
</code>```

//Musica.cs

```<code>    public musica()
    {
        InitializeComponent();
    }

    public void Play()
    {
        MessageBox.Show("Play");
    }

    public void Stop()
    {
        MessageBox.Show("Stop");
    }
</code>```

This works fine there must be some problem with the Play and Stop methods.

Body:
So i have 2 forms, one is called "musica" and its playing a music (this form is invisible) and the other is called "Form1" and gives the option to stop and start the music with radio buttons.

The problem is that the radio buttons are working, but the video continues even if i click on "radionButton2" and if i use the "stop()" function on "musica_load" the music stops so i don't think the problem is from there either.

What is my mistake here?

Form1 code:

musica mus = new musica();
private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            mus.play();

        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.stop();

        }
    }

musica code:

    public void play()
    {
            axWindowsMediaPlayer1.Ctlcontrols.play();
    }
    public void stop()
    {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
    }

Body:
// Form1.cs

    musica mus;
    public Form1()
    {
        InitializeComponent();
        mus = new musica();
    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {

        if (radioButton1.Checked == true)
        {
            mus.Play(); ;
        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.Stop();
        }
    }

//Musica.cs

    public musica()
    {
        InitializeComponent();
    }

    public void Play()
    {
        MessageBox.Show("Play");
    }

    public void Stop()
    {
        MessageBox.Show("Stop");
    }

This works fine there must be some problem with the Play and Stop methods.


问:
Scala structured data extraction via regex and pattern matching
Given structured data in a string format how do I extract parts of the data effectively using pattern matching and regular expressions?

Example:

```<code>val input = Seq("name-12345","inval1d-12345","invalid-12here123","hello-54321","inval1d-1aa2")

case class Client(name:Option[String],clientID:Option[Int])

def parseClient(input:String):Option[Client] = {
  val clientRegex = """([a-zA-Z]+)-([0-9]+)""".r
  Option(input).flatMap(in => {
    in match {
      case clientRegex(name,clientID) => Some(Client(Some(name),Some(clientID.toInt)))
      case _ => None
    }
  })
}

input.map(parseClient)
</code>```

The issue with this however is that if I fail to validate a single part of the structured data then I parse None of it.

How could I use regular expressions to define in a hierarchical manor such as:

```<code>val nameRegex = """([a-zA-Z]+)""".r
val clientIDRegex = """([0-9]+)""".r
</code>```

Then match these combined within a pattern?

The output from the example:

```<code>Seq(
 Some(Client(Some("name"),Some(12345)))
 ,None
 ,None
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)
</code>```

The required output:

```<code>Seq(
 Some(Client(Some("name"),Some(12345)))
 ,Some(Client(None,Some(12345)))
 ,Some(Client(Some("invalid"),None))
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)
</code>```

答:
This should give the expected outcome:

```<code>val input = Seq("name-12345", "inval1d-12345", "invalid-12here123", "hello-54321")

case class Client(name: Option[String], clientID: Option[Int])

def parseClient(input: String): Option[Client] = {
  val clientRegex = """(?:([a-zA-Z^-]+)|[^-]*)-(?:([0-9]+)|.*)""".r
  input match {
    case clientRegex(null, null) => None
    case clientRegex(name, id) => Some(Client(Option(name), Option(id).map(_.toInt)))
    case _ =>
      None
  }
}

input.map(parseClient)
</code>```

I removed the flatMap construct since this was unnecessary.
Interesting part here is the regex:

```<code>"""(?:([a-zA-Z^-]+)|[^-]*)-(?:([0-9]+)|.*)"""
</code>```

I made changed it so it expects either the correct values and therefore captures it in the group ( ([a-zA-Z^-]+) for name and ([0-9]+) for id ) but also added the other cases (no valid name or id). Everything is in non-capture groups (?:) so it is grouped correctly.

If something is not as expected in the capture groups, the group will be null, which is handled in the match-case.

EDIT
Made a correction to the code so that it works for completely invalid input and removed unnecessary if-statements

EDIT 2
Adapted the code according to comment of OP taking advantage of Option(null) => None evaluation

Body:
Given structured data in a string format how do I extract parts of the data effectively using pattern matching and regular expressions?

Example:

val input = Seq("name-12345","inval1d-12345","invalid-12here123","hello-54321","inval1d-1aa2")

case class Client(name:Option[String],clientID:Option[Int])

def parseClient(input:String):Option[Client] = {
  val clientRegex = """([a-zA-Z]+)-([0-9]+)""".r
  Option(input).flatMap(in => {
    in match {
      case clientRegex(name,clientID) => Some(Client(Some(name),Some(clientID.toInt)))
      case _ => None
    }
  })
}

input.map(parseClient)

The issue with this however is that if I fail to validate a single part of the structured data then I parse None of it.

How could I use regular expressions to define in a hierarchical manor such as:

val nameRegex = """([a-zA-Z]+)""".r
val clientIDRegex = """([0-9]+)""".r

Then match these combined within a pattern?

The output from the example:

Seq(
 Some(Client(Some("name"),Some(12345)))
 ,None
 ,None
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)

The required output:

Seq(
 Some(Client(Some("name"),Some(12345)))
 ,Some(Client(None,Some(12345)))
 ,Some(Client(Some("invalid"),None))
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)

Body:
This should give the expected outcome:

val input = Seq("name-12345", "inval1d-12345", "invalid-12here123", "hello-54321")

case class Client(name: Option[String], clientID: Option[Int])

def parseClient(input: String): Option[Client] = {
  val clientRegex = """(?:([a-zA-Z^-]+)|[^-]*)-(?:([0-9]+)|.*)""".r
  input match {
    case clientRegex(null, null) => None
    case clientRegex(name, id) => Some(Client(Option(name), Option(id).map(_.toInt)))
    case _ =>
      None
  }
}

input.map(parseClient)

I removed the flatMap construct since this was unnecessary.
Interesting part here is the regex:

"""(?:([a-zA-Z^-]+)|[^-]*)-(?:([0-9]+)|.*)"""

I made changed it so it expects either the correct values and therefore captures it in the group ( ([a-zA-Z^-]+) for name and ([0-9]+) for id ) but also added the other cases (no valid name or id). Everything is in non-capture groups (?:) so it is grouped correctly.

If something is not as expected in the capture groups, the group will be null, which is handled in the match-case.

EDIT
Made a correction to the code so that it works for completely invalid input and removed unnecessary if-statements

EDIT 2
Adapted the code according to comment of OP taking advantage of Option(null) => None evaluation


问:
Is memory type returned by makeedge() is of static or dynamic type?
What type of memory allocation is this in makedge function?

```<code>#include<iostream>
#include<stdio.h>

using namespace std;

struct edge
{
    int a;
    int b;
    edge(int a, int b)
    {
        this->a=a;
        this->b=b;
    }
};

edge makedge(int a, int b)
{
    return edge(a, b);
}

int main(void)
{
    edge e=makedge(5 , 6);
    printf("%d %d\n", e.a, e.b);
}
</code>```

When I try to free the memory using delete(&e). The error is

```<code>Error : double free or corruption (out): 0x00007fff6aee5d30 ***
</code>```

in geeksforgeeks online compiler.

答:
There is no dynamic allocation in your program.

All your objects have automatic storage duration.

Consequently, deleteing or freeing them is very bad.

Hence the error message.

```<code>return edge(a, b);
</code>```

Here you returned a temporary, an object without name … but it was not dynamically allocated.

It's not totally different from:

```<code>edge myObject(a, b);
return myObject;
</code>```

Body:
What type of memory allocation is this in makedge function?

#include<iostream>
#include<stdio.h>

using namespace std;

struct edge
{
    int a;
    int b;
    edge(int a, int b)
    {
        this->a=a;
        this->b=b;
    }
};

edge makedge(int a, int b)
{
    return edge(a, b);
}

int main(void)
{
    edge e=makedge(5 , 6);
    printf("%d %d\n", e.a, e.b);
}

When I try to free the memory using delete(&e). The error is

Error : double free or corruption (out): 0x00007fff6aee5d30 ***

in geeksforgeeks online compiler.

Body:
There is no dynamic allocation in your program.

All your objects have automatic storage duration.

Consequently, deleteing or freeing them is very bad.

Hence the error message.

return edge(a, b);

Here you returned a temporary, an object without name … but it was not dynamically allocated.

It's not totally different from:

edge myObject(a, b);
return myObject;