问:
Generating XML reports using LINQ to XML in C#
I'm generating reports using LINQ to XML in C#.
For example, I want to generate a report formatted like:

```<code><report>
    <canada>
        <division_1>
            <power generated="22" dailygoal="25" />
            <resources used="15" available="50" />
        </division_1>
        <division_2>
            <power generated="36" dailygoal="40" />
            <resources used="28" available="85" />
        </division_2>
    </canada>
</report>
</code>```

How can I generate an XML file (with one root element) with this format in C# by using foreach loops and object methods to fill the data like so, since I'm getting the data from power and resources objects?:

```<code>foreach (var i in powerList)
{
    division_1.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
{
</code>```

Can I do this with an XDocument object, or do I need to initialize division_1 and division_2 as XElements, do .Add to add the info to the XElements, .Save the XElements as .xml docs, then merge and save them as one doc?

Update:

I've modified the code to look like this...:

```<code>namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {

        // list of power objects...

        List<Power> powerList = new List<Power>();

        Power canada = new Power("canada", 25, 50, 70, 100);
        Power usa = new Power("usa", 45, 60, 80, 150);
        Power sweden = new Power("sweden", 50, 60, 70, 80);
        Power germany = new Power("germany", 65, 75, 90, 125);

        powerList.Add(canada);
        powerList.Add(usa);
        powerList.Add(sweden);
        powerList.Add(germany);

        // create report var and element..

        var report = new XElement("report");

        // foreach...
        foreach (var x in powerList)
        {

            var country = new XElement(x.Country);
            report.Add(country);

            var n = 0;

            //foreach...
            foreach (var i in powerList)
            {
                ++n;

                var division = new XElement("division_" + n);

                division.Add(
                    new XElement("power",
                        new XAttribute("generated", i.powerGenerated),
                        new XAttribute("dailygoal", i.powerGoal)),
                    new XElement("resources",
                        new XAttribute("used", i.resourcesUsed),
                        new XAttribute("available", i.resourcesAvailable)));
                country.Add(division);
            }
        }

        // create xdocument from xelement and save to disk...

        XDocument xml = new XDocument();
        xml.Add(report);

        xml.Save(@".\report.xml");
    }
}
}
</code>```

... but it's generating, for example:

```<code><canada>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</canada>
<usa>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</usa>
</code>```

In the loop it's generating the same data for all objects each run through. Do you see what the issue is and how it could be fixed? I've tried multiple approaches and can't seem to get it.

答:
This seems to do what you are looking for:</p>

```<code>var powerList = new PowerList[] {
    new PowerList { powerGenerated = 22, powerGoal = 25, resourcesUsed = 15, resourcesAvailable = 50 },
    new PowerList { powerGenerated = 36, powerGoal = 40, resourcesUsed = 28, resourcesAvailable = 85 }
};

var report = new XElement("report");
var country = new XElement("canada");
report.Add(country);

var n = 0;
foreach (var i in powerList)
{
    ++n;
    var division = new XElement("division_"+n);

    division.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
    country.Add(division);
}

XDocument xml = new XDocument();
xml.Add(report);
</code>```

Body:
I'm generating reports using LINQ to XML in C#.
For example, I want to generate a report formatted like:

<report>
    <canada>
        <division_1>
            <power generated="22" dailygoal="25" />
            <resources used="15" available="50" />
        </division_1>
        <division_2>
            <power generated="36" dailygoal="40" />
            <resources used="28" available="85" />
        </division_2>
    </canada>
</report>

How can I generate an XML file (with one root element) with this format in C# by using foreach loops and object methods to fill the data like so, since I'm getting the data from power and resources objects?:

foreach (var i in powerList)
{
    division_1.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
{

Can I do this with an XDocument object, or do I need to initialize division_1 and division_2 as XElements, do .Add to add the info to the XElements, .Save the XElements as .xml docs, then merge and save them as one doc?

Update:

I've modified the code to look like this...:

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {

        // list of power objects...

        List<Power> powerList = new List<Power>();

        Power canada = new Power("canada", 25, 50, 70, 100);
        Power usa = new Power("usa", 45, 60, 80, 150);
        Power sweden = new Power("sweden", 50, 60, 70, 80);
        Power germany = new Power("germany", 65, 75, 90, 125);

        powerList.Add(canada);
        powerList.Add(usa);
        powerList.Add(sweden);
        powerList.Add(germany);

        // create report var and element..

        var report = new XElement("report");

        // foreach...
        foreach (var x in powerList)
        {

            var country = new XElement(x.Country);
            report.Add(country);

            var n = 0;

            //foreach...
            foreach (var i in powerList)
            {
                ++n;

                var division = new XElement("division_" + n);

                division.Add(
                    new XElement("power",
                        new XAttribute("generated", i.powerGenerated),
                        new XAttribute("dailygoal", i.powerGoal)),
                    new XElement("resources",
                        new XAttribute("used", i.resourcesUsed),
                        new XAttribute("available", i.resourcesAvailable)));
                country.Add(division);
            }
        }

        // create xdocument from xelement and save to disk...

        XDocument xml = new XDocument();
        xml.Add(report);

        xml.Save(@".\report.xml");
    }
}
}

... but it's generating, for example:

<canada>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</canada>
<usa>
    <division_1>
        <power generated="25" dailygoal="50" />
        <resources used="70" available="100" />
    </division_1>
    <division_2>
        <power generated="45" dailygoal="60" />
        <resources used="80" available="150" />
    </division_2>
    <division_3>
        <power generated="50" dailygoal="60" />
        <resources used="70" available="80" />
    </division_3>
    <division_4>
        <power generated="65" dailygoal="75" />
        <resources used="90" available="125" />
    </division_4>
</usa>

In the loop it's generating the same data for all objects each run through. Do you see what the issue is and how it could be fixed? I've tried multiple approaches and can't seem to get it.

Body:
This seems to do what you are looking for:

var powerList = new PowerList[] {
    new PowerList { powerGenerated = 22, powerGoal = 25, resourcesUsed = 15, resourcesAvailable = 50 },
    new PowerList { powerGenerated = 36, powerGoal = 40, resourcesUsed = 28, resourcesAvailable = 85 }
};

var report = new XElement("report");
var country = new XElement("canada");
report.Add(country);

var n = 0;
foreach (var i in powerList)
{
    ++n;
    var division = new XElement("division_"+n);

    division.Add(
        new XElement("power",
            new XAttribute("generated", i.powerGenerated),
            new XAttribute("dailygoal", i.powerGoal)),
        new XElement("resources",
            new XAttribute("used", i.resourcesUsed),
            new XAttribute("available", i.resourcesAvailable)));
    country.Add(division);
}

XDocument xml = new XDocument();
xml.Add(report);


来源: stackexchange

问:
how to represent graphs /trees in python and how to detect cycles?
i want to implement kruskal's algorithm in python how can i go about representing the tree/graph and what approach should i follow to detect the cycles ?</p>

答:
The simplest way of representing it (in my opinion) is by using a dict of <s>arrays</s> lists:

```<code>graph = {}
graph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]
</code>```

A simple way of finding cycles is by using a BF or DF search:

```<code>def df(node):
    if visited(node):
        pass # found a cycle here, do something with it
    visit(node)
    [df(node_id) for node_id in graph[node]]
</code>```

Disclaimer: this is actually a sketch; neighbors(), visited() and visit() are just dummies to represent how the algorithm should look like.

ContentLicense: CC BY-SA 2.5

Body:
The simplest way of representing it (in my opinion) is by using a dict of <s>arrays</s> lists:

graph = {}
graph[node_id] = [other_node_id for other_node_id in neighbors(node_id)]

A simple way of finding cycles is by using a BF or DF search:

def df(node):
    if visited(node):
        pass # found a cycle here, do something with it
    visit(node)
    [df(node_id) for node_id in graph[node]]

Disclaimer: this is actually a sketch; neighbors(), visited() and visit() are just dummies to represent how the algorithm should look like.

ContentLicense: CC BY-SA 3.0


