问:
CSS two divs next to each other (w/o line break)
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

```<code>    <hr class="hr--small">
    <div class="grid">

    <div class="grid__item text-left">
      <p class="site-footer__links">{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved
      </p>
    </div>

    <div class="grid__item text-right">
      <p class="site-footer__links">
        <a href="http://www.w3schools.com/html/">Privacy Policy</a> •
        <a href="http://www.w3schools.com/html/">Terms & Conditions</a>
      </p>
    </div>
</code>```

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.

答:
You can float both div elements and clear the container, using inline-block and box-sizing to fit the true width of the container:

```<code>.grid {
  width: 100%;
  clear: both;
}

.grid__item {
  box-sizing: border-box;
  width: 50%;
  float: left;
  padding: 0px 15px;
  display: inline-block;
}

.text-right {
  text-align: right;
}
</code>```

Fiddle Here

Body:
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved

        Privacy Policy •
        Terms & Conditions

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.

Body:
You can float both div elements and clear the container, using inline-block and box-sizing to fit the true width of the container:

.grid {
  width: 100%;
  clear: both;
}

.grid__item {
  box-sizing: border-box;
  width: 50%;
  float: left;
  padding: 0px 15px;
  display: inline-block;
}

.text-right {
  text-align: right;
}

Fiddle Here


来源: stackexchange

问:
Unable to connect to Microsoft Dynamics CRM with PHP and Curl
I am trying to use PHP and CURL to connect to Microsoft Dynamics API so I can read client data from the CRM. The API guide can be found here:
https://msdn.microsoft.com/en-gb/library/mt593051.aspx

I've been into the Azure portal and set up a new application, and it gives me the credentials to use (client id, secret, etc.) and the url end points. Using these credentials I am able to successfully connect to the CRM and retrieve a bearer access token, but I am unable to get any further.

When I attempt to use the token to return data I receive the below error message:

HTTP Error 401 - Unauthorized: Access is denied

My assumption would be that I must be passing the token correctly?

My code is below.

```<code><?php
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay)
$credentials = array(
    'grant_type'=>'client_credentials',
    'username'=>'xxxxxxxx',
    'password'=>'xxxxxxxx',
    'client_id'=>'xxxxxxxxxxxx',
    'client_secret'=>'xxxxxxxxxx',
    );
$urlSafeCredentials = http_build_query($credentials);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);

// A BEARER access token is successfully returned
$token = $result->access_token;

// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied)

$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
print_r($response); // 401 Unauthorized ?!
?>
</code>```

As far as I can tell there is nothing else to configure at the back end, any help would be much appreciated.

答:
I wrote a lightweight PHP class for working with Dynamics 365 online Web API. You can find it here.

BTW in your code you should try "password" inside the grant_type instead of "client_credentials"

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use PHP and CURL to connect to Microsoft Dynamics API so I can read client data from the CRM. The API guide can be found here:
https://msdn.microsoft.com/en-gb/library/mt593051.aspx

I've been into the Azure portal and set up a new application, and it gives me the credentials to use (client id, secret, etc.) and the url end points. Using these credentials I am able to successfully connect to the CRM and retrieve a bearer access token, but I am unable to get any further.

When I attempt to use the token to return data I receive the below error message:

HTTP Error 401 - Unauthorized: Access is denied

My assumption would be that I must be passing the token correctly?

My code is below.

<?php
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay)
$credentials = array(
    'grant_type'=>'client_credentials',
    'username'=>'xxxxxxxx',
    'password'=>'xxxxxxxx',
    'client_id'=>'xxxxxxxxxxxx',
    'client_secret'=>'xxxxxxxxxx',
    );
$urlSafeCredentials = http_build_query($credentials);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);

// A BEARER access token is successfully returned
$token = $result->access_token;

// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied)

$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
print_r($response); // 401 Unauthorized ?!
?>

As far as I can tell there is nothing else to configure at the back end, any help would be much appreciated.


问:
Validate input before Jackson in Spring Boot
I've built a REST endpoint using Spring Boot. JSON is posted to the endpoint. Jackson converts the JSON giving me an object.

The JSON look like this:

```<code>{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-02"
}
</code>```

Jackson converts the JSON to an object based on this class:

```<code>public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}
</code>```

This all works fine. The issue I'm having is that I would like to validate the data before Jackson converts the data. For instance if I post

```<code>{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-40"
}
</code>```

Where parameterDateAdjusted is not a valid date (there is no month with 40 days in it). Jackson converts this to 2017-02-09. One way of getting around this is to have a class that is only strings let's call it ParameterDateInput. Validate each filed with Hibernate Validator in the parameterDateInput object and then copy the parameterDateInput object to parameterDate where each field has the correct type (dates are of type Date and not of type String). This to me doesn't look like a very elegant solution. Is there some other way I can solve this? How is data generally validated in Spring Boot when posted as JSON? I like to be able to send back a message to the user/client what is wrong with the data that is being posted.

答:
How about a custom JSON deserializer where you can write down the logic you want:</p>

```<code>@RestController
public class JacksonCustomDesRestEndpoint {

    @RequestMapping(value = "/yourEndPoint", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object createRole(@RequestBody ParameterDate paramDate) {
        return paramDate;
    }
}

@JsonDeserialize(using = RoleDeserializer.class)
public class ParameterDate {
    // ......
}

public class RoleDeserializer extends JsonDeserializer<ParameterDate> {
    @Override
    public ParameterDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        String parameterDateUnadjusted = node.get("parameterDateUnadjusted").getTextValue();
        //Do what you want with the date and set it to object from type ParameterDate and return the object at the end.
        //Don't forget to fill all the properties to this object because you do not want to lose data that came from the request.
        return something;
    }
}
</code>```

Body:
I've built a REST endpoint using Spring Boot. JSON is posted to the endpoint. Jackson converts the JSON giving me an object.

The JSON look like this:

{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-02"
}

Jackson converts the JSON to an object based on this class:

public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}

This all works fine. The issue I'm having is that I would like to validate the data before Jackson converts the data. For instance if I post

{
    "parameterDateUnadjusted": "2017-01-01",
    "parameterDateAdjusted": "2017-01-40"
}

Where parameterDateAdjusted is not a valid date (there is no month with 40 days in it). Jackson converts this to 2017-02-09. One way of getting around this is to have a class that is only strings let's call it ParameterDateInput. Validate each filed with Hibernate Validator in the parameterDateInput object and then copy the parameterDateInput object to parameterDate where each field has the correct type (dates are of type Date and not of type String). This to me doesn't look like a very elegant solution. Is there some other way I can solve this? How is data generally validated in Spring Boot when posted as JSON? I like to be able to send back a message to the user/client what is wrong with the data that is being posted.

Body:
How about a custom JSON deserializer where you can write down the logic you want:

@RestController
public class JacksonCustomDesRestEndpoint {

    @RequestMapping(value = "/yourEndPoint", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object createRole(@RequestBody ParameterDate paramDate) {
        return paramDate;
    }
}

@JsonDeserialize(using = RoleDeserializer.class)
public class ParameterDate {
    // ......
}

public class RoleDeserializer extends JsonDeserializer<ParameterDate> {
    @Override
    public ParameterDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        String parameterDateUnadjusted = node.get("parameterDateUnadjusted").getTextValue();
        //Do what you want with the date and set it to object from type ParameterDate and return the object at the end.
        //Don't forget to fill all the properties to this object because you do not want to lose data that came from the request.
        return something;
    }
}


问:
Request.QueryString - replacing + (plus) sign with space

abcd.aspx?ST=f7aABcBdHIm7E8/0SAWKGtz8qKkhwNpJuZ+Jh+Jg+jg=&ET=d0698IjyKXsfkDDAmgy79kOd8+ONzX6IlgSrDME0QHw=

when I use the below code in my .cs page:

```<code>Request.QueryString["ST"]
</code>```

It returns the value:

```<code>"f7aABcBdHIm7E8/0SAWKGtz8qKkhwNpJuZ Jh Jg jg="
</code>```

It replaced the + sign with a space character (" ").

Any idea how to solve this?

答:
I tested it. It gives the right result</p>

```<code>string cidEncode = Server.UrlEncode(Request.QueryString["CID"]);
string cid = Regex.Replace(cidEncode, "%3d", "=", RegexOptions.IgnoreCase);
</code>```

Body:
abcd.aspx?ST=f7aABcBdHIm7E8/0SAWKGtz8qKkhwNpJuZ+Jh+Jg+jg=&ET=d0698IjyKXsfkDDAmgy79kOd8+ONzX6IlgSrDME0QHw=

when I use the below code in my .cs page:

Request.QueryString["ST"]

It returns the value:

"f7aABcBdHIm7E8/0SAWKGtz8qKkhwNpJuZ Jh Jg jg="

It replaced the + sign with a space character (" ").