问:
Alternatives to looping through a function taking inputs from several Pandas series
I have been using Pandas for a while but have not came across a need to do this until now. Here's the setup. I have several Pandas series (with their indices exactly identical), say A, B and C, and a complicated function func(). What I am trying to do (in a non-Pandas-efficient way) is iterate through the index of the series applying func().

```<code>D = pandas.Series(index=A.index) # First create an empty Series
for i in range(len(A)):
    D[i] = func(A[i], B[i], C[i])
</code>```

Is there a Pandas-efficient way of doing the above that takes into account that this is essentially an array-based operation? I looked at pandas.DataFrame.apply but the examples show application of simple functions such as numpy.sqrt() that take only one series argument.

答:
If you have only a pd.Series your function should return a series as well.

Therefore,

```<code>D = func(A, B, C)
</code>```

should yield D as a pd.Series which is a vectorized result over the A, B and C values.

If you want a new column on a DataFrame you could solve it this way:

```<code>df.loc[:,'new column'] = \
        df.loc[:,'data column'].\
            apply(lambda x: func(x, A[x.name], B[x.name], C[x.name]), axis=1)
</code>```

Body:
I have been using Pandas for a while but have not came across a need to do this until now. Here's the setup. I have several Pandas series (with their indices exactly identical), say A, B and C, and a complicated function func(). What I am trying to do (in a non-Pandas-efficient way) is iterate through the index of the series applying func().

D = pandas.Series(index=A.index) # First create an empty Series
for i in range(len(A)):
    D[i] = func(A[i], B[i], C[i])

Is there a Pandas-efficient way of doing the above that takes into account that this is essentially an array-based operation? I looked at pandas.DataFrame.apply but the examples show application of simple functions such as numpy.sqrt() that take only one series argument.

Body:
If you have only a pd.Series your function should return a series as well.

Therefore,

D = func(A, B, C)

should yield D as a pd.Series which is a vectorized result over the A, B and C values.

If you want a new column on a DataFrame you could solve it this way:

df.loc[:,'new column'] = \
        df.loc[:,'data column'].\
            apply(lambda x: func(x, A[x.name], B[x.name], C[x.name]), axis=1)


问:
Listing Blocks of content in horizontal line html
I am trying to make blocks of information presented in horizontal list, and they are currently vertical. Any suggestions?[block example][code]</p>

答:
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}
ul li {
  display: inline-block;
  padding: 10px;
  margin: 10px;
  background-color: #F8F8F8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Block 1</li>
  <li>Block 2</li>
  <li>Block 3</li>
</ul></code>```

Body:
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}
ul li {
  display: inline-block;
  padding: 10px;
  margin: 10px;
  background-color: #F8F8F8;
}

<ul>
  <li>Block 1</li>
  <li>Block 2</li>
  <li>Block 3</li>
</ul>


问:
Why can't I push this additional data into my array?
I'm making an API call and here is the response

As you can see, key 0 & 1 have NULL for their 'outcome_status' whereas key 2 is populated. The number of returned results is dynamic

I wish to loop the results and push the 'category' & 'location' details into the array and if 'outcome_status' isn't NULL then I wish to add that data into the same array.

The problem is, within the IF statement that checks if outcome_status is null, I can't assign the forloop var i; variable as the key for
 mapData where I use.push() the second time.

line:68 Uncaught TypeError: Cannot read property 'push' of undefined

```<code>var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {
</code>```

EDIT: I want to do this.

```<code>            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]);
</code>```

But if there is no outcome_status then it will fail... So I added the second part into a conditional instead

```<code>         if(data[i].outcome_status != null) {

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });
</code>```

答:
The Issue:

Here, you initialize i as 1:

```<code>for(var i = 1; i < data.length; i++) {
</code>```

You then push one item to mapData[]:

```<code>mapData.push([
    data[i]['category'],
    data[i]['location']['street']['name'],
]);
</code>```

A couple lines later, you try to access mapData[i]...

```<code>mapData[i].push([
    data[i]['outcome_status']['category'],
    data[i]['outcome_status']['date'],
]);
</code>```

This is trying to access mapData[1], but mapData[] only has one item at this point. You need mapData[0].

The Solution:

Try simply changing your i to initialize as 0 instead of 1:

```<code>for(var i = 0; i < data.length; i++) {
</code>```

If this is not sufficient and data[] needs to be a 1-index, then perhaps mapData[i-1] instead of mapData[i] would suit your needs.

Body:
I'm making an API call and here is the response

As you can see, key 0 & 1 have NULL for their 'outcome_status' whereas key 2 is populated. The number of returned results is dynamic

I wish to loop the results and push the 'category' & 'location' details into the array and if 'outcome_status' isn't NULL then I wish to add that data into the same array.

The problem is, within the IF statement that checks if outcome_status is null, I can't assign the forloop var i; variable as the key for
 mapData where I use.push() the second time.

line:68 Uncaught TypeError: Cannot read property 'push' of undefined

var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {

EDIT: I want to do this.

            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]);

But if there is no outcome_status then it will fail... So I added the second part into a conditional instead

         if(data[i].outcome_status != null) {

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '

'+[i+1]+'

Type of crime: '+mapData[i][0]+'

Location specifics: '+mapData[i][1]+'

';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });

Body:
The Issue:

Here, you initialize i as 1:

for(var i = 1; i < data.length; i++) {

You then push one item to mapData[]:

mapData.push([
    data[i]['category'],
    data[i]['location']['street']['name'],
]);

A couple lines later, you try to access mapData[i]...

mapData[i].push([
    data[i]['outcome_status']['category'],
    data[i]['outcome_status']['date'],
]);

This is trying to access mapData[1], but mapData[] only has one item at this point. You need mapData[0].

The Solution:

Try simply changing your i to initialize as 0 instead of 1:

for(var i = 0; i < data.length; i++) {

If this is not sufficient and data[] needs to be a 1-index, then perhaps mapData[i-1] instead of mapData[i] would suit your needs.


问:
Could I use a pre-built CMS or should I build one from the ground-up?
I am working on a project for a client that started out as a simple CMS with pages, posts, and a directory. The client is constantly expanding the scope of this project with requirements for customization of just about everything. As a single developer, I am having trouble keeping up with the clients time-table. I have googled for software packages that might already exist that proved the features my client needs but I have not found anything. Does anyone know of any pre-built software that allows for the following customization or at least better words to describe this type of package?

Here are some examples of the customization that is requested:

A page or directory listing needs to be formatted from an admin-defined template. Within this template there needs to be admin-defined sections that contain admin-defined data types. (This is so the look and feel of the site can be maintained while users can easily build content, add listings, and etc.)

Advertising-tiles need to be able to be defined and populated globally and at page level.

All user generated content, pages, posts, and directory listings need to be associated with user and have flexibility to show all other user generated content for inter-linking between same users content.

Site would need billing/e-commerce system for premium listings, premium posts, advertising tiles, and etc.

Approval system for all user added or edited content (pages, posts, directory listings, etc.)

(asp.net and mvc are definitely preferable)

答:
My dear friend,
                       I've read your question & I may suggest that you should try some open-source CMS software with your own which can generate, display admin-generated templates & other stuffs.
                      You should use the

Pre-bulit CMS software for keeping track of pages.

Your own small customized cms for maintaining templates.

osCommerce (open-source) for eCommerce support.


问:
Social identity auth using Azure AD B2C for google doesnt show permission request page but facebook does.
Social identity auth using Azure AD B2C for Google doesn't show permission request page but Facebook does.

Does anyone know why this is happening? Am i missing something here.

答:
Azure AD B2C does not require consent.

The only consent experience you might go through in Azure AD B2C is when signing up / signing in with social accounts.

As part of setting up a social IdP in Azure AD B2C, you must register an application in the social IdP (see this example on how to do it for Facebook). Users will have to consent to that app in their social IdP the very first time the sign in. This consent enforced and maintained by the social IdP, so even if you delete the user in Azure AD B2C, recreating the user in Azure AD B2C using the same app registration will not re-trigger consent.


问:
nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/registry/classloading/internal/ClassLoaderServiceImpl$Work
While I am trying to do sample Spring JPA applicaton I am getting below exception.

```<code>Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
[ERROR] 08 Jun 2017 19:23:45{GMT+5.30:0} - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/registry/classloading/internal/ClassLoaderServiceImpl$Work
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at hello.Application.main(Application.java:17)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/registry/classloading/internal/ClassLoaderServiceImpl$Work
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:54)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 15 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$Work
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 21 common frames omitted
</code>```

I added the necessary binaries eventhough I am getting above exception and please find my below pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.springframework</groupId>
  <artifactId>gs-accessing-data-jpa</artifactId>
  <version>0.1.0</version>
  <packaging>jar</packaging>

  <name>gs-accessing-data-jpa</name>
  <url>http://maven.apache.org</url>

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

  <properties>
  <java.version>1.8</java.version>
  </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
              <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.8.Final</version>
    </dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

    </dependencies>

  <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

Please help me to resolve out this issue.

Thanks,

答:
According to maven central hibernate-entitymanager is deprecated.

Try using hibernate-core

```<code><!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.8.Final</version>
</dependency>
</code>```

Or the latest version

```<code><!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.12.Final</version>
</dependency>
</code>```

Body:
While I am trying to do sample Spring JPA applicaton I am getting below exception.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
[ERROR] 08 Jun 2017 19:23:45{GMT+5.30:0} - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/registry/classloading/internal/ClassLoaderServiceImpl$Work
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at hello.Application.main(Application.java:17)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/registry/classloading/internal/ClassLoaderServiceImpl$Work
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:54)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 15 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$Work
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 21 common frames omitted

I added the necessary binaries eventhough I am getting above exception and please find my below pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.springframework</groupId>
  <artifactId>gs-accessing-data-jpa</artifactId>
  <version>0.1.0</version>
  <packaging>jar</packaging>

  <name>gs-accessing-data-jpa</name>
  <url>http://maven.apache.org</url>

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

  <properties>
  <java.version>1.8</java.version>
  </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
              <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.8.Final</version>
    </dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

    </dependencies>

  <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Please help me to resolve out this issue.

Thanks,

Body:
According to maven central hibernate-entitymanager is deprecated.

Try using hibernate-core

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.8.Final</version>
</dependency>

Or the latest version

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.12.Final</version>
</dependency>


问:
laravel displaying path which matches business_id
I am allowing business to upload images. Everything is saved into database and the only thing I need to do is retrieve  images that match business_id:

So now I need to browse throught business_id and if it's matching, output all images.

```<code>function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    $session = session()->put('key', $id);
    $session = session()->get('key');
    $retrieve_gallery = Gallery::where('business_id', '=' ,$session)->firstOrFail();
    return view('displayBusiness', compact('business', 'address', 'gallery'));
}
</code>```

In session variable I am storing a business id from business table. I want to match that session variable with each business_id in database and return compact 'gallery' so I can use it's path in view:

```<code><img class="images" src="{{ asset($gallery->path) }}" />
</code>```

However I get $gallery is not defined. How can that be fixed?

答:
Use get() to get a collection of images:

```<code>$gallery = Gallery::where('business_id', $id)->get();
</code>```

Then iterate over images to display them:

```<code>@foreach ($gallery as $image)
    <img class="images" src="{{ asset($image->path) }}" />
@endforeach
</code>```

Body:
I am allowing business to upload images. Everything is saved into database and the only thing I need to do is retrieve  images that match business_id:

So now I need to browse throught business_id and if it's matching, output all images.

function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    $session = session()->put('key', $id);
    $session = session()->get('key');
    $retrieve_gallery = Gallery::where('business_id', '=' ,$session)->firstOrFail();
    return view('displayBusiness', compact('business', 'address', 'gallery'));
}

In session variable I am storing a business id from business table. I want to match that session variable with each business_id in database and return compact 'gallery' so I can use it's path in view:

path) }}" />

However I get $gallery is not defined. How can that be fixed?

Body:
Use get() to get a collection of images:

$gallery = Gallery::where('business_id', $id)->get();

Then iterate over images to display them:

@foreach ($gallery as $image)
    <img class="images" src="{{ asset($image->path) }}" />
@endforeach


问:
Dial multiple numbers, hangup on non-answered and connect answered call (twilio)
I'm trying to setup a dialer system for a sales department that will dial multiple numbers from a supplied list, and await for one to be answered by a human. When this occurs, the other phones ringing should immediately be dropped.

According to this Twilio blog post from 2009, nesting  in a TwiML  command should do exactly this. However, upon my testing I find that if a single phone rejects the call no others will be dialed and the entire call-event ends. Is this no longer possible since this post in 2009, or has something changed?

I am using the twilio-client in a web interface and the node helper library to handle receiving events and generating TwiXML responses.

答:
When you give the twiML response as

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial>
    <Number>877-555-1212</Number>
    <Number>877-999-1234</Number>
    <Number>877-123-4567</Number>
  </Dial>
</Response>
</code>```

All the numbers will be called simultaneously and If the call is rejected from any one of the numbers, the other numbers will surely be dialed out until the timeout attribute (in seconds) in the Dial verb

So you can extend this timeout as below,

```<code><Dial timeout='50'>
</code>```

Refer This documentation for more on timeout attribute.

In case if you again want to do some action based on the dialcallstatus,

When  ends, Twilio will submit to the action URL with the parameter
DialStatus with one of the following scenarios:

nobody picks up, DialStatus=no-answer

the line is busy, DialStatus=busy

the called party picked up, DialStatus=answered

an invalid phone number was provided, DialStatus=failed

You can handle it in the action attribute of Dial verb as below

```<code><Dial timeout='50' action='your_url'>
</code>```

So in the Response construction you can handle the other stuff based on the dialcallstatus param in the request of your mentioned "action url" from Twilio.

Body:
When you give the twiML response as

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial>
    <Number>877-555-1212</Number>
    <Number>877-999-1234</Number>
    <Number>877-123-4567</Number>
  </Dial>
</Response>

All the numbers will be called simultaneously and If the call is rejected from any one of the numbers, the other numbers will surely be dialed out until the timeout attribute (in seconds) in the Dial verb

So you can extend this timeout as below,

<Dial timeout='50'>

Refer This documentation for more on timeout attribute.

In case if you again want to do some action based on the dialcallstatus,

When  ends, Twilio will submit to the action URL with the parameter
DialStatus with one of the following scenarios:

nobody picks up, DialStatus=no-answer

the line is busy, DialStatus=busy

the called party picked up, DialStatus=answered

an invalid phone number was provided, DialStatus=failed

You can handle it in the action attribute of Dial verb as below

<Dial timeout='50' action='your_url'>

So in the Response construction you can handle the other stuff based on the dialcallstatus param in the request of your mentioned "action url" from Twilio.


问:
Dynamically Create Collection/Array in VBA
I'm struggling with this, I'm doing some stuff in Access with VBA and I need to dynamically create N collections/lists/arrays of records and add them to my dictionary.

```<code>//Some pseudo code
Dim dict as object
Set dict = CreateObject("Scripting.Dictionary")

for record in myRecordSetObject
    if dict.exists(keyfromrecord)
         dict(keyfromrecord) = array.add(record)
    else
         newarray = [record]
         dict.add key:="keyfromrecord" item:=array
</code>```

If it can't be done I might just do a string of primary keys and grow it as needed, then call string split.

Edit

So I have my records and I need to divide them into subgroups based on a few common fields that they may or may not share. If two records have the same pieces of information in these select fields they're in a subgroup. A subgroup may have 1 - N records.

Instead of getting all possible combinations and filtering my query I want to create a dictionary that defines it's key as a string generated from these fields. If a key exists then there's a member of that subgroup, if it doesn't it's a new subgroup.

The value was going to be an array of records.

Afterwards I was going to go through my dictionary and do stuff with these records.

```<code>Field1     Field2     Field3    Field4
Fruit      Skinned    Sliced    Baked
Apples     True       True      True
Bananas    True       True      True
Oranges    True       False     False
</code>```

Using this example above subgroup would be when Field2,3 and 4 have the same value. (Apples, Bananas) and the other would be (Oranges)

I want a dictionary with Key being

```<code>dictionary{
           "True-True-True": [Apples, Bananas],
           "True-False-True": [Oranges]
}
</code>```