Any idea how to solve this?

Body:
I tested it. It gives the right result

string cidEncode = Server.UrlEncode(Request.QueryString["CID"]);
string cid = Regex.Replace(cidEncode, "%3d", "=", RegexOptions.IgnoreCase);


问:
How to Create new activity using float action button (fab)?
Hi can somebody have a suggestions on how to make a new activity using Fab  like if you click the fab button it will show up a side transition saying hello world? actually i am creating a chat app and i want to replace the "hello world" with my contacts.

i got a reference link or source code regarding the float action button i mention.what i did is i removed the list view so that only the  fab button is on the screen,  http://www.myandroidsolutions.com/2015/01/01/android-floating-action-button-fab-tutorial

any comments or suggestion will be helpful for me to execute this. thanks!

答:
you should define your activity in androidmainfest.xml as </p>

```<code><activity android:name=".MainActivity">
        </activity>
</code>```

Body:
you should define your activity in androidmainfest.xml as

<activity android:name=".MainActivity">
        </activity>


答:
By default, divs are block elements. This means, among other things, that they drop to a new line each time. There are a few css techniques you can use to get divs to stay on the same line (float: left, display: inline, display: flex), but my favourite is display: inline-block The only issue with this is that there is a slight bug in that sometimes the whitespace (spaces or newlines) in your html file can cause your elements to wrap to a new line. You can get around this by removing the whitespace like so:

```<code>    <div class="grid__item text-left">
      <p class="site-footer__links">{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved
      </p>
    </div><div class="grid__item text-right">
      <p class="site-footer__links">
        <a href="http://www.w3schools.com/html/">Privacy Policy</a> •
        <a href="http://www.w3schools.com/html/">Terms & Conditions</a>
      </p>
    </div>
</code>```

Then in your css, you'd have something like this:

```<code>.grid__item{
    display: inline-block;
    width: 50%;
}
</code>```

Title: CSS two divs next to each other (w/o line break)

Body:
By default, divs are block elements. This means, among other things, that they drop to a new line each time. There are a few css techniques you can use to get divs to stay on the same line (float: left, display: inline, display: flex), but my favourite is display: inline-block The only issue with this is that there is a slight bug in that sometimes the whitespace (spaces or newlines) in your html file can cause your elements to wrap to a new line. You can get around this by removing the whitespace like so:

    <div class="grid__item text-left">
      <p class="site-footer__links">{{ 'layout.footer.copyright' | t }} &copy;
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved
      </p>
    </div><div class="grid__item text-right">
      <p class="site-footer__links">
        <a href="http://www.w3schools.com/html/">Privacy Policy</a> •
        <a href="http://www.w3schools.com/html/">Terms & Conditions</a>
      </p>
    </div>

Then in your css, you'd have something like this:

.grid__item{
    display: inline-block;
    width: 50%;
}


问:
Writing testable TypeScript classes for Dynamics CRM
How do you write a class for a Dynamics CRM form in TypeScript that is testable?

By testable, I mean a non-static class that can be instantiated and passed a mock Xrm object.

My current approach is something like this, but it has limitations (which I explain):

```<code>export class Contact {
    Xrm: Xrm.XrmStatic;

    constructor(xrm?: Xrm.XrmStatic) {
        this.Xrm = xrm;
    }

    onLoad(): void {
       if (this.Xrm) { Xrm = this.Xrm; }
       // ...
    }
}
</code>```

Firstly, the Contact class is exported so that can be referenced by a CRM form. CRM can't instantiate an object before calling it's functions, so to call these methods I use Contact.prototype.onLoad in the CRM form designer.

My test looks like this:

```<code>beforeEach(function () {
    this.XrmMock = new XrmStaticMock();
    this.contact = new Contact(this.XrmMock);
    this.contact.onLoad();
}

it('does stuff', function () {
    // ...
}
</code>```

The test is able to instantiate Contact and pass XrmMock to the constructor. Subsequently when onLoad() is called, it evaluates if (this.Xrm) to true, and uses XrmMock. Conversely, when Contact.prototype.onLoad() is called from within CRM, (this.Xrm) is false because Contact has never been instantiated. Therefore any reference to Xrm within onLoad() uses the default Xrm namespace (which is what we want). We want this because when a CRM form is opened, the real Xrm dependency is loaded by the browser.

The limitation here is having to write a conditional check in every method which wants to use the Xrm dependency. How can this be overcome?

Here's a link to documentation on the Xrm.Page object model. My classes and Xrm mock are written using @types/xrm.

I appreciate I'm asking multiple questions here, if you think you can guide me to writing a more specific question, please let me know :)

答:
From J. Doe's answer I've arrived at code similar to as follows:

```<code>module Company.Contact {
    let contact: Contact;

    export function onLoad(xrm?: Xrm.XrmStatic) {
        contact = new Contact(xrm || Xrm);
        contact.onLoad();
    }

    export class Contact {
        constructor(xrm?: Xrm.XrmStatic) { Xrm = xrm || Xrm; }

        onLoad(): void {
            // ...
        }
    }
}
</code>```

The solution is to create an exported function that is separate from the Contact object for each event you want to fire from CRM. The example above separates the onLoad method, but you could create functions for other CRM form events such as a field change:

```<code>module Company.Contact {
    export function onLoad(xrm?: Xrm.XrmStatic) { // ... }
    export function firstNameOnChange() { // ... }

    export class Contact { // ... }
}
</code>```

You can also go one step further, and wrap the exported event functions in a module per entity form, such as Main and Mobile:

```<code>module Company.Contact {
    export module MainForm {
        export function onLoad(xrm?: Xrm.XrmStatic) {
            // ...
        }
    }

    export module MobileForm {
        export function onLoad(xrm?: Xrm.XrmStatic) {
            // ...
        }
    }

    export class Contact { // ... }
}
</code>```

Usage in CRM

Just add Company.Contact.onLoad to the form or field's event handlers.

Usage in tests

```<code>beforeEach(() => {
    // Create your Xrm mock from a separate mocking library
    this.XrmMock = new XrmStaticMock();

    // Call onLoad
    Company.Contact.onLoad(this.XrmMock);

    // Or use this if using separate modules per form
    Company.Contact.MainForm.onLoad(this.XrmMock);
}

describe('onLoad', () => {
    it('does stuff', () => {
        // ...
    }
}
</code>```

Body:
How do you write a class for a Dynamics CRM form in TypeScript that is testable?

By testable, I mean a non-static class that can be instantiated and passed a mock Xrm object.

My current approach is something like this, but it has limitations (which I explain):

export class Contact {
    Xrm: Xrm.XrmStatic;

    constructor(xrm?: Xrm.XrmStatic) {
        this.Xrm = xrm;
    }

    onLoad(): void {
       if (this.Xrm) { Xrm = this.Xrm; }
       // ...
    }
}

Firstly, the Contact class is exported so that can be referenced by a CRM form. CRM can't instantiate an object before calling it's functions, so to call these methods I use Contact.prototype.onLoad in the CRM form designer.

My test looks like this:

beforeEach(function () {
    this.XrmMock = new XrmStaticMock();
    this.contact = new Contact(this.XrmMock);
    this.contact.onLoad();
}

it('does stuff', function () {
    // ...
}

The test is able to instantiate Contact and pass XrmMock to the constructor. Subsequently when onLoad() is called, it evaluates if (this.Xrm) to true, and uses XrmMock. Conversely, when Contact.prototype.onLoad() is called from within CRM, (this.Xrm) is false because Contact has never been instantiated. Therefore any reference to Xrm within onLoad() uses the default Xrm namespace (which is what we want). We want this because when a CRM form is opened, the real Xrm dependency is loaded by the browser.

The limitation here is having to write a conditional check in every method which wants to use the Xrm dependency. How can this be overcome?

Here's a link to documentation on the Xrm.Page object model. My classes and Xrm mock are written using @types/xrm.

I appreciate I'm asking multiple questions here, if you think you can guide me to writing a more specific question, please let me know :)

Body:
From J. Doe's answer I've arrived at code similar to as follows:

module Company.Contact {
    let contact: Contact;

    export function onLoad(xrm?: Xrm.XrmStatic) {
        contact = new Contact(xrm || Xrm);
        contact.onLoad();
    }

    export class Contact {
        constructor(xrm?: Xrm.XrmStatic) { Xrm = xrm || Xrm; }

        onLoad(): void {
            // ...
        }
    }
}

The solution is to create an exported function that is separate from the Contact object for each event you want to fire from CRM. The example above separates the onLoad method, but you could create functions for other CRM form events such as a field change:

module Company.Contact {
    export function onLoad(xrm?: Xrm.XrmStatic) { // ... }
    export function firstNameOnChange() { // ... }

    export class Contact { // ... }
}

You can also go one step further, and wrap the exported event functions in a module per entity form, such as Main and Mobile:

module Company.Contact {
    export module MainForm {
        export function onLoad(xrm?: Xrm.XrmStatic) {
            // ...
        }
    }

    export module MobileForm {
        export function onLoad(xrm?: Xrm.XrmStatic) {
            // ...
        }
    }

    export class Contact { // ... }
}

Usage in CRM

Just add Company.Contact.onLoad to the form or field's event handlers.

Usage in tests

beforeEach(() => {
    // Create your Xrm mock from a separate mocking library
    this.XrmMock = new XrmStaticMock();

    // Call onLoad
    Company.Contact.onLoad(this.XrmMock);

    // Or use this if using separate modules per form
    Company.Contact.MainForm.onLoad(this.XrmMock);
}

describe('onLoad', () => {
    it('does stuff', () => {
        // ...
    }
}


问:
Vagrantfile merge/append parameters
I want to allow appending of parameters to config.vm.synced_folder. I want users to append additional parameters to this config.

I have so far:

```<code>append_params = 'x: false, y: false'
config.vm.synced_folder x['folder'], "/var/www", create: true, type: "nfs", append_params
</code>```

If I remove , append_params it works. But with it, it fails with error:

```<code>There is a syntax error in the following Vagrantfile. The syntax error
message is reproduced below for convenience:
D:/x/Vagrantfile:32: syntax error, unexpected '\n', expecting =>
</code>```

How can I append additional parameters on request to config.vm.synced_folder?

答:
So finally I found the solution that works in my case as I have some config.yml with parameters that get parsed inside Vagrantfile

```<code># config.yml
append_params:
    :someVar: false
    :fsnotify: true

# Vagrantfile
if File.file?("config.yml")
    parameters = YAML.load_file 'config.yml'
else
    parameters = {}
end
...
Vagrant.configure("2") do |config|
    config.ssh.forward_agent = true
    ...
    config.vm.synced_folder parameters['synced_folder'], "/var/www",  parameters['append_params'].merge({create: true, type: "nfs"})
</code>```

Title: Vagrantfile merge/append parameters

Body:
I want to allow appending of parameters to config.vm.synced_folder. I want users to append additional parameters to this config.

I have so far:

append_params = 'x: false, y: false'
config.vm.synced_folder x['folder'], "/var/www", create: true, type: "nfs", append_params

If I remove , append_params it works. But with it, it fails with error:

There is a syntax error in the following Vagrantfile. The syntax error
message is reproduced below for convenience:
D:/x/Vagrantfile:32: syntax error, unexpected '\n', expecting =>

How can I append additional parameters on request to config.vm.synced_folder?

Body:
So finally I found the solution that works in my case as I have some config.yml with parameters that get parsed inside Vagrantfile

# config.yml
append_params:
    :someVar: false
    :fsnotify: true

# Vagrantfile
if File.file?("config.yml")
    parameters = YAML.load_file 'config.yml'
else
    parameters = {}
end
...
Vagrant.configure("2") do |config|
    config.ssh.forward_agent = true
    ...
    config.vm.synced_folder parameters['synced_folder'], "/var/www",  parameters['append_params'].merge({create: true, type: "nfs"})


问:
Need to Escape the Character After Special Characters in Python's regex?
I have the following python code:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
line = 'div><div class="fieldRow jr_name"><div class="fieldLabel">name<'
regex0 = re.compile('(.+?)\v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex1 = re.compile('(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex2 = re.compile('(.+?) class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)

m0 = regex0.match(line)
m1 = regex1.match(line)
m2 = regex2.match(line)

if m0:
    print 'regex0 is good'
else:
    print 'regex0 is no good'

if m1:
    print 'regex1 is good'
else:
    print 'regex1 is no good'

if m2:
    print 'regex2 is good'
else:
    print 'regex2 is no good'
</code>```

The output is

```<code>regex0 is good
regex1 is no good
regex2 is good
</code>```

I don't quite understand why I need to escape the character 'v' after "(.+?)" in regex0.  If I don't escape, which will become regex1, then the matching will fail.  However, for space right after "(.+?)" in regex3, I don't have to escape.

Any idea?

Thanks in advance.

答:
So, there are some issues with your approach
The ones that contribute to your specific complaint are:

You do not mark te regexp string as raw (r' prefix) - that makes the Python compiler change some "\" prefixed characters inside the string before they even reach the re.match call.

"\v" happens to be one such character - a vertical tab that is replaced by "\0x0b"

You use the  "re.VERBOSE" flag - that simply tells the regexp engine to ignore any whitesapce character. "\v" being a vertical tab is one character in this class and is ignored.

So, there is your match for regex0: the letter "v" os never seem as such.

Now, for the possible fixes on you approach, in the order that you should be trying to do them:

1) Don't use regular expressions to parse HTML. Really. There are a lot of packages that can do a good job on parsing HTML, and in missing those you can use stdlib's own HTMLParser (html.parser in Python3);

2) If possible, use Python 3 instead of Python 2 - you will be bitten on the first non-ASCII character inside yourt HTML body if you go on with the naive approach of treating Python2 strings as "real life" text. Python 3 automatic encoding handling (and explicit settings allowed to you when it is not automatic) .

Since you are probably not changing anyway, so try to use regex.findall instead of regex.match - this returns a list of matching strings and could retreive the attributes you are looking at once, without searching from the beggining of the file, or depending on line-breaks inside the HTML.

Body:
I have the following python code:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
line = 'div>

name<'
regex0 = re.compile('(.+?)\v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex1 = re.compile('(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex2 = re.compile('(.+?) class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)

m0 = regex0.match(line)
m1 = regex1.match(line)
m2 = regex2.match(line)

if m0:
    print 'regex0 is good'
else:
    print 'regex0 is no good'

if m1:
    print 'regex1 is good'
else:
    print 'regex1 is no good'

if m2:
    print 'regex2 is good'
else:
    print 'regex2 is no good'

The output is

regex0 is good
regex1 is no good
regex2 is good

I don't quite understand why I need to escape the character 'v' after "(.+?)" in regex0.  If I don't escape, which will become regex1, then the matching will fail.  However, for space right after "(.+?)" in regex3, I don't have to escape.

Any idea?

Thanks in advance.


问:
Calling actionscript2.0 method from javascript
How to call AS2 method from Javascript?

Without ExternalInterface use.

答:
```<code>if (window.actionScript2) {
    var AS2 = new window.actionScript2;
    // use AS2
}
</code>```

Just wait for me to implement a browser that has the window.actionScript2 property.

ContentLicense: CC BY-SA 2.5

Body:
if (window.actionScript2) {
    var AS2 = new window.actionScript2;
    // use AS2
}

Just wait for me to implement a browser that has the window.actionScript2 property.


问:
WinForms - DataGridViewCell not being set to read only
I am working on an old .Net 2.0 WinForms project and need to set some cells to read only.

I have a DataTable that I am reading and setting as the DataSource and the field types are being set correctly

Generate DataTable and columns

```<code>public DataTable FilterData(DataTable datatable, string dataType)
    {
        try
        {
            if (dataType == "MailPreferences")
            {

                var dt = new DataTable();

                dt.Columns.Add("SEQ_ID", typeof(int));                              // SEQ_ID
                dt.Columns.Add("MAIL_PREFERENCE_ID", typeof(string));               // MAIL_PREFERENCE_ID
                dt.Columns.Add("Mail Preference Description", typeof(string));      // MAIL_PREFERENCE_DESC
                dt.Columns.Add("Post", typeof(bool));                               // POST
                dt.Columns.Add("SMS", typeof(bool));                                // SMS
                dt.Columns.Add("Email", typeof(bool));                              // EMAIL
                dt.Columns.Add("Telephone", typeof(bool));                          // TELEPHONE

                foreach (DataRow row in datatable.Rows)
                {
                    dt.Rows.Add(row["SEQ_ID"].ToString(),
                                row["MAIL_PREFERENCE_ID"].ToString(),
                                row["MAIL_PREFERENCE_DESC"].ToString(),
                                Convert.ToBoolean(row["POST"]),
                                Convert.ToBoolean(row["SMS"]),
                                Convert.ToBoolean(row["EMAIL"]),
                                Convert.ToBoolean(row["TELEPHONE"]));
                }

                return dt;

            }

        }
        catch (Exception ex)
        {
            // catch and deal with my exception here
        }

        return null;
    }
</code>```

The above method is being called here and this is where I am having the issue of disabling cells.

```<code>private void PopulateMailPreferencesGV()
    {
        var dt = FilterData(_cAddPersonWizard.GetMailPreferneces(), "MailPreferences");
        dgvMailPreferences.DataSource = dt;

        dgvMailPreferences.Columns["Mail Preference Description"].Width = 250;
        dgvMailPreferences.Columns["Post"].Width = 50;
        dgvMailPreferences.Columns["SMS"].Width = 50;
        dgvMailPreferences.Columns["Email"].Width = 50;
        dgvMailPreferences.Columns["Telephone"].Width = 75;

        dgvMailPreferences.Columns["SEQ_ID"].Visible = false;
        dgvMailPreferences.Columns["MAIL_PREFERENCE_ID"].Visible = false;

        // not setting the datagridview cell to readonly
        foreach (DataGridViewRow row in dgvMailPreferences.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.GetType() == typeof(DataGridViewCheckBoxCell))
                {
                    if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)
                    {
                        ((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).ReadOnly = true;
                    }
                }
            }
        }

    }
</code>```

When stepping through and looking at the Watch window I can see that the read only properties are being set, however when coming to work with the DataGridView the cells are still active.

I would be grateful if someone could point me in the direction of where this code is wrong or if I need to do something else?

Thanks for your help.

--- Edit 31/05/2017

The image above shows the grid that I want to work with, the options that are selected are selected by default.

The options that are not selected are to be disabled because these forms of delivery are not possible for the mail type

答:
Try this

```<code>((DataGridViewCheckBoxCell)Rows[Index].Cells["colName"]).ReadOnly = true;
</code>```

Hopefully it will work for you.

Body:
I am working on an old .Net 2.0 WinForms project and need to set some cells to read only.

I have a DataTable that I am reading and setting as the DataSource and the field types are being set correctly

Generate DataTable and columns

public DataTable FilterData(DataTable datatable, string dataType)
    {
        try
        {
            if (dataType == "MailPreferences")
            {

                var dt = new DataTable();

                dt.Columns.Add("SEQ_ID", typeof(int));                              // SEQ_ID
                dt.Columns.Add("MAIL_PREFERENCE_ID", typeof(string));               // MAIL_PREFERENCE_ID
                dt.Columns.Add("Mail Preference Description", typeof(string));      // MAIL_PREFERENCE_DESC
                dt.Columns.Add("Post", typeof(bool));                               // POST
                dt.Columns.Add("SMS", typeof(bool));                                // SMS
                dt.Columns.Add("Email", typeof(bool));                              // EMAIL
                dt.Columns.Add("Telephone", typeof(bool));                          // TELEPHONE

                foreach (DataRow row in datatable.Rows)
                {
                    dt.Rows.Add(row["SEQ_ID"].ToString(),
                                row["MAIL_PREFERENCE_ID"].ToString(),
                                row["MAIL_PREFERENCE_DESC"].ToString(),
                                Convert.ToBoolean(row["POST"]),
                                Convert.ToBoolean(row["SMS"]),
                                Convert.ToBoolean(row["EMAIL"]),
                                Convert.ToBoolean(row["TELEPHONE"]));
                }

                return dt;

            }

        }
        catch (Exception ex)
        {
            // catch and deal with my exception here
        }

        return null;
    }

The above method is being called here and this is where I am having the issue of disabling cells.

private void PopulateMailPreferencesGV()
    {
        var dt = FilterData(_cAddPersonWizard.GetMailPreferneces(), "MailPreferences");
        dgvMailPreferences.DataSource = dt;

        dgvMailPreferences.Columns["Mail Preference Description"].Width = 250;
        dgvMailPreferences.Columns["Post"].Width = 50;
        dgvMailPreferences.Columns["SMS"].Width = 50;
        dgvMailPreferences.Columns["Email"].Width = 50;
        dgvMailPreferences.Columns["Telephone"].Width = 75;

        dgvMailPreferences.Columns["SEQ_ID"].Visible = false;
        dgvMailPreferences.Columns["MAIL_PREFERENCE_ID"].Visible = false;

        // not setting the datagridview cell to readonly
        foreach (DataGridViewRow row in dgvMailPreferences.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.GetType() == typeof(DataGridViewCheckBoxCell))
                {
                    if(((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).Selected == false)
                    {
                        ((DataGridViewCheckBoxCell)row.Cells[cell.ColumnIndex]).ReadOnly = true;
                    }
                }
            }
        }

    }

When stepping through and looking at the Watch window I can see that the read only properties are being set, however when coming to work with the DataGridView the cells are still active.

I would be grateful if someone could point me in the direction of where this code is wrong or if I need to do something else?

Thanks for your help.

--- Edit 31/05/2017

The image above shows the grid that I want to work with, the options that are selected are selected by default.

The options that are not selected are to be disabled because these forms of delivery are not possible for the mail type

Body:
Try this

((DataGridViewCheckBoxCell)Rows[Index].Cells["colName"]).ReadOnly = true;

Hopefully it will work for you.


问:
Load the same file using different data flow task with different script component
I have encountered a weird situation now.

Basically I have two data flow tasks in my SSIS package, these two tasks are loading the data to the same staging table. Each one is using the script component as the data source, and using the StreamReader on different two files.

If I enable two tasks at the same time, the 2nd data flow task loads the same data as the first one. But if I disable the 1st one and just leave the 2nd one enabled, it loads the correct file as expected.

I am not very sure what did I do wrong since all the StreamReader are defined on files with different names, the only common part is loading to the same destination.

And these two tasks are not in parallel, they are being constrained in sequence.

Any suggestion or advice? Thanks in advance.

答:
Thanks for the comments, actually I found why they are trying to load the same data when two connections are open at the same time. It is because I copied the 1st script component to the 2nd one, which sharing the same task ID within the container, I tested multiple times, it turned out to be if the task ID are the same, the 2nd one will do what the 1st does, basically it is just the replica task as the 1st one even the codes are different.

Please correct me if my findings are wrong, but it seems it is what it is during my past tests.


问:
Adding noise to image for deep learning, yes or no?
I've been thinking that adding noise to an image can prevent overfitting and also "increase" the dataset by adding variations to it. I'm only trying to add some random 1s to images that has shape (256,256,3) which uses uint8 to represent its color. I don't think that can affect the visualization at all (I showed both images with matplotlib and they seems almost the same) and has only ~0.01 mean difference in the sum of their values.

But it doesn't look to have its advances. After training for a long time it's still not as good as the one doesn't use noises.

Has anyone tried to use noise for image classification tasks like this? Is it eventually better?

答:
Yes you may add noise to extend your dataset and avoid overfitting your training set but make sure it is random otherwise your network will take this noise as something it should learn (and that's not something you want). I wouldn't use this method first to do that, I would first rotate and/or flip my samples.

However, your network should perform better or, at least, as well as your previous network.

First thing I would check is : How do you measure your performances ? What were your performances before and after ? And did you change anything else ?


问:
Manipulate the java class path of an Eclipse plugin?
I am working on a plugin that consist of a homemade view to Eclipse.
When I run the plugin and display the classpath using  System.getProperty("java.class.path")
I get this as output : D:\Programs\eclipse\plugins\org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar

I would like to add some .jar files for the proper functioning of my view, but I can't figure out how... I guess you can do it by adding some specifications to the MANIFEST.MF of the plugin but I don't know how to do it propely.
any ideas ?

答:
For Compile time we need to add it to the Project runtime library.

For the run time you have to package the jar either in your EAR/WAR file or Load it to the Application server as a App server libraries.

Please let me know if you need further assistance on this.


问:
PM2 NodeJs Cluster Mode
I have 4 ec2 instances running on AWS. PM2 is running in cluster mode on all instances. When I get 5K+ Concurrent request, response time of app increases significantly.

All requests fetch redis key, and a normal fetch takes upto 10 seconds which without so many concurrent requests takes only 50ms. What can be issue here?

答:
We need to pinpoint the bottleneck. Let's do some diagnostics:

Are the EC2 instances multicore to take advantage of PM2's clustering?

When you execute pm2 start app.js -i X are you sure X=number_of_vCPUs of EC2 instance?

When you execute pm2 monit do you see all instances of the cluster sharing the equal CPU and memory usage?

When you run htop what is your total CPU and memory usage %?

When you execute iftop what is your total of your RX and TX traffic compared to the maximum available in your machine?

Title: PM2 NodeJs Cluster Mode


问:
Execute multiple url
I have a little problem. I need to execute an script that execute 5000 URL in php.

```<code>$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}
</code>```

Any idea??

Thx.

答:
use CURL

LIKE :

```<code>$ch = curl_init();
while ($row = mysql_fetch_array($result)) {

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);
}
// close cURL resource, and free up system resources
curl_close($ch);
</code>```

Title: Execute multiple url

Body:
I have a little problem. I need to execute an script that execute 5000 URL in php.

$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}

Any idea??

Thx.

Body:
use CURL

LIKE :

$ch = curl_init();
while ($row = mysql_fetch_array($result)) {

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);
}
// close cURL resource, and free up system resources
curl_close($ch);


问:
mysql_secure_installation "Can't connect to local MySQL server through socket"
When I am invoking the file mysql_secure_installation I get an error like

```<code>    [mysqk123@InstallZeMo bin]$ ./mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Enter current password for root (enter for none):
</code>```

but the given sock file in my.cnf file is /home/mysqk123/tmp/mysql.sock and I am using redhat linux 5.3 and mysql 5.1.47

I know that the tasks performed by mysql_secure_installation script can be performed manually but here I have to run the script [ not allowed to do the task manually ]

答:
I had this same error happen, and it turns out I had stopped the MySQL service and forgotten to restart it. So you may want to check the status of the mysql service using a command like:

mysqladmin -u root -p status

If you get an error, it means MySQL is not running, and you can start the MySQL service. Or, if you prefer, you can recklessly attempt to start the service without first checking its status (which won't work if it's already running) using one of these commands:

```<code>/etc/init.d/mysql start
service mysql start
</code>```

Replace mysqld with mysqld if your system is using that version of MySQL.

ContentLicense: CC BY-SA 4.0

Body:
When I am invoking the file mysql_secure_installation I get an error like

    [mysqk123@InstallZeMo bin]$ ./mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Enter current password for root (enter for none):

but the given sock file in my.cnf file is /home/mysqk123/tmp/mysql.sock and I am using redhat linux 5.3 and mysql 5.1.47

I know that the tasks performed by mysql_secure_installation script can be performed manually but here I have to run the script [ not allowed to do the task manually ]

Body:
I had this same error happen, and it turns out I had stopped the MySQL service and forgotten to restart it. So you may want to check the status of the mysql service using a command like:

mysqladmin -u root -p status

If you get an error, it means MySQL is not running, and you can start the MySQL service. Or, if you prefer, you can recklessly attempt to start the service without first checking its status (which won't work if it's already running) using one of these commands:

/etc/init.d/mysql start
service mysql start

Replace mysqld with mysqld if your system is using that version of MySQL.


问:
Android application with switch statement crashes on my phone
When I run this code on my Android Phone, it keeps on crashing.

My java code is as follows

```<code>public class MainActivity extends Activity {

EditText edit = (EditText) findViewById(R.id.text);
Button button = (Button) findViewById(R.id.button);
String string = edit.getText().toString();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (string){
                case "c":
                    MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
                    mp1.start();
                    break;
</code>```

My XML code:

```<code><?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pembroke.com.example.algorhythmic.MainActivity">

<EditText
    android:id="@+id/box"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="308dp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.781" />
</code>```

The code is crashing, but I don't know why. I might not be using the string correctly.

No errors in the code but it is still crashing. Is it because the Android IDE can't compute my code?

答:
There are 3 problems with the code :

For doing the findViewById, we do this after setContentView in onCreate method of activity. This is because, before setContentView, all views are null. Hence, I moved the findViewById code for both EditText and button after setContentView(R.layout.activity_main) in onCreate method of activity.

For the edittext, the ID which you used is R.id.text in java code, but in xml, it is R.id.box. So I have changed that to R.id.box in java code when doing the findViewById.

To find the value present in EditText, we have to get text present in EditText inside the onClickListener since the value inside EditText keeps on changing as user enters inside EditText.
Hence we assign the value to variable string inside the onClickListener's onClick method.

So final code would be :

```<code>public class MainActivity extends Activity {

    EditText edit;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit  = (EditText) findViewById(R.id.box);
        button  = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String string = edit.getText().toString();
                switch (string){
                    case "c":
                        MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
                        mp1.start();
                        break;
           }
       }
    }
}
</code>```

Body:
When I run this code on my Android Phone, it keeps on crashing.

My java code is as follows

public class MainActivity extends Activity {

EditText edit = (EditText) findViewById(R.id.text);
Button button = (Button) findViewById(R.id.button);
String string = edit.getText().toString();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (string){
                case "c":
                    MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
                    mp1.start();
                    break;

My XML code:

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pembroke.com.example.algorhythmic.MainActivity">

<EditText
    android:id="@+id/box"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="308dp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.781" />

The code is crashing, but I don't know why. I might not be using the string correctly.

No errors in the code but it is still crashing. Is it because the Android IDE can't compute my code?

Body:
There are 3 problems with the code :

For doing the findViewById, we do this after setContentView in onCreate method of activity. This is because, before setContentView, all views are null. Hence, I moved the findViewById code for both EditText and button after setContentView(R.layout.activity_main) in onCreate method of activity.

For the edittext, the ID which you used is R.id.text in java code, but in xml, it is R.id.box. So I have changed that to R.id.box in java code when doing the findViewById.

To find the value present in EditText, we have to get text present in EditText inside the onClickListener since the value inside EditText keeps on changing as user enters inside EditText.
Hence we assign the value to variable string inside the onClickListener's onClick method.

So final code would be :

public class MainActivity extends Activity {

    EditText edit;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit  = (EditText) findViewById(R.id.box);
        button  = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String string = edit.getText().toString();
                switch (string){
                    case "c":
                        MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sample1);
                        mp1.start();
                        break;
           }
       }
    }
}


问:
IIS rewrite module canonical URL with two domains
I have a webserver and I have two domains with name http://example.mx and http://example.com.mx both are pointing to the same webserver and root folder, I can use my website with both domains and for the moment I can use www. as well but this is what I want to remove, I did it and I got this web.config file

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <remove name="CGI-exe" />
            <add name="CGI-exe" path="*.exe" verb="*" modules="CgiModule" resourceType="File" requireAccess="Script" allowPathInfo="true" />
        </handlers>
        <rewrite>
            <rules>
                <rule name="CanonicalHostNameRule2" enabled="false">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example\.com\.mx$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.com.mx/{R:1}" />
                </rule>
                <rule name="CanonicalHostNameRule1" enabled="false">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example\.mx$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.mx/{R:1}" />
                </rule>
                <rule name="http a https" enabled="false" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

But the problem is the I go to http://example.mx it sends me to http://example.com.mx and it suppose to works like this:

If I go to http://www.example.mx redirects to http://example.mx

If I go to http://www.example.com.mx redirects to http://example.com.mx

but right now if I go to http://www.example.mx it redirects to http://example.com.mx and I dont want this, What I need to change in the pattern?

答:
You should use this rules:</p>

```<code><rule name="CanonicalHostNameRule2">
    <match url="(.*)" />
    <conditions>
         <add input="{HTTP_HOST}" pattern="^www\.example\.com\.mx$"/>
    </conditions>
    <action type="Redirect" url="http://example.com.mx/{R:1}" />
</rule>
<rule name="CanonicalHostNameRule1">
    <match url="(.*)" />
    <conditions>
         <add input="{HTTP_HOST}" pattern="^www\.example\.mx$" />
    </conditions>
    <action type="Redirect" url="http://example.mx/{R:1}" />
</rule>
</code>```

Body:
I have a webserver and I have two domains with name http://example.mx and http://example.com.mx both are pointing to the same webserver and root folder, I can use my website with both domains and for the moment I can use www. as well but this is what I want to remove, I did it and I got this web.config file

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <remove name="CGI-exe" />
            <add name="CGI-exe" path="*.exe" verb="*" modules="CgiModule" resourceType="File" requireAccess="Script" allowPathInfo="true" />
        </handlers>
        <rewrite>
            <rules>
                <rule name="CanonicalHostNameRule2" enabled="false">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example\.com\.mx$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.com.mx/{R:1}" />
                </rule>
                <rule name="CanonicalHostNameRule1" enabled="false">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example\.mx$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.mx/{R:1}" />
                </rule>
                <rule name="http a https" enabled="false" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

But the problem is the I go to http://example.mx it sends me to http://example.com.mx and it suppose to works like this:

If I go to http://www.example.mx redirects to http://example.mx

If I go to http://www.example.com.mx redirects to http://example.com.mx

but right now if I go to http://www.example.mx it redirects to http://example.com.mx and I dont want this, What I need to change in the pattern?

Body:
You should use this rules:

<rule name="CanonicalHostNameRule2">
    <match url="(.*)" />
    <conditions>
         <add input="{HTTP_HOST}" pattern="^www\.example\.com\.mx$"/>
    </conditions>
    <action type="Redirect" url="http://example.com.mx/{R:1}" />
</rule>
<rule name="CanonicalHostNameRule1">
    <match url="(.*)" />
    <conditions>
         <add input="{HTTP_HOST}" pattern="^www\.example\.mx$" />
    </conditions>
    <action type="Redirect" url="http://example.mx/{R:1}" />
</rule>


问:
Is it possible to store tweets in csv file?
Successfully fetched more than 100 tweets but now i am unable to store those tweets in .csv file ?
Tried for File Handling classes so how can I store the tweets?

```<code>public class SentimentAnalysisWithCount {

DoccatModel model;
static int positive = 0;
static int negative = 0;

public static void main(String[] args) throws IOException, TwitterException {
    String line = "";
    SentimentAnalysisWithCount twitterCategorizer = new SentimentAnalysisWithCount();
    twitterCategorizer.trainModel();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("--------------------------------------------------")
        .setOAuthConsumerSecret("--------------------------------------------------")
        .setOAuthAccessToken("--------------------------------------------------")
        .setOAuthAccessTokenSecret("--------------------------------------------------");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    Query query = new Query("udta punjab");
    QueryResult result = twitter.search(query);
    int result1 = 0;
    for (Status status : result.getTweets()) {
        result1 = twitterCategorizer.classifyNewTweet(status.getText());
        if (result1 == 1) {
            positive++;
        } else {
            negative++;
        }
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"));
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();
}

public void trainModel() {
    InputStream dataIn = null;
    try {
        dataIn = new FileInputStream("C:\\Users\\User\\Downloads\\tweets.txt");
        ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
        ObjectStream sampleStream = new DocumentSampleStream(lineStream);
        // Specifies the minimum number of times a feature must be seen
        int cutoff = 2;
        int trainingIterations = 30;
        model = DocumentCategorizerME.train("en", sampleStream, cutoff,
                trainingIterations);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public int classifyNewTweet(String tweet) throws IOException {
    DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
    double[] outcomes = myCategorizer.categorize(tweet);
    String category = myCategorizer.getBestCategory(outcomes);

    System.out.print("-----------------------------------------------------\nTWEET :" + tweet + " ===> ");
    if (category.equalsIgnoreCase("1")) {
        System.out.println(" POSITIVE ");
        return 1;
    } else {
        System.out.println(" NEGATIVE ");
        return 0;
    }

}
}
</code>```

In this code the tweet which is being displayed on the console that should be stored in .csv file

答:
Please remove your API keys from Stackoverflow. You should not post them in public.

Storing tweets in a CSV is possible and you simply have to enhance your posted code-fragment by adapting the written output. The following code-snippet should give an idea on how to implement it in Java 8:

```<code>    try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"))) {

    int positive = 0;
    int negative = 0;

    StringBuilder sb = new StringBuilder();
    for (Status status : result.getTweets()) {
        String tweetText = status.getText();
        long tweetId = status.getId();
        int classificationResult = twitterCategorizer.classifyNewTweet(tweetText);

        if (classificationResult == 1) {
            positive++;
        } else {
            negative++;
        }

        sb.append("ID=").append(tweetId).append(",TEXT=").append(tweetText).append(",classificationResult=").append(classificationResult);

        String csvText = sb.toString();

        bw.write(csvText);
        bw.newLine();

        sb.delete(0,csvText);

    }

    bw.write("##### SUMMARY #####")
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();

    }catch(IOException e) {
         //TODO Exception Handling
    }
</code>```

results.csv would look like:

```<code>ID=25125125,TEXT=some fancy text here,classificationResult=1
ID=25146734725,TEXT=some fancy text1 here,classificationResult=0
ID=25127575125,TEXT=some fancy text2 here,classificationResult=1
ID=251258979125,TEXT=some fancy text3 here,classificationResult=0
ID=25125867125,TEXT=some fancy text4 here,classificationResult=1
##### SUMMARY #####
Positive Tweets,3
Negative Tweets,2
</code>```

Body:
Successfully fetched more than 100 tweets but now i am unable to store those tweets in .csv file ?
Tried for File Handling classes so how can I store the tweets?

public class SentimentAnalysisWithCount {

DoccatModel model;
static int positive = 0;
static int negative = 0;

public static void main(String[] args) throws IOException, TwitterException {
    String line = "";
    SentimentAnalysisWithCount twitterCategorizer = new SentimentAnalysisWithCount();
    twitterCategorizer.trainModel();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("--------------------------------------------------")
        .setOAuthConsumerSecret("--------------------------------------------------")
        .setOAuthAccessToken("--------------------------------------------------")
        .setOAuthAccessTokenSecret("--------------------------------------------------");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    Query query = new Query("udta punjab");
    QueryResult result = twitter.search(query);
    int result1 = 0;
    for (Status status : result.getTweets()) {
        result1 = twitterCategorizer.classifyNewTweet(status.getText());
        if (result1 == 1) {
            positive++;
        } else {
            negative++;
        }
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"));
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();
}

public void trainModel() {
    InputStream dataIn = null;
    try {
        dataIn = new FileInputStream("C:\\Users\\User\\Downloads\\tweets.txt");
        ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
        ObjectStream sampleStream = new DocumentSampleStream(lineStream);
        // Specifies the minimum number of times a feature must be seen
        int cutoff = 2;
        int trainingIterations = 30;
        model = DocumentCategorizerME.train("en", sampleStream, cutoff,
                trainingIterations);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public int classifyNewTweet(String tweet) throws IOException {
    DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
    double[] outcomes = myCategorizer.categorize(tweet);
    String category = myCategorizer.getBestCategory(outcomes);

    System.out.print("-----------------------------------------------------\nTWEET :" + tweet + " ===> ");
    if (category.equalsIgnoreCase("1")) {
        System.out.println(" POSITIVE ");
        return 1;
    } else {
        System.out.println(" NEGATIVE ");
        return 0;
    }

}
}

In this code the tweet which is being displayed on the console that should be stored in .csv file

Body:
Please remove your API keys from Stackoverflow. You should not post them in public.

Storing tweets in a CSV is possible and you simply have to enhance your posted code-fragment by adapting the written output. The following code-snippet should give an idea on how to implement it in Java 8:

    try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"))) {

    int positive = 0;
    int negative = 0;

    StringBuilder sb = new StringBuilder();
    for (Status status : result.getTweets()) {
        String tweetText = status.getText();
        long tweetId = status.getId();
        int classificationResult = twitterCategorizer.classifyNewTweet(tweetText);

        if (classificationResult == 1) {
            positive++;
        } else {
            negative++;
        }

        sb.append("ID=").append(tweetId).append(",TEXT=").append(tweetText).append(",classificationResult=").append(classificationResult);

        String csvText = sb.toString();

        bw.write(csvText);
        bw.newLine();

        sb.delete(0,csvText);

    }

    bw.write("##### SUMMARY #####")
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();

    }catch(IOException e) {
         //TODO Exception Handling
    }

results.csv would look like:

ID=25125125,TEXT=some fancy text here,classificationResult=1
ID=25146734725,TEXT=some fancy text1 here,classificationResult=0
ID=25127575125,TEXT=some fancy text2 here,classificationResult=1
ID=251258979125,TEXT=some fancy text3 here,classificationResult=0
ID=25125867125,TEXT=some fancy text4 here,classificationResult=1
##### SUMMARY #####
Positive Tweets,3
Negative Tweets,2


问:
CSS two divs next to each other (w/o line break)
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

```<code>    <hr class="hr--small">
    <div class="grid">

    <div class="grid__item text-left">
      <p class="site-footer__links">{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved
      </p>
    </div>

    <div class="grid__item text-right">
      <p class="site-footer__links">
        <a href="http://www.w3schools.com/html/">Privacy Policy</a> •
        <a href="http://www.w3schools.com/html/">Terms & Conditions</a>
      </p>
    </div>
</code>```

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.

答: You can use a table element to control this layout. See example.

Body:
I want to put 2
s next to each other. How can I do this?
Both should be 50% width. Can someone help correct my code?

This is the code:

{{ 'layout.footer.copyright' | t }} ©
      {{ 'now' | date: "%Y" }} {{ shop.name | link_to: '/' }} • All Rights Reserved

        Privacy Policy •
        Terms & Conditions

At the moment they appear correctly left & right, but with line break. Just want them to appear on the same line.


问:
WPF - MenuItem missing Icon/Image
Im getting menuItem icon appearing only on last menuItem.
If i snoop the app only last menuItem has image in icon, while if i debug all MenuItems appear to have image in icon. Also if i add submenuItem the icon on menuItem dissapears once i open submenus and the last submenu gets the icon... Any idea? PS: also tooltips on menu item dont work.
Im using caliburn micro and fluent ribbon controls.</p>

```<code>        <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="Header"
                            Value="{Binding DisplayName}"/>
                    <Setter Property="Icon">
                        <Setter.Value>
                            <Image Source="{Binding Path=IconPath}"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ItemsSource"
                            Value="{Binding Items}"/>
                    <Setter Property="cm:Message.Attach"
                            Value="ClickAction()"/>
                    <Setter Property="ef:KeyTip.Keys"
                            Value="{Binding KeyTip}"/>
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ef:ScreenTip Title="{Binding DisplayName}"
                                          HelpTopic="ScreenTip help ..."
                                          Image="{Binding LargeIconPath}"
                                          Text="Text for ScreenTip"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>
</code>```

答:
Works like this:</p>

```<code>       <DataTemplate x:Key="MenuItemHeaderTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Image Grid.Column="0" Source="{Binding Path=IconPath}" />
            <Label Grid.Column="1" Content="{Binding DisplayName}" />
        </Grid>
    </DataTemplate>

    <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="HeaderTemplate" Value="{StaticResource MenuItemHeaderTemplate}" />
                    <Setter Property="ItemsSource"
                            Value="{Binding Items}"/>
                    <Setter Property="cm:Message.Attach"
                            Value="ClickAction()"/>
                    <Setter Property="ef:KeyTip.Keys"
                            Value="{Binding KeyTip}"/>
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ef:ScreenTip Title="{Binding DisplayName}"
                                          HelpTopic="ScreenTip help ..."
                                          Image="{Binding LargeIconPath}"
                                          Text="Text for ScreenTip"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>
</code>```

Title: WPF - MenuItem missing Icon/Image

Body:
Im getting menuItem icon appearing only on last menuItem.
If i snoop the app only last menuItem has image in icon, while if i debug all MenuItems appear to have image in icon. Also if i add submenuItem the icon on menuItem dissapears once i open submenus and the last submenu gets the icon... Any idea? PS: also tooltips on menu item dont work.
Im using caliburn micro and fluent ribbon controls.

        <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>

            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>

Body:
Works like this:

       <DataTemplate x:Key="MenuItemHeaderTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Image Grid.Column="0" Source="{Binding Path=IconPath}" />
            <Label Grid.Column="1" Content="{Binding DisplayName}" />
        </Grid>
    </DataTemplate>

    <ControlTemplate x:Key="dropDownButton">
        <ef:DropDownButton Header="{Binding DisplayName}"
                           ItemsSource="{Binding Items}"
                           LargeIcon="{Binding LargeIconPath}"
                           cm:Message.Attach="ClickAction()"
                           ef:KeyTip.Keys="{Binding KeyTip}">
            <ef:DropDownButton.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="HeaderTemplate" Value="{StaticResource MenuItemHeaderTemplate}" />
                    <Setter Property="ItemsSource"
                            Value="{Binding Items}"/>
                    <Setter Property="cm:Message.Attach"
                            Value="ClickAction()"/>
                    <Setter Property="ef:KeyTip.Keys"
                            Value="{Binding KeyTip}"/>
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ef:ScreenTip Title="{Binding DisplayName}"
                                          HelpTopic="ScreenTip help ..."
                                          Image="{Binding LargeIconPath}"
                                          Text="Text for ScreenTip"/>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ef:DropDownButton.ItemContainerStyle>
            <ef:DropDownButton.ToolTip>
                <ef:ScreenTip Title="{Binding DisplayName}"
                              HelpTopic="ScreenTip help ..."
                              Image="{Binding LargeIconPath}"
                              Text="Text for ScreenTip"/>
            </ef:DropDownButton.ToolTip>
        </ef:DropDownButton>


问:
How to unit 2 or more Data Series in group by One Chart C#
Develop a chart in C #, this is filled automatically with a sp. The sp spreads cities with totals that month are filtered, as I show in the image.

Within my Chart, I add 2 sets of data although they may be more in the future. The problem is not to add the series of data, but how to respect the order of the data, if I add the series of data as secondary, it does perfectly, but I do not group them but transpose them and I do not respect the Order of the same.

I would like to know if any of you know how to do this, I have already verified on the internet and I can not find information. I add the sp who throw me the information, I also throw them as I group the data in the chart and as I would like to be grouped regardless of whether in the following month there would be more cities.

This code add data series to chart

```<code>conexion_server.PreparaComandoSP("sp_telemetria_camiones_Km_Mes_Actual");
            conexion_server.AgregarParametro("Mes", SqlDbType.VarChar, strmes);
            mes_actual = conexion_server.EjecutaComandoDataSet();
            graf_km_camiones_comparativo.Titles.Add("Comparativa KMS entre Camiones \\n" + strmes + " VS " + strmes_comparativo).Font = new Font("Arial", 12, FontStyle.Bold);
            graf_km_camiones_comparativo.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
            graf_km_camiones_comparativo.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
            graf_km_camiones_comparativo.Series["Series1"].ToolTip = "(#VALX, #VALY)";
            graf_km_camiones_comparativo.Series["Series2"].ToolTip = "(#VALX, #VALY)";
            graf_km_camiones_comparativo.Series["Series1"].LegendText = strmes;
            graf_km_camiones_comparativo.Series["Series2"].LegendText = strmes_comparativo;
            graf_km_camiones_comparativo.Legends["Legend1"].Title = "Segmentación";
            foreach (DataRow row in mes_actual.Tables[0].Rows)
            {
                graf_km_camiones_comparativo.Series["Series1"].Points.AddXY(row["CeEmplazamiento"], row["Totales"]);

                graf_km_camiones_comparativo.Series["Series1"].Label = "#VALY";
            }

Thank you.
</code>```

答:
Thanks to everybody for your comments, this was my solution.
1.- To créate a unión between the queries, because isn't posible to organize the series without a query.
2.- The Chart  was fill with a foreach.

e

```<code>,final_comparativo as (
                    select s.CeEmplazamiento, avg(s.Totales) TotalGeneral , s2.TotGral, @Mes as Mes
                    from tmpSemanas s
                        cross join ( select avg(Totales) TotGral from tmpSemanas s2 where Totales >0) s2
                    group by s.CeEmplazamiento , s2.TotGral
            union all
                    select ss.CeEmplazamiento, avg(ss.Totales) TotalGeneral , ss2.TotGral, @Mes_comparar as Mes
                    from tmpSemanas_comparar ss
                        cross join ( select avg(Totales) TotGral from tmpSemanas_comparar ss2 where Totales >0) ss2
                    group by ss.CeEmplazamiento , ss2.TotGral
        )

**CeEmplazamiento   Diciembre   Enero**
Celaya          76.500000   75.600000
Coecillo            79.000000   79.800000
Irapuato            77.500000   75.400000
León Sur            85.750000   87.600000
Los Reyes            0.000000   0.000000
Oriente León    86.250000   85.200000
Texcoco          0.000000   0.000000
</code>```

Thanks to everybody

Body:
Develop a chart in C #, this is filled automatically with a sp. The sp spreads cities with totals that month are filtered, as I show in the image.

Within my Chart, I add 2 sets of data although they may be more in the future. The problem is not to add the series of data, but how to respect the order of the data, if I add the series of data as secondary, it does perfectly, but I do not group them but transpose them and I do not respect the Order of the same.

I would like to know if any of you know how to do this, I have already verified on the internet and I can not find information. I add the sp who throw me the information, I also throw them as I group the data in the chart and as I would like to be grouped regardless of whether in the following month there would be more cities.

This code add data series to chart

conexion_server.PreparaComandoSP("sp_telemetria_camiones_Km_Mes_Actual");
            conexion_server.AgregarParametro("Mes", SqlDbType.VarChar, strmes);
            mes_actual = conexion_server.EjecutaComandoDataSet();
            graf_km_camiones_comparativo.Titles.Add("Comparativa KMS entre Camiones \\n" + strmes + " VS " + strmes_comparativo).Font = new Font("Arial", 12, FontStyle.Bold);
            graf_km_camiones_comparativo.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
            graf_km_camiones_comparativo.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
            graf_km_camiones_comparativo.Series["Series1"].ToolTip = "(#VALX, #VALY)";
            graf_km_camiones_comparativo.Series["Series2"].ToolTip = "(#VALX, #VALY)";
            graf_km_camiones_comparativo.Series["Series1"].LegendText = strmes;
            graf_km_camiones_comparativo.Series["Series2"].LegendText = strmes_comparativo;
            graf_km_camiones_comparativo.Legends["Legend1"].Title = "Segmentación";
            foreach (DataRow row in mes_actual.Tables[0].Rows)
            {
                graf_km_camiones_comparativo.Series["Series1"].Points.AddXY(row["CeEmplazamiento"], row["Totales"]);

                graf_km_camiones_comparativo.Series["Series1"].Label = "#VALY";
            }

Thank you.

Body:
Thanks to everybody for your comments, this was my solution.
1.- To créate a unión between the queries, because isn't posible to organize the series without a query.
2.- The Chart  was fill with a foreach.

e

,final_comparativo as (
                    select s.CeEmplazamiento, avg(s.Totales) TotalGeneral , s2.TotGral, @Mes as Mes
                    from tmpSemanas s
                        cross join ( select avg(Totales) TotGral from tmpSemanas s2 where Totales >0) s2
                    group by s.CeEmplazamiento , s2.TotGral
            union all
                    select ss.CeEmplazamiento, avg(ss.Totales) TotalGeneral , ss2.TotGral, @Mes_comparar as Mes
                    from tmpSemanas_comparar ss
                        cross join ( select avg(Totales) TotGral from tmpSemanas_comparar ss2 where Totales >0) ss2
                    group by ss.CeEmplazamiento , ss2.TotGral
        )

**CeEmplazamiento   Diciembre   Enero**
Celaya          76.500000   75.600000
Coecillo            79.000000   79.800000
Irapuato            77.500000   75.400000
León Sur            85.750000   87.600000
Los Reyes            0.000000   0.000000
Oriente León    86.250000   85.200000
Texcoco          0.000000   0.000000

Thanks to everybody


问:
R Leaflet: Is it possible to have a two column layer control panel?
I have a leaflet map with 75 overlay groups that I want to turn visible/invisible using the layer control panel. The problem is, that with that amount of groups my layer control panel reaches the end of my map and therefore not all of the groups are visible in the layers control panel.

The following minimal reproducible example shows the problem in detail:

```<code>library(leaflet)
leaflet(width = 400, height = 100) %>%
  addTiles() %>%
  # Overlay groups
  addCircleMarkers(lng = 9, lat = 47, color = 'red', group = 'red') %>%
  addCircleMarkers(lng = 8, lat = 46, color = 'blue', group = 'blue') %>%
  addCircleMarkers(lng = 8, lat = 47, color = 'green', group = 'green') %>%
  addCircleMarkers(lng = 9, lat = 46, color = 'yellow', group = 'yellow') %>%
  addCircleMarkers(lng = 8.5, lat = 46.5, color = 'purple', group = 'purple') %>%
  # Layers control
  addLayersControl(
    overlayGroups = c('red', 'green', 'blue', 'yellow', 'purple'),
    options = layersControlOptions(collapsed = TRUE))
</code>```

This leads to the following map where the purple point is not available on the layers control panel

Is there a possibility to force the layers control panel to arrange the layers in more than one column?

答:
Following @symbolrush's answer, the  section may need to be edited a little if it already contains parameters.

Before (html file created by leaflet):

```<code>...
</head>
<body style="background-color:white;">
<div id="htmlwidget_container">
...
</code>```

After @symbolrush's edits:

```<code>...
</head>
<body>
<style="background-color:white;"></style> #might not be necessary
<style type="text/css">
      .leaflet-control-layers {
        max-height: 600px;
        overflow: auto;
      }
    </style>
<div id="htmlwidget_container">
...
</code>```

Body:
I have a leaflet map with 75 overlay groups that I want to turn visible/invisible using the layer control panel. The problem is, that with that amount of groups my layer control panel reaches the end of my map and therefore not all of the groups are visible in the layers control panel.

The following minimal reproducible example shows the problem in detail:

library(leaflet)
leaflet(width = 400, height = 100) %>%
  addTiles() %>%
  # Overlay groups
  addCircleMarkers(lng = 9, lat = 47, color = 'red', group = 'red') %>%
  addCircleMarkers(lng = 8, lat = 46, color = 'blue', group = 'blue') %>%
  addCircleMarkers(lng = 8, lat = 47, color = 'green', group = 'green') %>%
  addCircleMarkers(lng = 9, lat = 46, color = 'yellow', group = 'yellow') %>%
  addCircleMarkers(lng = 8.5, lat = 46.5, color = 'purple', group = 'purple') %>%
  # Layers control
  addLayersControl(
    overlayGroups = c('red', 'green', 'blue', 'yellow', 'purple'),
    options = layersControlOptions(collapsed = TRUE))

This leads to the following map where the purple point is not available on the layers control panel

Is there a possibility to force the layers control panel to arrange the layers in more than one column?

Body:
Following @symbolrush's answer, the <body> section may need to be edited a little if it already contains parameters.

Before (html file created by leaflet):

...
</head>
<body style="background-color:white;">
<div id="htmlwidget_container">
...

After @symbolrush's edits:

...
</head>
<body>
<style="background-color:white;"></style> #might not be necessary
<style type="text/css">
      .leaflet-control-layers {
        max-height: 600px;
        overflow: auto;
      }
    </style>
<div id="htmlwidget_container">
...


问:
'render' is not defined when running create react app
When I am using create react app when compliling I get the following errors ./src/Grid.js
 "Line 3:  Your render method should have return statement" and "Line 5:  'render' is not defined"
this is the contents of the the Grid.js file

```<code>import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return <p>Hello, World</p>;
    }
}

export default Grid;
</code>```

I can't see that is wrong here? any help appreciated

```<code>import React, { Component } from 'react';
import Grid from './Grid.js';

class App extends Component
{
  render()
  {
    return(
      <div>
        <Grid />
      </div>
    );
  }
}

export default App;
</code>```

This is where I am using the component

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
</code>```

Where ReactDOM render is used

答: Still no real explanation for this. Copying the component code in to a newly created file compiles correctly. Very strange indeed.</p>

Body:
When I am using create react app when compliling I get the following errors ./src/Grid.js
 "Line 3:  Your render method should have return statement" and "Line 5:  'render' is not defined"
this is the contents of the the Grid.js file

import React, { Component } from 'react';

class Grid extends Component {
    render(){
        return
Hello, World
;
    }
}

export default Grid;

I can't see that is wrong here? any help appreciated

import React, { Component } from 'react';
import Grid from './Grid.js';

class App extends Component
{
  render()
  {
    return(

        <Grid />

    );
  }
}

export default App;

This is where I am using the component

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Where ReactDOM render is used


问:
Access to private methods in private class
How can I have access to a private method in a private class?

My code:

```<code>public class OuterClass {

    private InnerClass ic;

    public OuterClass(){ //Constructor
        this.ic = new InnerClass();
    }

    public InnerClass getInnerClass(){
        return this.ic;
    }

    private class InnerClass {
        private VeryInnerClass vic;

        private void InnerClass(){
            this.vic = new VeryInnerClass();
        }

        private void method(Object item){
            //Job
        }

        private class VeryInnerClass {
            private Object item;

            private void VeryInnerClass(){
                //Constructor
            }

        }//End VeryInnerClass

    }//End InnerClass

}//End OuterClass
</code>```

This is the main code:

```<code>public class Main {

    public static void main(String[] args) {

        OuterClass oc = new OuterClass();
        Object item = new Object();

        oc.getInnerClass().method(item);

    }

}
</code>```

The error is that the type OuterClass.InnerClass is not visible, but I used a getInnerClass() method, so I don't know how to have access to method(Object item).

答: You can't direct access private method / private inner class outside  of the scope of the class.</p>

Body:
How can I have access to a private method in a private class?

My code:

public class OuterClass {

    private InnerClass ic;

    public OuterClass(){ //Constructor
        this.ic = new InnerClass();
    }

    public InnerClass getInnerClass(){
        return this.ic;
    }

    private class InnerClass {
        private VeryInnerClass vic;

        private void InnerClass(){
            this.vic = new VeryInnerClass();
        }

        private void method(Object item){
            //Job
        }

        private class VeryInnerClass {
            private Object item;

            private void VeryInnerClass(){
                //Constructor
            }

        }//End VeryInnerClass

    }//End InnerClass

}//End OuterClass

This is the main code:

public class Main {

    public static void main(String[] args) {

        OuterClass oc = new OuterClass();
        Object item = new Object();

        oc.getInnerClass().method(item);

    }

}

The error is that the type OuterClass.InnerClass is not visible, but I used a getInnerClass() method, so I don't know how to have access to method(Object item).


问:
Disabling ajax on HTTP 302 in jQueryMobile
In jQueryMobile, is there a way to disable ajax pages loading when the server respond HTTP 302 ?

I have a login page (mydomain.tld/login) with specific javascript library on this page (and only on this page). When a user is logged in, and session expire, the user is redirected by the Silex framework to the login page when he try to access new content (mydomain.tld/mycontent --> mydomain.tld/login). Normal.

Problem : loading of the login page failed because jQueryMobile try to load this page with ajax, so the specific JS library for the login page is not loaded (jQueryMobile insert only page content into the DOM) and so the login page failed to initialize without this library...

I don't wan't to load this specific library on all pages for efficiency reasons (this library is usefull on login, useless on all the rest of the site).

I don't really want to disable ajax loading of pages for all the site...

Is there a way to disable ajax loading only when the server respond a HTTP 302 or disable ajax for a specific page (param in mobileinit ?)

Thank in advance for your ideas and suggestions...

答:
or you can disable request before the route :</p>

```<code>$app->before(function(Request $request, Application $app)) {
   if ($request->isXmlHttpRequest() && $request->headers->get('User-Agent') == 'mobile header') {
     return $app->json(array('error' => 'Authentication failed'));
   }
});
</code>```

Body:
or you can disable request before the route :

$app->before(function(Request $request, Application $app)) {
   if ($request->isXmlHttpRequest() && $request->headers->get('User-Agent') == 'mobile header') {
     return $app->json(array('error' => 'Authentication failed'));
   }
});