答: You could use the Redim keyword to change the array size</p>

Body:
I'm struggling with this, I'm doing some stuff in Access with VBA and I need to dynamically create N collections/lists/arrays of records and add them to my dictionary.

//Some pseudo code
Dim dict as object
Set dict = CreateObject("Scripting.Dictionary")

for record in myRecordSetObject
    if dict.exists(keyfromrecord)
         dict(keyfromrecord) = array.add(record)
    else
         newarray = [record]
         dict.add key:="keyfromrecord" item:=array

If it can't be done I might just do a string of primary keys and grow it as needed, then call string split.

Edit

So I have my records and I need to divide them into subgroups based on a few common fields that they may or may not share. If two records have the same pieces of information in these select fields they're in a subgroup. A subgroup may have 1 - N records.

Instead of getting all possible combinations and filtering my query I want to create a dictionary that defines it's key as a string generated from these fields. If a key exists then there's a member of that subgroup, if it doesn't it's a new subgroup.

The value was going to be an array of records.

Afterwards I was going to go through my dictionary and do stuff with these records.

Field1     Field2     Field3    Field4
Fruit      Skinned    Sliced    Baked
Apples     True       True      True
Bananas    True       True      True
Oranges    True       False     False

Using this example above subgroup would be when Field2,3 and 4 have the same value. (Apples, Bananas) and the other would be (Oranges)

I want a dictionary with Key being

dictionary{
           "True-True-True": [Apples, Bananas],
           "True-False-True": [Oranges]
}


问:
c++ How could I properly predefined array of char*?
I am doing it that way:

```<code>int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";
</code>```

but I get notice, that it is deprecated. What is better way?

答:
Besides the problem of using something other than a constant expression for your array size...

The thing that has been deprecated is the silent casting of string literals to char*.  This used to be OK:

```<code>char * hello = "hello";
</code>```

Now it has to be:

```<code>char const* hello = "hello";
</code>```

This deprecation is actually in an Appendix in C++03.

Body:
I am doing it that way:

int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";

but I get notice, that it is deprecated. What is better way?

Body:
Besides the problem of using something other than a constant expression for your array size...

The thing that has been deprecated is the silent casting of string literals to char*.  This used to be OK:

char * hello = "hello";

Now it has to be:

char const* hello = "hello";

This deprecation is actually in an Appendix in C++03.


问:
Random unique binary matrices
I want Random BUT unique binary matrices of dimension n*n.

For example, if n = 5, then there are 2^(5*5) = 33554432 unique combinations (matrices), which is a HUGE number. I only need 1000. This is my current approach but it takes ALOT of time (which I can not afford because I need to increase the dimensions in future). And I feel it is redundant because in the end I am only selecting 1000 random combinations out of the full number. Any other approach to handle this? This is how I am currently doing it:

I start with a data frame of n*n variables, first row all 1s and second row all 0s:

```<code> Length = 25
 m <- as.data.frame(matrix(c(rep(0, connections), rep(1,
      connections)),ncol=25, byrow = TRUE))
</code>```

m looks like this:

```<code>#V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
#V22 V23 V24 V25
#1  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0
#0   0   0   0   0
#2  1  1  1  1  1  1  1  1  1   1   1   1   1   1   1   1   1   1   1   1
#1   1   1   1   1
</code>```

Next I get all the unique combinations using expand.grid

```<code>mFull = expand.grid(m) # This takes forever
</code>```

And then I select 1000 random rows:

```<code>mRand = mFull[sample(1:nrow(mFull), 1000,)]
</code>```

And after this I convert each row into a n*n matrix, for example, for 1st row:

```<code>mRand[1,]
#     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
#V21 V22 V23 V24 V25
#21788869  1  1  0  1  1  1  0  0  1   1   1   0   0   0   0   1   1   1   0
#0   1   1   0   1   0
</code>```

Convert it to a matrix:

```<code>> matrix(mRand[1,], nrow = 5, byrow = TRUE)
 [,1] [,2] [,3] [,4] [,5]
 [1,] 1    1    0    1    1
 [2,] 1    0    0    1    1
 [3,] 1    0    0    0    0
 [4,] 1    1    1    0    0
 [5,] 1    1    0    1    0
</code>```

Does anyone has a suggestion for a more efficient solution?

答:
I suggest you just generate the matrices completely random and check for each new matrix if it already has been created. If not, discard it.

As long as the number of possible matrices is a lot bigger than the number of matrices needed this works well, otherwise it may be slow.

Example code:

```<code>randomMatrix <- function(n) matrix(as.numeric(runif(n^2) > 0.5), ncol = n)  # generates random binary square matrix of size n x n

m <- 1000  # number of matrices needed

res <- vector("list", m)  # stores the result
i <- 1  # index of next matrix

while (i <= m) {

  cand <- randomMatrix(5)
  ## check if the candidate is distinct from all matrices in res
  if (!any(sapply(res, function(x) identical(x, cand)))) {
    res[[i]] <- cand
    i <- i + 1
  }

}
</code>```

If you really run into speed problems (which I doubt) you could use some hashes to speed up compoarison. For example you could store the row- and column sums for each matrix and only test for equality if the sums coincide.

Title: Random unique binary matrices

Body:
I want Random BUT unique binary matrices of dimension n*n.

For example, if n = 5, then there are 2^(5*5) = 33554432 unique combinations (matrices), which is a HUGE number. I only need 1000. This is my current approach but it takes ALOT of time (which I can not afford because I need to increase the dimensions in future). And I feel it is redundant because in the end I am only selecting 1000 random combinations out of the full number. Any other approach to handle this? This is how I am currently doing it:

I start with a data frame of n*n variables, first row all 1s and second row all 0s:

 Length = 25
 m <- as.data.frame(matrix(c(rep(0, connections), rep(1,
      connections)),ncol=25, byrow = TRUE))

m looks like this:

#V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
#V22 V23 V24 V25
#1  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0
#0   0   0   0   0
#2  1  1  1  1  1  1  1  1  1   1   1   1   1   1   1   1   1   1   1   1
#1   1   1   1   1

Next I get all the unique combinations using expand.grid

mFull = expand.grid(m) # This takes forever

And then I select 1000 random rows:

mRand = mFull[sample(1:nrow(mFull), 1000,)]

And after this I convert each row into a n*n matrix, for example, for 1st row:

mRand[1,]
#     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
#V21 V22 V23 V24 V25
#21788869  1  1  0  1  1  1  0  0  1   1   1   0   0   0   0   1   1   1   0
#0   1   1   0   1   0

Convert it to a matrix:

> matrix(mRand[1,], nrow = 5, byrow = TRUE)
 [,1] [,2] [,3] [,4] [,5]
 [1,] 1    1    0    1    1
 [2,] 1    0    0    1    1
 [3,] 1    0    0    0    0
 [4,] 1    1    1    0    0
 [5,] 1    1    0    1    0

Does anyone has a suggestion for a more efficient solution?

Body:
I suggest you just generate the matrices completely random and check for each new matrix if it already has been created. If not, discard it.

As long as the number of possible matrices is a lot bigger than the number of matrices needed this works well, otherwise it may be slow.

Example code:

randomMatrix <- function(n) matrix(as.numeric(runif(n^2) > 0.5), ncol = n)  # generates random binary square matrix of size n x n

m <- 1000  # number of matrices needed

res <- vector("list", m)  # stores the result
i <- 1  # index of next matrix

while (i <= m) {

  cand <- randomMatrix(5)
  ## check if the candidate is distinct from all matrices in res
  if (!any(sapply(res, function(x) identical(x, cand)))) {
    res[[i]] <- cand
    i <- i + 1
  }

}

If you really run into speed problems (which I doubt) you could use some hashes to speed up compoarison. For example you could store the row- and column sums for each matrix and only test for equality if the sums coincide.


问:
stringr str_locate_all not returning the proper index in a dplyr string
I'm trying to use str_locate_all to find the index of the third occurrence of  '/' in a dplyr chain but it's not returning the correct index.

```<code>  ga.categoryViews.2016 <- ga.data %>%
    mutate(province = str_sub(pagePath,2,3),
           index = str_locate_all(pagePath, '/')[[1]][,"start"][3],
           category = str_sub(pagePath,
                              str_locate_all(pagePath, '/')[[1]][,"start"][3] + 1,
                              ifelse(str_detect(pagePath,'\\?'), str_locate(pagePath, '\\?') - 1, str_length(pagePath))
                              )
             )
</code>```

an example of what it's returning is

The first column is pagePath, the fourth is the index

It seems to be always returning an index of 12.

Any help is appreciated.

Thanks,

答:
You need to use rowwise(), i.e.

```<code>library(dplyr)
library(stringr)

df %>%
 rowwise() %>%
 mutate(new = str_locate_all(v1, '/')[[1]][,2][3])

Source: local data frame [2 x 2]
Groups: <by row>

# A tibble: 2 x 2
#                              v1   new
#                           <chr> <int>
#1 /on/srgsfsfs-gfdgdg/dfgsdfg-df    20
#2        /on/sgsddg-dfgsd/dfg-dg    17
</code>```

DATA

```<code>x <- c('/on/srgsfsfs-gfdgdg/dfgsdfg-df', '/on/sgsddg-dfgsd/dfg-dg')
df <- data.frame(v1 = x, stringsAsFactors = F)

df
#                              v1
#1 /on/srgsfsfs-gfdgdg/dfgsdfg-df
#2        /on/sgsddg-dfgsd/dfg-dg
</code>```

Body:
I'm trying to use str_locate_all to find the index of the third occurrence of  '/' in a dplyr chain but it's not returning the correct index.

  ga.categoryViews.2016 <- ga.data %>%
    mutate(province = str_sub(pagePath,2,3),
           index = str_locate_all(pagePath, '/')[[1]][,"start"][3],
           category = str_sub(pagePath,
                              str_locate_all(pagePath, '/')[[1]][,"start"][3] + 1,
                              ifelse(str_detect(pagePath,'\\?'), str_locate(pagePath, '\\?') - 1, str_length(pagePath))
                              )
             )

an example of what it's returning is

The first column is pagePath, the fourth is the index

It seems to be always returning an index of 12.

Any help is appreciated.

Thanks,

Body:
You need to use rowwise(), i.e.

library(dplyr)
library(stringr)

df %>%
 rowwise() %>%
 mutate(new = str_locate_all(v1, '/')[[1]][,2][3])

Source: local data frame [2 x 2]
Groups: <by row>

# A tibble: 2 x 2
#                              v1   new
#                           <chr> <int>
#1 /on/srgsfsfs-gfdgdg/dfgsdfg-df    20
#2        /on/sgsddg-dfgsd/dfg-dg    17

DATA

x <- c('/on/srgsfsfs-gfdgdg/dfgsdfg-df', '/on/sgsddg-dfgsd/dfg-dg')
df <- data.frame(v1 = x, stringsAsFactors = F)

df
#                              v1
#1 /on/srgsfsfs-gfdgdg/dfgsdfg-df
#2        /on/sgsddg-dfgsd/dfg-dg


问:
Count lines (max) with values
I would like to count the lines that have values. I tried oSheet.Rows.Count but that doesn't work. Any idea about this?

My code is the following:

```<code>Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet")

oSheet.Range("A" & max).Value = "0000111"
oSheet.Range("B1").Value ="Name"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()
</code>```

答:
Define a row variable as Long, then start a loop which will end when it finds a blank value in column A:

```<code>Dim lRow as Long = 1

Do until oSheet.Range("A" & lRow).Value=""
  ' increment the loop variable
  lRow+=1
Loop

' display the result in a message block
MsgBox(lRow-1)
</code>```

Title: Count lines (max) with values

Body:
I would like to count the lines that have values. I tried oSheet.Rows.Count but that doesn't work. Any idea about this?

My code is the following:

Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet")

oSheet.Range("A" & max).Value = "0000111"
oSheet.Range("B1").Value ="Name"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()

Body:
Define a row variable as Long, then start a loop which will end when it finds a blank value in column A:

Dim lRow as Long = 1

Do until oSheet.Range("A" & lRow).Value=""
  ' increment the loop variable
  lRow+=1
Loop

' display the result in a message block
MsgBox(lRow-1)


问:
Regular expression - delimiter problem in PHP
I'm trying to extract src attributes from: [attname src="http://example.org"] somecontent [attname src="http://www.example.com"]

What I have now:

preg_match_all('#attname src=".*[^"]#', $buffer, $bufferarr);

However it doesn't work - there's no stop after second ", what results in: attname src="http://example.org"] somecontent [attname src="http://www.example.com

答:
Not the best solution but anyways it get's the job done :</p>

```<code>$str = '[attname src="http://example.org"] somecontent [attname src="http://www.example.com"]';
preg_match_all('/attname src=\"(.*?)\"/', $str, $match);
var_dump($match);
</code>```

Body:
Not the best solution but anyways it get's the job done :

$str = '[attname src="http://example.org"] somecontent [attname src="http://www.example.com"]';
preg_match_all('/attname src=\"(.*?)\"/', $str, $match);
var_dump($match);


问:
Change colorbar gradient in matplotlib
I have a grid of weights (Y) evolving with time (X):

I cannot distinguish correctly the variations of weights as the distribution is asymmetric between positive and negative weights; the null weights should be recognized as it means the given variables are not used.

For these reasons, I would like to change the color gradient to get something like those (either a or b):

Any idea on how to approach this?

答:
A colorbar in matplotlib maps number between 0 and 1 to a color. In order to map other numbers to colors you need a normalization to the range [0,1] first. This is usually done automatically from the minimum and maximum data, or by using vmin and vmax arguments to the respective plotting function. Internally a normalization instance matplotlib.colors.Normalize is used to perform the normalization and by default a linear scale between vmin and vmax is assumed.

Here you want a nonlinear scale, which (a) shifts the middle point to some specified value, and (b) squeezes the colors around that value.

The idea can now be to subclass matplotlib.colors.Normalize and let it return a a mapping which fulfills the criteria (a) and (b).

An option might be the combination of two root functions as shown below.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

class SqueezedNorm(matplotlib.colors.Normalize):
    def __init__(self, vmin=None, vmax=None, mid=0, s1=2, s2=2, clip=False):
        self.vmin = vmin # minimum value
        self.mid  = mid  # middle value
        self.vmax = vmax # maximum value
        self.s1=s1; self.s2=s2
        f = lambda x, zero,vmax,s: np.abs((x-zero)/(vmax-zero))**(1./s)*0.5
        self.g = lambda x, zero,vmin,vmax, s1,s2: f(x,zero,vmax,s1)*(x>=zero) - \
                                             f(x,zero,vmin,s2)*(x<zero)+0.5
        matplotlib.colors.Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        r = self.g(value, self.mid,self.vmin,self.vmax, self.s1,self.s2)
        return np.ma.masked_array(r)

fig, (ax, ax2, ax3) = plt.subplots(nrows=3,
                                   gridspec_kw={"height_ratios":[3,2,1], "hspace":0.25})

x = np.linspace(-13,4, 110)
norm=SqueezedNorm(vmin=-13, vmax=4, mid=0, s1=1.7, s2=4)

line, = ax.plot(x, norm(x))
ax.margins(0)
ax.set_ylim(0,1)

im = ax2.imshow(np.atleast_2d(x).T, cmap="Spectral_r", norm=norm, aspect="auto")
cbar = fig.colorbar(im ,cax=ax3,ax=ax2, orientation="horizontal")
</code>```

The function is chosen such that independent of its parameters it will map any range onto the range [0,1], such that a colormap can be used. The parameter mid determines which value should be mapped to the middle of the colormap. This would be 0 in this case. The parameters s1 and s2 determine how squeezed the colormap is in both directions.

Setting mid = np.mean(vmin, vmax), s1=1, s2=1 would recover the original scaling.

In order to choose good parameters, one may use some Sliders to see the live updated plot.

```<code>from matplotlib.widgets import Slider

midax = plt.axes([0.1, 0.04, 0.2, 0.03], facecolor="lightblue")
s1ax = plt.axes([0.4, 0.04, 0.2, 0.03], facecolor="lightblue")
s2ax = plt.axes([0.7, 0.04, 0.2, 0.03], facecolor="lightblue")

mid = Slider(midax, 'Midpoint', x[0], x[-1], valinit=0)
s1 = Slider(s1ax, 'S1', 0.5, 6, valinit=1.7)
s2 = Slider(s2ax, 'S2', 0.5, 6, valinit=4)

def update(val):
    norm=SqueezedNorm(vmin=-13, vmax=4, mid=mid.val, s1=s1.val, s2=s2.val)
    im.set_norm(norm)
    cbar.update_bruteforce(im)
    line.set_ydata(norm(x))
    fig.canvas.draw_idle()

mid.on_changed(update)
s1.on_changed(update)
s2.on_changed(update)

fig.subplots_adjust(bottom=0.15)
</code>```

Title: Change colorbar gradient in matplotlib

Body:
A colorbar in matplotlib maps number between 0 and 1 to a color. In order to map other numbers to colors you need a normalization to the range [0,1] first. This is usually done automatically from the minimum and maximum data, or by using vmin and vmax arguments to the respective plotting function. Internally a normalization instance matplotlib.colors.Normalize is used to perform the normalization and by default a linear scale between vmin and vmax is assumed.

Here you want a nonlinear scale, which (a) shifts the middle point to some specified value, and (b) squeezes the colors around that value.

The idea can now be to subclass matplotlib.colors.Normalize and let it return a a mapping which fulfills the criteria (a) and (b).

An option might be the combination of two root functions as shown below.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

class SqueezedNorm(matplotlib.colors.Normalize):
    def __init__(self, vmin=None, vmax=None, mid=0, s1=2, s2=2, clip=False):
        self.vmin = vmin # minimum value
        self.mid  = mid  # middle value
        self.vmax = vmax # maximum value
        self.s1=s1; self.s2=s2
        f = lambda x, zero,vmax,s: np.abs((x-zero)/(vmax-zero))**(1./s)*0.5
        self.g = lambda x, zero,vmin,vmax, s1,s2: f(x,zero,vmax,s1)*(x>=zero) - \
                                             f(x,zero,vmin,s2)*(x<zero)+0.5
        matplotlib.colors.Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        r = self.g(value, self.mid,self.vmin,self.vmax, self.s1,self.s2)
        return np.ma.masked_array(r)

fig, (ax, ax2, ax3) = plt.subplots(nrows=3,
                                   gridspec_kw={"height_ratios":[3,2,1], "hspace":0.25})

x = np.linspace(-13,4, 110)
norm=SqueezedNorm(vmin=-13, vmax=4, mid=0, s1=1.7, s2=4)

line, = ax.plot(x, norm(x))
ax.margins(0)
ax.set_ylim(0,1)

im = ax2.imshow(np.atleast_2d(x).T, cmap="Spectral_r", norm=norm, aspect="auto")
cbar = fig.colorbar(im ,cax=ax3,ax=ax2, orientation="horizontal")

The function is chosen such that independent of its parameters it will map any range onto the range [0,1], such that a colormap can be used. The parameter mid determines which value should be mapped to the middle of the colormap. This would be 0 in this case. The parameters s1 and s2 determine how squeezed the colormap is in both directions.

Setting mid = np.mean(vmin, vmax), s1=1, s2=1 would recover the original scaling.

In order to choose good parameters, one may use some Sliders to see the live updated plot.

from matplotlib.widgets import Slider

midax = plt.axes([0.1, 0.04, 0.2, 0.03], facecolor="lightblue")
s1ax = plt.axes([0.4, 0.04, 0.2, 0.03], facecolor="lightblue")
s2ax = plt.axes([0.7, 0.04, 0.2, 0.03], facecolor="lightblue")

mid = Slider(midax, 'Midpoint', x[0], x[-1], valinit=0)
s1 = Slider(s1ax, 'S1', 0.5, 6, valinit=1.7)
s2 = Slider(s2ax, 'S2', 0.5, 6, valinit=4)

def update(val):
    norm=SqueezedNorm(vmin=-13, vmax=4, mid=mid.val, s1=s1.val, s2=s2.val)
    im.set_norm(norm)
    cbar.update_bruteforce(im)
    line.set_ydata(norm(x))
    fig.canvas.draw_idle()

mid.on_changed(update)
s1.on_changed(update)
s2.on_changed(update)

fig.subplots_adjust(bottom=0.15)


问:
My image in a picture box is not rotating on keypressed
I am doing a car parking game.i am using the arrow keys to move it,but when the down key is pressed,the picture box does not move down.Also ,when the right or up keys are pressed,the picture box does not stop.I want also to rotate the car while moving right or left.I tried but was not able.</p>

```<code> Private Sub Timerdiagonalright_Tick(sender As Object, e As EventArgs) Handles Timerdiagonalright.Tick
    RotateImage(pbcar1.Image, 20)

End Sub

Private Function RotateImage(img As Image, angle As Single) As Bitmap
    ' the calling code is responsible for (and must)
    ' disposing of the bitmap returned

    Dim retBMP As New Bitmap(img.Width, img.Height)
    retBMP.SetResolution(img.HorizontalResolution, img.VerticalResolution)

    Using g = Graphics.FromImage(retBMP)
        ' rotate aroung the center of the image
        g.TranslateTransform(img.Width \ 2, img.Height \ 2)

        'rotate
        g.RotateTransform(angle)

        g.TranslateTransform(-img.Width \ 2, -img.Height \ 2)

        'draw image to the bitmap
        g.DrawImage(img, New PointF(0, 0))

        Return retBMP
    End Using
End Function
</code>```

答:
If the image is already loaded to your PictureBox, your can use

```<code>PictureBox.Image.RotateFlip(RotateFlipType)
</code>```

to rotate your image.

Please note that this is not an efficient way to do animated graphics; to improve performance a little when moving controls, consider reading on SuspendLayout / ResumeLayout and BeginUpdate / EndUpdate.

Body:
I am doing a car parking game.i am using the arrow keys to move it,but when the down key is pressed,the picture box does not move down.Also ,when the right or up keys are pressed,the picture box does not stop.I want also to rotate the car while moving right or left.I tried but was not able.

 Private Sub Timerdiagonalright_Tick(sender As Object, e As EventArgs) Handles Timerdiagonalright.Tick
    RotateImage(pbcar1.Image, 20)

End Sub

Private Function RotateImage(img As Image, angle As Single) As Bitmap
    ' the calling code is responsible for (and must)
    ' disposing of the bitmap returned

    Dim retBMP As New Bitmap(img.Width, img.Height)
    retBMP.SetResolution(img.HorizontalResolution, img.VerticalResolution)

    Using g = Graphics.FromImage(retBMP)
        ' rotate aroung the center of the image
        g.TranslateTransform(img.Width \ 2, img.Height \ 2)

        'rotate
        g.RotateTransform(angle)

        g.TranslateTransform(-img.Width \ 2, -img.Height \ 2)

        'draw image to the bitmap
        g.DrawImage(img, New PointF(0, 0))

        Return retBMP
    End Using
End Function

Body:
If the image is already loaded to your PictureBox, your can use

PictureBox.Image.RotateFlip(RotateFlipType)

to rotate your image.

Please note that this is not an efficient way to do animated graphics; to improve performance a little when moving controls, consider reading on SuspendLayout / ResumeLayout and BeginUpdate / EndUpdate.


问:
ReportLab Set Page Size to Letter
I am trying to set my page size to letter while still adding a flowable style. Please help me refine my code.

```<code># Sample platypus document
# From the FAQ at reportlab.org/oss/rl-toolkit/faq/#1.1

# Import some constructors, some paragraph styles and other conveniences from other modules.
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.platypus import Image
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas

PAGE_HEIGHT = defaultPageSize[0]
PAGE_WIDTH = defaultPageSize[0]
defaultPageSize = letter
styles = getSampleStyleSheet()
Title = "Comparison Index"
pageinfo = "platypus example"
Image3 = 'BTALogo.png'

# Define the fixed features of the first page of the document
def myFirstPage(canvas, doc):
    canvas.saveState()
    canvas.setFontSize(22)
    canvas.setFont('Helvetica-Bold', 36)
    canvas.drawString(50, 670, 'Health & Welfare')

    canvas.setFont('Helvetica-Bold', 24)
    canvas.drawString(50, 625, 'Benchmark Comparison Report')

    canvas.setFont('Helvetica', 16)
    canvas.drawString(50, 550, 'Prepared for:')

    canvas.setFont('Times-Roman', 12)
    canvas.drawString(inch, 0.25 * inch, "First Page / %s" % pageinfo)
    canvas.restoreState()

# Since we want pages after the first to look different from the first we define an alternate layout for
# the fixed features of the other pages.
# Note that the two functions use the pdfgen level canvas operations to  paint the annotations for the pages.
def myLaterPages(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 23)
    canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
    canvas.restoreState()

def myThirdPages(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 9)
    canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
    canvas.restoreState()

# Create a story and build the document
def go():

    doc = SimpleDocTemplate("Comparison Index.pdf", pagesize=letter)
    Story = [Spacer(1, 2 * inch)]
    style = styles["Normal"]
    for i in range(3):
        bogustext = ("Paragraph number %s. " % i) * 4
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1, 0.2 * inch))

    logo = "PlanOffered.jpg"
    im = Image(logo, 7 * inch, 2 * inch)
    Story.append(im)

    logo = "BTALogo.png"
    im2 = Image(logo, 4 * inch, 4 * inch)
    Story.append(im2)

    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)

if __name__ == "__main__":
    go()
</code>```

The goal is to be able to add flows but not alter the size of the page. We need this report to be in leter size.

答:
Try This....

```<code>def PrintID(request,std_id):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;
    filename="somefilename.pdf"'
    buffer = BytesIO()

    p = canvas.Canvas(buffer)
    p.setFont('Helvetica-Bold', 36)

    p.setPageSize((400, 400))
    p.drawString(100, 100, "Hello world.")

# Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
</code>```

It works........

Title: ReportLab Set Page Size to Letter

Body:
I am trying to set my page size to letter while still adding a flowable style. Please help me refine my code.

# Sample platypus document
# From the FAQ at reportlab.org/oss/rl-toolkit/faq/#1.1

# Import some constructors, some paragraph styles and other conveniences from other modules.
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.platypus import Image
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas

PAGE_HEIGHT = defaultPageSize[0]
PAGE_WIDTH = defaultPageSize[0]
defaultPageSize = letter
styles = getSampleStyleSheet()
Title = "Comparison Index"
pageinfo = "platypus example"
Image3 = 'BTALogo.png'

# Define the fixed features of the first page of the document
def myFirstPage(canvas, doc):
    canvas.saveState()
    canvas.setFontSize(22)
    canvas.setFont('Helvetica-Bold', 36)
    canvas.drawString(50, 670, 'Health & Welfare')

    canvas.setFont('Helvetica-Bold', 24)
    canvas.drawString(50, 625, 'Benchmark Comparison Report')

    canvas.setFont('Helvetica', 16)
    canvas.drawString(50, 550, 'Prepared for:')

    canvas.setFont('Times-Roman', 12)
    canvas.drawString(inch, 0.25 * inch, "First Page / %s" % pageinfo)
    canvas.restoreState()

# Since we want pages after the first to look different from the first we define an alternate layout for
# the fixed features of the other pages.
# Note that the two functions use the pdfgen level canvas operations to  paint the annotations for the pages.
def myLaterPages(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 23)
    canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
    canvas.restoreState()

def myThirdPages(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 9)
    canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
    canvas.restoreState()

# Create a story and build the document
def go():

    doc = SimpleDocTemplate("Comparison Index.pdf", pagesize=letter)
    Story = [Spacer(1, 2 * inch)]
    style = styles["Normal"]
    for i in range(3):
        bogustext = ("Paragraph number %s. " % i) * 4
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1, 0.2 * inch))

    logo = "PlanOffered.jpg"
    im = Image(logo, 7 * inch, 2 * inch)
    Story.append(im)

    logo = "BTALogo.png"
    im2 = Image(logo, 4 * inch, 4 * inch)
    Story.append(im2)

    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)

if __name__ == "__main__":
    go()

The goal is to be able to add flows but not alter the size of the page. We need this report to be in leter size.

Body:
Try This....

def PrintID(request,std_id):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;
    filename="somefilename.pdf"'
    buffer = BytesIO()

    p = canvas.Canvas(buffer)
    p.setFont('Helvetica-Bold', 36)

    p.setPageSize((400, 400))
    p.drawString(100, 100, "Hello world.")

# Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

It works........


问:
Java Date year calculation is off by year for two days
This caused a Y2K-style bug in my software if you can imagine.  Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.

The output:

```<code>03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012
</code>```

I am not sure which part of the Java date utilities could cause such an error.

The code (since the test is so small I included a complete working program):

```<code>import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class DateT {

        private static String getFormattedBackscanStartTime(int days) {

                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
                Calendar workingDate = Calendar.getInstance();
                workingDate.add(Calendar.DATE, -1 * days);

                String formattedStartTime = dateFormat.format(workingDate.getTime());
                return formattedStartTime;
        }

        public static void main(String args[]) {

                for(int i = 35; i < 45; i++) {
                        System.out.println(getFormattedBackscanStartTime(i));
                }
        }
}
</code>```

答:
For the sake of completeness, here’s the modern answer using LocalDate (as recommended by Basil Bourque in a comment).

```<code>import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateT {

    private static DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.US);

    private static String getFormattedBackscanStartTime(int days) {
        return LocalDate.now(ZoneId.systemDefault()).minusDays(days).format(dateFormatter);
    }

    public static void main(String args[]) {
        for(int i = 155; i < 165; i++) {
            System.out.println(getFormattedBackscanStartTime(i));
        }
    }
}
</code>```

Running this today I got

```<code>04-Jan-2017
03-Jan-2017
02-Jan-2017
01-Jan-2017
31-Dec-2016
30-Dec-2016
29-Dec-2016
28-Dec-2016
27-Dec-2016
26-Dec-2016
</code>```

A few things to note:

Give an explicit locale to your formatter to control the langauge of your output. Even if you just pass Locale.getDefault() you are telling the reader that you have thought about locale and made a decision.

Similarly give an explicit time zone to LocalDate.now() to tell the reader you’ve made a decision (for example ZoneId.of("America/New_York") for a specific time zone; ZoneId.systemDefault() for the JVM’s current time zone setting).

I find the code simpler and more straightforward than the code using the oldfashioned Calendar class. This is typical for the newer classes.

I have used uuuu for year. yyyy (lowercase) works too, there will only be a difference for years before the common era (AKA BC).

Body:
This caused a Y2K-style bug in my software if you can imagine.  Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.

The output:

03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012

I am not sure which part of the Java date utilities could cause such an error.

The code (since the test is so small I included a complete working program):

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

public class DateT {

        private static String getFormattedBackscanStartTime(int days) {

                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
                Calendar workingDate = Calendar.getInstance();
                workingDate.add(Calendar.DATE, -1 * days);

                String formattedStartTime = dateFormat.format(workingDate.getTime());
                return formattedStartTime;
        }

        public static void main(String args[]) {

                for(int i = 35; i < 45; i++) {
                        System.out.println(getFormattedBackscanStartTime(i));
                }
        }
}

Body:
For the sake of completeness, here’s the modern answer using LocalDate (as recommended by Basil Bourque in a comment).

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateT {

    private static DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.US);

    private static String getFormattedBackscanStartTime(int days) {
        return LocalDate.now(ZoneId.systemDefault()).minusDays(days).format(dateFormatter);
    }

    public static void main(String args[]) {
        for(int i = 155; i < 165; i++) {
            System.out.println(getFormattedBackscanStartTime(i));
        }
    }
}

Running this today I got

04-Jan-2017
03-Jan-2017
02-Jan-2017
01-Jan-2017
31-Dec-2016
30-Dec-2016
29-Dec-2016
28-Dec-2016
27-Dec-2016
26-Dec-2016

A few things to note:

Give an explicit locale to your formatter to control the langauge of your output. Even if you just pass Locale.getDefault() you are telling the reader that you have thought about locale and made a decision.

Similarly give an explicit time zone to LocalDate.now() to tell the reader you’ve made a decision (for example ZoneId.of("America/New_York") for a specific time zone; ZoneId.systemDefault() for the JVM’s current time zone setting).

I find the code simpler and more straightforward than the code using the oldfashioned Calendar class. This is typical for the newer classes.

I have used uuuu for year. yyyy (lowercase) works too, there will only be a difference for years before the common era (AKA BC).


问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.

You should also sanitize your inputs from SQL/XSS vulnerabilities.

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>


问:
How attach mail template in .NET core
I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code

```<code>  //From Address
            string FromAddress = "info@gorollo.com";
            string FromAdressTitle = "Gorollo";
            //To Address
            string ToAddress = email;
            string Subject = subject;
            string BodyContent = message;
            var body = new BodyBuilder();
            var mimeMessage = new MimeMessage();
            mimeMessage.From.Add(new MailboxAddress
                                    (FromAdressTitle,
                                     FromAddress
                                     ));
            mimeMessage.To.Add(new MailboxAddress
                                     (
                                     ToAddress
                                     ));
            mimeMessage.Subject = Subject;
            using (var client = new SmtpClient())
            {
                client.Connect("smtp.mailgun.org", 587, false);
                client.Authenticate(
                    "info@gorollo.com",
                    "password"
                    );
                await client.SendAsync(mimeMessage);
                await client.DisconnectAsync(true);
            }
</code>```

i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.

答:
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.

Example:

```<code>var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();
</code>```

Title: How attach mail template in .NET core

Body:
I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code

  //From Address
            string FromAddress = "info@gorollo.com";
            string FromAdressTitle = "Gorollo";
            //To Address
            string ToAddress = email;
            string Subject = subject;
            string BodyContent = message;
            var body = new BodyBuilder();
            var mimeMessage = new MimeMessage();
            mimeMessage.From.Add(new MailboxAddress
                                    (FromAdressTitle,
                                     FromAddress
                                     ));
            mimeMessage.To.Add(new MailboxAddress
                                     (
                                     ToAddress
                                     ));
            mimeMessage.Subject = Subject;
            using (var client = new SmtpClient())
            {
                client.Connect("smtp.mailgun.org", 587, false);
                client.Authenticate(
                    "info@gorollo.com",
                    "password"
                    );
                await client.SendAsync(mimeMessage);
                await client.DisconnectAsync(true);
            }

i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.

Body:
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.

Example:

var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();


问:
Need to create subquery in Access 2016 that gives a distinct count
So I am trying to create a query that will return the total weight of food taken out of our food cupboard by students (I work at a university food cupboard) and I am able to get it to give me all of the totals I need except for a count of distinct students that come in. Basically, I need it to give me the number of different students that come in instead of the number of transactions it's giving me right now. Anyone out there know how to fix it? Current code is below:

Student_ID is the field that I need the subquery on if I'm correct...

```<code>SELECT DISTINCTROW
    Format$([Transaction Table].[Date],'mmmm yyyy') AS [Month],
    Sum([Transaction Table].Weight) AS [Total Weight],
    Count(*) AS [Total Transaction],
    Count([Transaction Table].Student_ID) AS [Unique Customers]
FROM [Transaction Table]
GROUP BY
    Format$([Transaction Table].[Date],'mmmm yyyy'),
    Year([Transaction Table].[Date])*12+DatePart('m',[Transaction Table].[Date])-1;
</code>```

答:
If you only want the number of distinct students per date, you can use the following:

```<code>SELECT Count(Student_ID) As StudentCount, ShortDate
FROM
   (SELECT Student_ID, Format$([Date], "Short Date") As ShortDate
    FROM [Transaction Table]
    GROUP BY Student_ID, Format$([Date], "Short Date"))
GROUP BY ShortDate
</code>```

Then you can join it on the date.

Doing it in one statement, however, will be difficult, since Access doesn't like nested subqueries.

Body:
So I am trying to create a query that will return the total weight of food taken out of our food cupboard by students (I work at a university food cupboard) and I am able to get it to give me all of the totals I need except for a count of distinct students that come in. Basically, I need it to give me the number of different students that come in instead of the number of transactions it's giving me right now. Anyone out there know how to fix it? Current code is below:

Student_ID is the field that I need the subquery on if I'm correct...

SELECT DISTINCTROW
    Format$([Transaction Table].[Date],'mmmm yyyy') AS [Month],
    Sum([Transaction Table].Weight) AS [Total Weight],
    Count(*) AS [Total Transaction],
    Count([Transaction Table].Student_ID) AS [Unique Customers]
FROM [Transaction Table]
GROUP BY
    Format$([Transaction Table].[Date],'mmmm yyyy'),
    Year([Transaction Table].[Date])*12+DatePart('m',[Transaction Table].[Date])-1;

Body:
If you only want the number of distinct students per date, you can use the following:

SELECT Count(Student_ID) As StudentCount, ShortDate
FROM
   (SELECT Student_ID, Format$([Date], "Short Date") As ShortDate
    FROM [Transaction Table]
    GROUP BY Student_ID, Format$([Date], "Short Date"))
GROUP BY ShortDate

Then you can join it on the date.

Doing it in one statement, however, will be difficult, since Access doesn't like nested subqueries.


问:
Horizontal and vertical sortable divs
I'd like to get an answer to my problem with a sortable grid. I'm having 2 rows with both containing 3 columns.

```<code><div id="sortable" class="connectedSortable">
<div class="row">
    <div class="column">column</div>
    <div class="column">column</div>
    <div class="column">column</div>
</div>
<div class="row">
    <div class="column">column</div>
    <div class="column">column</div>
    <div class="column">column</div>
</div>
</div>
</code>```

I'd like these to be sortable vertically(the columns) and horizontally(the rows)
Here is my CSS:

```<code>    .row {  height: 200px;  }

    .row:nth-child(even) {  background: lightgray;  }

    #sortable {  height: 100px;  }

    .column {
        float: left;
        display: inline-block;
        width: 33.3%;
        height: 200px;
    }
    .column:nth-child(odd) {  background: red;  }

    .row:nth-child(2){
        background:yellow;
    }

    .row:nth-child(2) .column:nth-child(odd) {  background: pink;  }
</code>```

Which looks like this:

I am unable to select the first or second row to change positions vertically, i think it's because of the columns that can be sortable too, and the colums are using full width of the row.

The only jQuery that I'm using is the following (with jQueryUI):

```<code>$(function () {
        $("#sortable, .row").sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    });
</code>```

Jsfiddle:
JsFiddle

答:
Does this do what you want. I have changed the layout so the columns all have the same parent and then used the below to clear them.

```<code>.conlumn:nth-child(3n) {
  content:"";
  clear:both;
}
</code>```

https://jsfiddle.net/g4q95kp2/1/

Title: Horizontal and vertical sortable divs

Body:
I'd like to get an answer to my problem with a sortable grid. I'm having 2 rows with both containing 3 columns.

column

column

column

column

column

column

I'd like these to be sortable vertically(the columns) and horizontally(the rows)
Here is my CSS:

    .row {  height: 200px;  }

    .row:nth-child(even) {  background: lightgray;  }

    #sortable {  height: 100px;  }

    .column {
        float: left;
        display: inline-block;
        width: 33.3%;
        height: 200px;
    }
    .column:nth-child(odd) {  background: red;  }

    .row:nth-child(2){
        background:yellow;
    }

    .row:nth-child(2) .column:nth-child(odd) {  background: pink;  }

Which looks like this:

I am unable to select the first or second row to change positions vertically, i think it's because of the columns that can be sortable too, and the colums are using full width of the row.

The only jQuery that I'm using is the following (with jQueryUI):

$(function () {
        $("#sortable, .row").sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    });

Jsfiddle:
JsFiddle

Body:
Does this do what you want. I have changed the layout so the columns all have the same parent and then used the below to clear them.

.conlumn:nth-child(3n) {
  content:"";
  clear:both;
}

https://jsfiddle.net/g4q95kp2/1/