问:
Javascript - Find if number is positive or negative
I see other solutions to my question but none that help me.

I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.

Also, prompt the user again and again if anything other than a number is entered

Here's the code so far

When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1

```<code>function isPositive(num) {

    var result;

    if (num >= 0) {
        result = true;
    } else if (num < 0) {
        result = false;
    }
    return result;
}

var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
    alert(isPositive(num));

    if (isNaN(num)) {
        alert("No number entered. Try again");
        num = parseInt(prompt("Enter a number"));
        isPositive(num);
        while (num != -1) {
            alert(isPositive(num));
        }
    }
}
</code>```

答:
```<code>Math.sign(number)
</code>```

which returns either a 1, -1 or 0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

Body:
I see other solutions to my question but none that help me.

I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.

Also, prompt the user again and again if anything other than a number is entered

Here's the code so far

When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1

function isPositive(num) {

    var result;

    if (num >= 0) {
        result = true;
    } else if (num < 0) {
        result = false;
    }
    return result;
}

var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
    alert(isPositive(num));

    if (isNaN(num)) {
        alert("No number entered. Try again");
        num = parseInt(prompt("Enter a number"));
        isPositive(num);
        while (num != -1) {
            alert(isPositive(num));
        }
    }
}

Body:
Math.sign(number)

which returns either a 1, -1 or 0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign


来源: stackexchange

问:
Configure the firestore security rules to allow users to only access their own data - efficiently
Using firestore with angularfire2 rc 2.

All is working very nicely in development with no effective security rules.

These are the no security rules - where the client code will create, update and delete collections below the $COLLECTION_NAME/document without issue.

```<code>service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if true;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if true;
        }
    }
}
</code>```

Where I want to get to is to only allow users to access their own data.

I started out with the following rules:

```<code>service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
    }
}
</code>```

However, as soon as I add any sort of restrictive rule including even just validating the request is authorised.

```<code>match /databases/{database}/documents {
    match /collectionA/{userId=**} {
       allow read, write: if request.auth;
    }
    match /collectionB/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionC/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionD/{userId=**}  {
         allow read, write: if request.auth;
    }
}
</code>```

I get code permission errors.

[code=permission-denied]: Missing or insufficient permissions.

FirebaseError: Missing or insufficient permissions.

Each {userId} document contains a collection which in turn contains documents so a full path might be something like

```<code>const entryCollection: AngularFirestoreCollection<Entry> = this.angularfirestore.collection('collectionC/' + user.uid + '/records' + '/2017-40' + '/entries');
</code>```

The requests should be authenticated as the access is only granted in the client following authentication using firebase authentication. Logging indicates the uid is present and indeed when creating the document below collectionA or B or C or D the user.uid document is named using the uid.

答:
I resolved this issue like this.</p>

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
       match /{allSubcollections=**} {
        allow read, write: if request.auth.uid == userId;
      }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using firestore with angularfire2 rc 2.

All is working very nicely in development with no effective security rules.

These are the no security rules - where the client code will create, update and delete collections below the $COLLECTION_NAME/document without issue.

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if true;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if true;
        }
    }
}

Where I want to get to is to only allow users to access their own data.

I started out with the following rules:

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
    }
}

However, as soon as I add any sort of restrictive rule including even just validating the request is authorised.

match /databases/{database}/documents {
    match /collectionA/{userId=**} {
       allow read, write: if request.auth;
    }
    match /collectionB/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionC/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionD/{userId=**}  {
         allow read, write: if request.auth;
    }
}

I get code permission errors.

[code=permission-denied]: Missing or insufficient permissions.

FirebaseError: Missing or insufficient permissions.

Each {userId} document contains a collection which in turn contains documents so a full path might be something like

const entryCollection: AngularFirestoreCollection<Entry> = this.angularfirestore.collection('collectionC/' + user.uid + '/records' + '/2017-40' + '/entries');

The requests should be authenticated as the access is only granted in the client following authentication using firebase authentication. Logging indicates the uid is present and indeed when creating the document below collectionA or B or C or D the user.uid document is named using the uid.

Body:
I resolved this issue like this.

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
       match /{allSubcollections=**} {
        allow read, write: if request.auth.uid == userId;
      }
    }
  }
}


问:
Php make soap request
I trying to make soap request to Amadeus Web Service. I have xml file with soap-header

```<code><?xml version="1.0"?>
<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <add:MessageID xmlns:add="http://www.w3.org/2005/08/addressing">dbbb6ca5-e5d4-7518-d84-f6f7c22ed752</add:MessageID>
  <add:Action xmlns:add="http://www.w3.org/2005/08/addressing">http://webservices.amadeus.com/Hotel_MultiSingleAvailability_10.0</add:Action>
  <add:To xmlns:add="http://www.w3.org/2005/08/addressing">https://nodeD1.test.webservices.amadeus.com/1ASIWOTANA8</add:To>
  <link:TransactionFlowLink xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1"/>
  <oas:Security xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
    <oas:UsernameToken xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" oas1:Id="UsernameToken-1">
      <oas:Username>WSNA8OTA</oas:Username>
      <oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"nonce</oas:Nonce>
      <oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">pass</oas:Password>
      <oas1:Created>2017-11-09T08:50:40.588Z</oas1:Created>
    </oas:UsernameToken>
  </oas:Security>
  <AMA_SecurityHostedUser xmlns="http://xml.amadeus.com/2010/06/Security_v1">
    <UserID POS_Type="1" PseudoCityCode="MIA1S38BL" AgentDutyCode="SU" RequestorType="U"/>
  </AMA_SecurityHostedUser>
</soap:Header>
</code>```

My php code

```<code>$params = [
            'exceptions' => 0,
            'soap_version' => SOAP_1_2,
            'trace' => 1,
        ];

        $soapvar = new \SoapVar($soapRequest, XSD_ANYXML);
        $client = new SoapClient($wsdlFile", $params);
        $result = $client->Hotel_MultiSingleAvailability($soapvar);
</code>```

But if I print last request I get another xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://www.opentravel.org/OTA/2003/05">
  <env:Body>
    <soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <add:MessageID xmlns:add="http://www.w3.org/2005/08/addressing">be4b7f20-c867-11e7-a815-83f383e012a5</add:MessageID>
      <add:Action xmlns:add="http://www.w3.org/2005/08/addressing">http://webservices.amadeus.com/Hotel_MultiSingleAvailability_10.0</add:Action>
      <add:To xmlns:add="http://www.w3.org/2005/08/addressing">https://nodeD1.test.webservices.amadeus.com/1ASIWOTANA8</add:To>
      <link:TransactionFlowLink xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1"/>
      <oas:Security xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        <oas:UsernameToken xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" oas1:Id="UsernameToken-1">
          <oas:Username>WSNA8OTA</oas:Username>
          <oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">nonce</oas:Nonce>
          <oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">pass</oas:Password>
          <oas1:Created>2017-11-13T11:42:35:788Z</oas1:Created>
        </oas:UsernameToken>
      </oas:Security>
      <AMA_SecurityHostedUser xmlns="http://xml.amadeus.com/2010/06/Security_v1">
        <UserID POS_Type="1" PseudoCityCode="MIA1S38BL" AgentDutyCode="SU" RequestorType="U"/>
      </AMA_SecurityHostedUser>
    </soap:Header>
  </env:Body>
</env:Envelope>
</code>```

How I can remove env:body and env:envelope from my request and use only my xml file?

答:
To get soap:Header with it's children elements

```<code>// load full xml
$xml = simplexml_load_string($s);
// get all namespaces used  in doc by seting true and register soap for xpath
$xml->registerXPathNamespace ('soap', $xml->getDocNamespaces(true)['soap']);
// get the part you want
$myxml = $xml->xpath('/env:Envelope/env:Body/soap:Header');
</code>```

demo

Title: Php make soap request

Body:
I trying to make soap request to Amadeus Web Service. I have xml file with soap-header

<?xml version="1.0"?>
<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <add:MessageID xmlns:add="http://www.w3.org/2005/08/addressing">dbbb6ca5-e5d4-7518-d84-f6f7c22ed752</add:MessageID>
  <add:Action xmlns:add="http://www.w3.org/2005/08/addressing">http://webservices.amadeus.com/Hotel_MultiSingleAvailability_10.0</add:Action>
  <add:To xmlns:add="http://www.w3.org/2005/08/addressing">https://nodeD1.test.webservices.amadeus.com/1ASIWOTANA8</add:To>
  <link:TransactionFlowLink xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1"/>
  <oas:Security xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
    <oas:UsernameToken xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" oas1:Id="UsernameToken-1">
      <oas:Username>WSNA8OTA</oas:Username>
      <oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"nonce</oas:Nonce>
      <oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">pass</oas:Password>
      <oas1:Created>2017-11-09T08:50:40.588Z</oas1:Created>
    </oas:UsernameToken>
  </oas:Security>
  <AMA_SecurityHostedUser xmlns="http://xml.amadeus.com/2010/06/Security_v1">
    <UserID POS_Type="1" PseudoCityCode="MIA1S38BL" AgentDutyCode="SU" RequestorType="U"/>
  </AMA_SecurityHostedUser>
</soap:Header>

My php code

$params = [
            'exceptions' => 0,
            'soap_version' => SOAP_1_2,
            'trace' => 1,
        ];

        $soapvar = new \SoapVar($soapRequest, XSD_ANYXML);
        $client = new SoapClient($wsdlFile", $params);
        $result = $client->Hotel_MultiSingleAvailability($soapvar);

But if I print last request I get another xml

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://www.opentravel.org/OTA/2003/05">
  <env:Body>
    <soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <add:MessageID xmlns:add="http://www.w3.org/2005/08/addressing">be4b7f20-c867-11e7-a815-83f383e012a5</add:MessageID>
      <add:Action xmlns:add="http://www.w3.org/2005/08/addressing">http://webservices.amadeus.com/Hotel_MultiSingleAvailability_10.0</add:Action>
      <add:To xmlns:add="http://www.w3.org/2005/08/addressing">https://nodeD1.test.webservices.amadeus.com/1ASIWOTANA8</add:To>
      <link:TransactionFlowLink xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1"/>
      <oas:Security xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        <oas:UsernameToken xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" oas1:Id="UsernameToken-1">
          <oas:Username>WSNA8OTA</oas:Username>
          <oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">nonce</oas:Nonce>
          <oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">pass</oas:Password>
          <oas1:Created>2017-11-13T11:42:35:788Z</oas1:Created>
        </oas:UsernameToken>
      </oas:Security>
      <AMA_SecurityHostedUser xmlns="http://xml.amadeus.com/2010/06/Security_v1">
        <UserID POS_Type="1" PseudoCityCode="MIA1S38BL" AgentDutyCode="SU" RequestorType="U"/>
      </AMA_SecurityHostedUser>
    </soap:Header>
  </env:Body>
</env:Envelope>

How I can remove env:body and env:envelope from my request and use only my xml file?

Body:
To get soap:Header with it's children elements

// load full xml
$xml = simplexml_load_string($s);
// get all namespaces used  in doc by seting true and register soap for xpath
$xml->registerXPathNamespace ('soap', $xml->getDocNamespaces(true)['soap']);
// get the part you want
$myxml = $xml->xpath('/env:Envelope/env:Body/soap:Header');

demo


问:
Failed to add fields.Selection to parent model
I'm working on access restriction to res.partner.
Currently I have two questions:

1.Why does this code don't create new field to inherited model (first error was something like "unknown object _", now it's gone): (Now it works, first question is answered)

```<code>from odoo import models, fields
class partner(models.Model):
    _inherit = 'res.partner'
    privacy_visibility = fields.Selection([
            ('followers', _('On invitation only')),
            ('employees', _('Visible by all employees')),
         #error was here. according to odoo documentation, here is a comma
         #if you remove it, the code works: [![enter image description here][1]][1]([('',''),('',''),('','')])
        ],
        string='Privacy', required=True,
        default='employees',
        help="Holds visibility of the partner that affects currently logged user:\n"
                "- On invitation only: Employee may only see the followed partners\n"
                "- Visible by all employees: Employee may see selected partner\n")
</code>```

Later, when my restrictions would be applied, how to make selected users to access all pertners anyway? (my ideas - 1.to hide "privacy_visibility" field to be visible in developer mode only, as it made for project's "sub-task project". 2.to create a new group, but I have no idea how to use access groups with row-level access), which way wold you recommend to go?

答:
First Question Ans:
The Selection field syntax is not correct please follow this syntax

Example:

gender = fields.Selection([('male', 'Male'), ('female', 'Female'), ('any', 'Any')], string='Gender')

Body:
I'm working on access restriction to res.partner.
Currently I have two questions:

1.Why does this code don't create new field to inherited model (first error was something like "unknown object _", now it's gone): (Now it works, first question is answered)

from odoo import models, fields
class partner(models.Model):
    _inherit = 'res.partner'
    privacy_visibility = fields.Selection([
            ('followers', _('On invitation only')),
            ('employees', _('Visible by all employees')),
         #error was here. according to odoo documentation, here is a comma
         #if you remove it, the code works: [![enter image description here][1]][1]([('',''),('',''),('','')])
        ],
        string='Privacy', required=True,
        default='employees',
        help="Holds visibility of the partner that affects currently logged user:\n"
                "- On invitation only: Employee may only see the followed partners\n"
                "- Visible by all employees: Employee may see selected partner\n")

Later, when my restrictions would be applied, how to make selected users to access all pertners anyway? (my ideas - 1.to hide "privacy_visibility" field to be visible in developer mode only, as it made for project's "sub-task project". 2.to create a new group, but I have no idea how to use access groups with row-level access), which way wold you recommend to go?


问:
Cross Site Request Forgery (XSRF) Protection AngularJS
Our AngularJS app is located in site.com and our api is hosted in api.site.com, The backend is written by ASP.NET Web API, It is appearent that the CORS should be enabled between site.com and api.site.com, the documentation in here says:

XSRF is an attack technique by which the attacker can trick an
  authenticated user into unknowingly executing actions on your website.
  AngularJS provides a mechanism to counter XSRF. When performing XHR
  requests, the $http service reads a token from a cookie (by default,
  XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only
  JavaScript that runs on your domain could read the cookie, your server
  can be assured that the XHR came from JavaScript running on your
  domain. The header will not be set for cross-domain requests.

I have bolded the last line what doc says, is enabling CSRF protection for my application useless in this scenario? or is my app immune from this kind of attacks?

答:
In response to your questions:

Is enabling CSRF protection for my application useless in this scenario?

No. The documentation simply tells you that AngularJS helps make the implementation of CSRF protection easier for you, and you are responsible for completing the implementation with the help of AngularJS's XSRF feature.

Is my app immune from this kind of attacks?

No. In fact, AngularJS uses the cookie-to-header prevention approach, that is not completely fool proof if you are not careful! For more information, please visit here.

To summarise, the documentation simply tells you that the client-side implementation is handled for you. You will need do the following part:

Create CSRF token (make sure it's random and can't be guessed) & associate it with user session during login

Assert that all incoming requests to your API have the X-XSRF-TOKEN header, and that the value of the header is the token that is associated with the user’s session

and yes, please make sure you enable your same-origin policy.


问:
Angular2 how to know if an input is of type radio with reactive forms
I am building reactive forms form in angular. I have simple radio button with gender name:

```<code>this._form = this._formBuilder.group({
            gender: ['', Validators.required]
        });
</code>```

Template:

```<code>            <div class="form-group">
                <h4>What is your gender?</h4>
                <div class="form-group">
                    <label class="custom-control custom-radio">
                        <input value="male" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Male</span>
                    </label>
                    <label class="custom-control custom-radio">
                        <input value="female" name="gender" type="radio" class="custom-control-input" formControlName="gender">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Female</span>
                    </label>
                    <app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'gender','required')" errorMsg="Field is required"></app-field-error-display>
                </div>
            </div>
</code>```

I can access the control field by name like this:

```<code>public GetControl(form: FormGroup, field: string){
        return form.get(field);
    }
</code>```

Based on this how do I access the attribute value of type="radio"? I want to know if input control is of type radio.

答:
 you can access the value by using this code in your component

```<code>let genderValue = this._form.value.gender;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am building reactive forms form in angular. I have simple radio button with gender name:

this._form = this._formBuilder.group({
            gender: ['', Validators.required]
        });

Template:

What is your gender?

                        <input value="male" name="gender" type="radio" class="custom-control-input" formControlName="gender">

                        Male

                        <input value="female" name="gender" type="radio" class="custom-control-input" formControlName="gender">

                        Female

                    <app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'gender','required')" errorMsg="Field is required"></app-field-error-display>

I can access the control field by name like this:

public GetControl(form: FormGroup, field: string){
        return form.get(field);
    }

Based on this how do I access the attribute value of type="radio"? I want to know if input control is of type radio.

Body:
 you can access the value by using this code in your component

let genderValue = this._form.value.gender;


问:
Logical Operators, || or OR?
I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).

I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.

Which is better and why?

答:
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

```<code>$positions = $this->positions() || [];
</code>```

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

```<code>$positions = $this->positions() or [];
</code>```

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

```<code><?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";
</code>```

This is the result:

```<code>bool(false)
NULL
array(0) {
}
</code>```

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

```<code>$positions = $this->positions() ?: [];
</code>```

Tested with PHP 7.2.1

Title: Logical Operators, || or OR?

Body:
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

$positions = $this->positions() or [];

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:

bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

$positions = $this->positions() ?: [];

Tested with PHP 7.2.1


问:
python removing items from a list
THis code is to remove words from a lists starting with a specified letter of the alphabet. The trouble is, is that it only removes some of the entries.
when I run it to remove words beginning with 'a', only 'ana', 'agra', 'aba' are removed. Why? also is it possible to rewrite the condition to include a range of letters, say a-i for example?

```<code>def delete_from_list():
    discarded=[]
    #list_of_terms = pickle.load( open( "list_it.txt", "rb" ) )
    list_of_terms = ['ana', 'agro','agra',' aaa','aba','bab','Banana', 'band', 'bink' ]

    print('start length = ', len(list_of_terms))

    for item in list_of_terms:
        item.lower().strip()
        if item.startswith('a'):
            discarded.append(item)
            list_of_terms.remove(item)
    print('end_length = ', len(list_of_terms))
    print(discarded, list_of_terms)
</code>```

Thank you for your time and help.

答:
Like DeepSpace and Patrick said, you're iterating through the list while removing items from it. To look for words starting from a-i, you could try using regex.

```<code>regex=re.compile('^[a-i]')

if re.match(regex, somestring):
    # do things
</code>```

The caret matches the start of the string, and the a-i inside the square brackets indicate the set of characters you want. See the python docs on regex for more detail.

Title: python removing items from a list

Body:
THis code is to remove words from a lists starting with a specified letter of the alphabet. The trouble is, is that it only removes some of the entries.
when I run it to remove words beginning with 'a', only 'ana', 'agra', 'aba' are removed. Why? also is it possible to rewrite the condition to include a range of letters, say a-i for example?

def delete_from_list():
    discarded=[]
    #list_of_terms = pickle.load( open( "list_it.txt", "rb" ) )
    list_of_terms = ['ana', 'agro','agra',' aaa','aba','bab','Banana', 'band', 'bink' ]

    print('start length = ', len(list_of_terms))

    for item in list_of_terms:
        item.lower().strip()
        if item.startswith('a'):
            discarded.append(item)
            list_of_terms.remove(item)
    print('end_length = ', len(list_of_terms))
    print(discarded, list_of_terms)

Thank you for your time and help.

Body:
Like DeepSpace and Patrick said, you're iterating through the list while removing items from it. To look for words starting from a-i, you could try using regex.

regex=re.compile('^[a-i]')

if re.match(regex, somestring):
    # do things

The caret matches the start of the string, and the a-i inside the square brackets indicate the set of characters you want. See the python docs on regex for more detail.


问:
Python & requests | ImportError: No module named util
I just installed the package requests on a new computer. I'm getting this error when I try to import that module. Any ideas what's causing the issue w/ the util module?</p>

```<code>Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> import requests

Traceback (most recent call last):

File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/__init__.py", line 58, in <module>
  from . import utils
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/utils.py", line 25, in <module>
  from .compat import parse_http_list as _parse_list_header
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/compat.py", line 7, in <module>
  from .packages import chardet
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/__init__.py", line 3, in <module>
  from . import urllib3
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/__init__.py", line 16, in <module>
  from .connectionpool import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connectionpool.py", line 36, in <module>
  from .connection import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connection.py", line 43, in <module>
  from .util import (
ImportError: No module named util
</code>```

答:
As seen here Bug 1459100
I have do execute the following commands:

```<code># mv /usr/lib/python2.7/site-packages/requests /usr/lib/python2.7/site-packages/requests_old
</code>```

then

```<code>dnf install python-requests --best --allowerasing
</code>```

So, finally I can start virt-manager again.

My system specs:
Fedora 25

```<code>$ /usr/lib/

python2.7/ python3.5/
</code>```

Body:
I just installed the package requests on a new computer. I'm getting this error when I try to import that module. Any ideas what's causing the issue w/ the util module?

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> import requests

Traceback (most recent call last):

File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/__init__.py", line 58, in <module>
  from . import utils
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/utils.py", line 25, in <module>
  from .compat import parse_http_list as _parse_list_header
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/compat.py", line 7, in <module>
  from .packages import chardet
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/__init__.py", line 3, in <module>
  from . import urllib3
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/__init__.py", line 16, in <module>
  from .connectionpool import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connectionpool.py", line 36, in <module>
  from .connection import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connection.py", line 43, in <module>
  from .util import (
ImportError: No module named util

Body:
As seen here Bug 1459100
I have do execute the following commands:

# mv /usr/lib/python2.7/site-packages/requests /usr/lib/python2.7/site-packages/requests_old

then

dnf install python-requests --best --allowerasing

So, finally I can start virt-manager again.

My system specs:
Fedora 25

$ /usr/lib/

python2.7/ python3.5/


问:
Bring activity front if it is running or create new one with backpress

Let me explain detailed; I have notification and this notification opens B activity with two cases.

Cases :

If app is closed. (not running on background)

If app is opened. (on background or front)

Case-1

I click to the notification and it opens the B activity with case-1. When i press back i want to go to the A activity and kill B activity. I dont need B activity anymore. Everything easy from here without using flags. When I'm on B activity and press back two times from here, it goes A activity and then closes the app. My trouble here is, if i open the app from navigation buttons of phone (can't remember the name of this button) app is opening from B activity. That's not what i expected. I want to open A activity. Don't want to see B activity anymore.

Case-2

I click to the notification and it opens the B activity with case-2.When i press back i want to bring A activity to the front, without creating anything new. If i press back on B activity, two times and close the app and then again re-open app from navigation button of phone, want to open app from A activity.

So how can i make this correctly, i tried to use flags (i already read docs) but couldn't get work.
What flags should i use when i open the B activity and onBackPress method of B activity to go A activity as i wanted

答:
This should be achievable by adding

```<code>android:launchMode="singleTask"
</code>```

to the A activity in the Manifest, then you can just open A activity from B activity onBackPressed and you will have A only once in the stack.

If it's not working the way you want, you can create an abstract class that extends Activity and handle the stack in a static object, then A & B must extend this new class

Body:
This should be achievable by adding

android:launchMode="singleTask"

to the A activity in the Manifest, then you can just open A activity from B activity onBackPressed and you will have A only once in the stack.

If it's not working the way you want, you can create an abstract class that extends Activity and handle the stack in a static object, then A & B must extend this new class


问:
iOS UITextField Auto Resize conform to the content
How I can set the Auto resize in Text Field in iOS ?

helloWorld.m

self.TextFieldExample.text = @"HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";

Now:

HELLO WORLD HELLO ...

Correct:

HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD

What is the best practice in this case?

答:
In my case I wanted the font to be of the same size. I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11.

For iOS 11 this even works while editing text.

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event.

```<code>//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}
</code>```

Body:
In my case I wanted the font to be of the same size. I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11.

For iOS 11 this even works while editing text.

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event.

//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}


问:
Laravel 5.4 upload multiple images with validation rules
I'm using following code to upload multiple images but I need to add some validation rules like file should be an image with mentioned extensions and file size. Currently it upload everything.

This is my html view code:

```<code><input required="" type="file" name="photos[]" id="photos" multiple="" directory="" webkitdirectory="" mozdirectory="">
</code>```

This is my controller code:

```<code>foreach ($request->photos as $photo) {
    $filename = $photo->store('photos');
    $data['photoName'] = $filename;
    PhotosModel::SavePhotos($data);
    $message = "Photos Added Successfully";
}
</code>```

I've added below code inside foreach loop and before that loop to but it's giving error that photos must be an image and of mentioned types.

```<code>$this->validate($request, [
    'photos' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);
</code>```

I want to upload all images and stop other files from being uploaded. Thanks!

答:
Try this (before your foreach):</p>

```<code>$this->validate($request, [
    'photos' => 'required',
    'photos.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);
</code>```

Body:
I'm using following code to upload multiple images but I need to add some validation rules like file should be an image with mentioned extensions and file size. Currently it upload everything.

This is my html view code:

<input required="" type="file" name="photos[]" id="photos" multiple="" directory="" webkitdirectory="" mozdirectory="">

This is my controller code:

foreach ($request->photos as $photo) {
    $filename = $photo->store('photos');
    $data['photoName'] = $filename;
    PhotosModel::SavePhotos($data);
    $message = "Photos Added Successfully";
}

I've added below code inside foreach loop and before that loop to but it's giving error that photos must be an image and of mentioned types.

$this->validate($request, [
    'photos' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
]);

I want to upload all images and stop other files from being uploaded. Thanks!

Body:
Try this (before your foreach):

$this->validate($request, [
    'photos' => 'required',
    'photos.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048'
]);


问:
Unable to get existing Hive tables from HiveContext using Spark
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

```<code>scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+
</code>```

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

```<code>hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>
</code>```

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>
```

<p>Below is my spark conf Directory:</p>

```total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*
```

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.

答:
This will give you required result:

import org.apache.spark.sql.hive.HiveContext

val hc = new HiveContext(sc)

import hc.implicits._

val df = hc.sql("show databases")

df.show

Body:
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>

Below is my spark conf Directory:

total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.


问:
Can i query the database in the middle of a 'map' closure with Couchbase Lite?
In Couchbase Lite, is this permissible/encouraged or will it cause race conditions / any other problems?

```<code>let view = database.viewNamed("myView")
view.setMapBlock({ properties, emit in
  database.existingDocument(withID: properties["some_foreign_key"])
</code>```

Basically i'm trying to create a view which is the equivalent of an SQL 'left inner join'.

答: It is not permitted.  Map functions must be pure, as in given the same set of inputs they will always produce the same outputs.  No external state may be referenced.  </p>

Body:
In Couchbase Lite, is this permissible/encouraged or will it cause race conditions / any other problems?

let view = database.viewNamed("myView")
view.setMapBlock({ properties, emit in
  database.existingDocument(withID: properties["some_foreign_key"])

Basically i'm trying to create a view which is the equivalent of an SQL 'left inner join'.


问:
SAS Macro help to loop monthly sas datasets
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

```<code>Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014
</code>```

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

答:
Depending on what you want the result to be, you can create one output per month by filtering on cust_expenses per month and joining with the corresponding monthly dataset

```<code>%macro want;
proc sql noprint;
select distinct month
into :months separated by ' '
from cust_expenses
;
quit;

proc sql;
%do i=1 %to %sysfunc(countw(&months));
  %let month=%scan(&months,&i,%str( ));
    create table want_&month. as
    select *
    from cust_expense(where=(month="&month.")) t1
    inner join cust_&month. t2
      on t1.customer_number=t2.customer_number
    ;
%end;
quit;
%mend;
%want;
</code>```

Or you could have one output using one join by 'unioning' all those monthly datasets into one and dynamically adding a month column.

```<code>%macro want;
proc sql noprint;
select distinct month
into :months separated by ' '
from cust_expenses
;
quit;

proc sql;
  create table want as
  select *
  from cust_expense t1
  inner join (
              %do i=1 %to %sysfunc(countw(&months));
                %let month=%scan(&months,&i,%str( ));
                %if &i>1 %then union;
                select *, "&month." as month
                from cust_&month
              %end;
             ) t2
    on t1.customer_number=t2.customer_number
     and t1.month=t2.month
  ;
quit;
%mend;
%want;
</code>```

In either case, I don't really see the point in joining those monthly datasets with the cust_expense dataset. The latter does not seem to hold any information that isn't already present in the monthly datasets.

Body:
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

Body:
Depending on what you want the result to be, you can create one output per month by filtering on cust_expenses per month and joining with the corresponding monthly dataset

%macro want;
proc sql noprint;
select distinct month
into :months separated by ' '
from cust_expenses
;
quit;

proc sql;
%do i=1 %to %sysfunc(countw(&months));
  %let month=%scan(&months,&i,%str( ));
    create table want_&month. as
    select *
    from cust_expense(where=(month="&month.")) t1
    inner join cust_&month. t2
      on t1.customer_number=t2.customer_number
    ;
%end;
quit;
%mend;
%want;

Or you could have one output using one join by 'unioning' all those monthly datasets into one and dynamically adding a month column.

%macro want;
proc sql noprint;
select distinct month
into :months separated by ' '
from cust_expenses
;
quit;

proc sql;
  create table want as
  select *
  from cust_expense t1
  inner join (
              %do i=1 %to %sysfunc(countw(&months));
                %let month=%scan(&months,&i,%str( ));
                %if &i>1 %then union;
                select *, "&month." as month
                from cust_&month
              %end;
             ) t2
    on t1.customer_number=t2.customer_number
     and t1.month=t2.month
  ;
quit;
%mend;
%want;

In either case, I don't really see the point in joining those monthly datasets with the cust_expense dataset. The latter does not seem to hold any information that isn't already present in the monthly datasets.


问:
foreign key not updated in one to many hibernate mapping

User class

```<code>@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn(name="FK_USER_ID",referencedColumnName="PK_USER_ID")
    private Set<DeviceInfo> deviceInfos;
}
</code>```

DeviceInfo

```<code>@Entity
@Table(name="device_info")
public class DeviceInfo {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;
    @Column(name="FK_USER_ID")
    private Integer userId;
}
</code>```

When i try to insert data into user table and device_info table, data is inserted but foreign key column of device_info table not updated with primary key of user table.

Hibernate version:4.3.6.Final
Spring version :4.3.1

答:
Have you missed setting user Object in deviceInfo object before persisting, code should look like:</p>

```<code>user.setDeviceInfo(setOfDeviceInfo);

deviceInfo.setUser(user);

session.save(user);
</code>```

Body:
User class

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn(name="FK_USER_ID",referencedColumnName="PK_USER_ID")
    private Set<DeviceInfo> deviceInfos;
}

DeviceInfo

@Entity
@Table(name="device_info")
public class DeviceInfo {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;
    @Column(name="FK_USER_ID")
    private Integer userId;
}

When i try to insert data into user table and device_info table, data is inserted but foreign key column of device_info table not updated with primary key of user table.

Hibernate version:4.3.6.Final
Spring version :4.3.1

Body:
Have you missed setting user Object in deviceInfo object before persisting, code should look like:

user.setDeviceInfo(setOfDeviceInfo);

deviceInfo.setUser(user);

session.save(user);


问:
print last line from the variable output in python
I am looking to get the last line produced from the line variable

```<code>bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line
</code>```

output i am getting is as follows ..

```<code>-122.1058
-123.1050
-125.10584323
</code>```

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

```<code>bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)
</code>```

this yeilds teh desired as folows..

```<code>bash-4.1$ ./file2_dup.py
-125.10584323
</code>```

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

答:
I see a better way by creating an empty list and appending the value comes from the condition and then choose the Index of your choice and list the output , this is good in the sense that it can be used for any line of your intrest which you require to pick.

Lets Suppose i wana the last second line then it can be resuable putting the value in the print section  print(lst[-2]) , which will print the last index of second line..

```<code>#!/usr/bin/python
file = open('file1.txt', 'r')
lst = list()
for line in file:
    if "!" in line:
        x= line.split()
        lst.append(x[-1])

print(lst[-1])
</code>```

Body:
I am looking to get the last line produced from the line variable

bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
  lines = f.readlines()
  for line in lines:
    if "!" in line:
      line = line.split()[-1].strip()
      print line

output i am getting is as follows ..

-122.1058
-123.1050
-125.10584323

The result i wanted to be printed out is

-125.10584323

Moreover, i got the hint from some goghling and getting the output
  desired but that seems bit complicated to me at the point ..

bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
  with open(fname) as f:
    f=f.read().splitlines()
    lines=[x for x in f]
    for i in range(len(lines)-n,len(lines)):
      line = lines[i].split()[-1]
      #line = line.split()[-1]
      print line
file_read_from_tail('file1.txt',1)

this yeilds teh desired as folows..

bash-4.1$ ./file2_dup.py
-125.10584323

PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python

Body:
I see a better way by creating an empty list and appending the value comes from the condition and then choose the Index of your choice and list the output , this is good in the sense that it can be used for any line of your intrest which you require to pick.

Lets Suppose i wana the last second line then it can be resuable putting the value in the print section  print(lst[-2]) , which will print the last index of second line..

#!/usr/bin/python
file = open('file1.txt', 'r')
lst = list()
for line in file:
    if "!" in line:
        x= line.split()
        lst.append(x[-1])

print(lst[-1])


问:
How to go back to root view controller in uisplitviewcontroller like "Settings" app in iPad?
In the "settings" app of iPad, if u click on "General" > "About", then click on "General" at the side. The "About" page will jump back to root view controller.

How do I achieve that in swift?

I'm currently using self.splitViewController?.showDetailViewController on click at "masterview"

答:
Can you try this?</p>

```<code>self.splitViewController?.navigationController?.popToRootViewController(animated: true)
</code>```

Body:
Can you try this?

self.splitViewController?.navigationController?.popToRootViewController(animated: true)


问:
Updating Matrix using an apply
I have a predefined matrix M = matrix(0,5,4) . I want to update the matrix elements from value zero to proper value basis the value of the dataframe df object as per condition df$colA = x (matrix row element) and df$colB = y (matrix column element). I have set the row names and col names with the respective unique colA and colB values. ColA and ColB values are discrete integers instead of taking regular sequence values.

M=matrix(0,5,4)
  rownames(M)=c(135,138,145,146,151)
  colnames(M)=c(192,204,206,207)

```<code>    192 204 206 207
135   0   0   0   0
138   0   0   0   0
145   0   0   0   0
146   0   0   0   0
151   0   0   0   0

df-> ColA   ColB    ColC
135 192 1
135 204 1
135 206 -1
138 192 -1
138 206 1
138 207 1
145 192 -1
145 204 -1
145 206 -1
145 207 1
146 206 1
146 207 1
151 192 -1
151 207 1
for (r in rownames(M)) {
  for (c in colnames(M)) {
    tmp = df[(df$colA == c & df$colB==r),]$colC
    if (!(length(tmp) == 0)) {
      M[(rownames(M) == r),(colnames(M) == c)]= tmp
    }
  }
}
</code>```

Instead of using for loop, wondering if this can be achieved with an apply or outer function with the matric updation part being handled using a custom function. Please help how to achieve this.

I was trying to refer to this link, but no luck.

答:
To modify a matrix, you can use apply() function. The code will be:

```<code>apply(M,1,function(x) <your_function>) # If you want to run for each row
apply(M,2,function(x) <your function>) # If you want to run for each column
</code>```

If you write the function you want or a short example, we will offer you a better help.

Title: Updating Matrix using an apply

Body:
I have a predefined matrix M = matrix(0,5,4) . I want to update the matrix elements from value zero to proper value basis the value of the dataframe df object as per condition df$colA = x (matrix row element) and df$colB = y (matrix column element). I have set the row names and col names with the respective unique colA and colB values. ColA and ColB values are discrete integers instead of taking regular sequence values.

M=matrix(0,5,4)
  rownames(M)=c(135,138,145,146,151)
  colnames(M)=c(192,204,206,207)

    192 204 206 207
135   0   0   0   0
138   0   0   0   0
145   0   0   0   0
146   0   0   0   0
151   0   0   0   0

df-> ColA   ColB    ColC
135 192 1
135 204 1
135 206 -1
138 192 -1
138 206 1
138 207 1
145 192 -1
145 204 -1
145 206 -1
145 207 1
146 206 1
146 207 1
151 192 -1
151 207 1
for (r in rownames(M)) {
  for (c in colnames(M)) {
    tmp = df[(df$colA == c & df$colB==r),]$colC
    if (!(length(tmp) == 0)) {
      M[(rownames(M) == r),(colnames(M) == c)]= tmp
    }
  }
}

Instead of using for loop, wondering if this can be achieved with an apply or outer function with the matric updation part being handled using a custom function. Please help how to achieve this.

I was trying to refer to this link, but no luck.

Body:
To modify a matrix, you can use apply() function. The code will be:

apply(M,1,function(x) <your_function>) # If you want to run for each row
apply(M,2,function(x) <your function>) # If you want to run for each column

If you write the function you want or a short example, we will offer you a better help.


问:
Create an emulator with a decent size from command line
I want to create an ARM API 21 emulator loaded with Google APIs.

Here's how I create the AVD:

```<code>ANDROID_ABI=google_apis/armeabi-v7a
EMULATOR_VERSION=21
avd --force -n nexus4-emulator -t "Google Inc.:Google APIs:"$EMULATOR_VERSION --abi $ANDROID_ABI --device "Nexus 4" -c 128M
</code>```

And now I start up the emulator with:

```<code>emulator -avd nexus4-emulator &
</code>```

However, this is what I get: a screen with tiny dimensions (in terms of effective pixels):

How can I change this config so that I have a properly sized screen?

I'm using this to build APKs and run tests on a machine in Travis, by the way, but it's reproducible in my machine (Mac OS X).

答:
So this is still not solved in late 2017 (Booo Google!).

The minimal change I found to be working is adding skin.name=1080x1920 or any other desired resolution to the avd's config.ini (~/.android/avd/{avdName}.avd/config.ini)

Body:
I want to create an ARM API 21 emulator loaded with Google APIs.

Here's how I create the AVD:

ANDROID_ABI=google_apis/armeabi-v7a
EMULATOR_VERSION=21
avd --force -n nexus4-emulator -t "Google Inc.:Google APIs:"$EMULATOR_VERSION --abi $ANDROID_ABI --device "Nexus 4" -c 128M

And now I start up the emulator with:

emulator -avd nexus4-emulator &

However, this is what I get: a screen with tiny dimensions (in terms of effective pixels):

How can I change this config so that I have a properly sized screen?

I'm using this to build APKs and run tests on a machine in Travis, by the way, but it's reproducible in my machine (Mac OS X).


问:
Java 9 gives "Main Class not found" ob Ubuntu, but file works on Windows and Mac // how to find main Class in OpenJDK
So I have a jar file that works perfectly fine on Windows and Mac, but not on Ubuntu (the only place where Openjdk is installed)
This question hints at OpenJDK being the problem: Java Application main class not found on Ubuntu
So: how do I show OpenJDK the correct Main Class? (Its Client.class in /chat in the jar file) I know it has something to do with the MetaINF File, but I cant guess the correct input there.
This is what's currently in the MANIFEST.MF file:

Manifest-Version: 1.0

Main-Class: Chat.Client

I cant find anything anywhere on the topic, but I also cant install the proprietary java on the Ubuntu PC, as its the one where the jar HAS to run and the one where I m not admin at.

答:
Its Client.class in /chat in the jar file

Then Main-Class: Chat.Client is incorrect, it should be Main-Class: chat.Client (lower case chat).

So probably not an OpenJDK issue, just the fact that some file systems are case-insensitive and others are case-sensitive. You're almost certainly using a case-insensitive one on Windows. I guess you must be on Mac as well, though I find that surprising. You probably aren't on Ubuntu.


问:
Nativescript's AOT Compilation succeeds - but still the `Compiler` package included?
I'm invoking :

```<code>npm run ns-bundle --android --build-app --uglify
</code>```

It does succeed   (here is the complete log).

If I navigate to the report folder (created by webpack-bundle-size-analyzer) - I see those two files :

Opening the html file shows :

As you can see -  the compiler from @angular is still there !!!

Question

1)  Why does the compiler still there ? (AOT should remove it). How do I remove it ?

2) If I hover the bundle.js section it shows me parsed size. so what is stat/parsed size ?

Additional info :

I must say that when i search bundle.js in filesystem - I see two files :

And a second one :

webpack.config.json : http://jsbin.com/varetibaya/1/edit?html

package.json : http://jsbin.com/sajifojuki/edit?html

main.aot.file : http://jsbin.com/jimonurama/edit?html

ts.config.aot : http://jsbin.com/tatahesoma/edit?html

答:
@yurzui has found the problem .

Changed :

```<code>import {RouterExtensions} from "nativescript-angular";
</code>```

with

```<code>import {RouterExtensions} from "nativescript-angular/router";
</code>```

Now - there is no compiler in the package.

(With many thanks.).

Body:
I'm invoking :

npm run ns-bundle --android --build-app --uglify

It does succeed   (here is the complete log).

If I navigate to the report folder (created by webpack-bundle-size-analyzer) - I see those two files :

Opening the html file shows :

As you can see -  the compiler from @angular is still there !!!

Question

1)  Why does the compiler still there ? (AOT should remove it). How do I remove it ?

2) If I hover the bundle.js section it shows me parsed size. so what is stat/parsed size ?

Additional info :

I must say that when i search bundle.js in filesystem - I see two files :

And a second one :

webpack.config.json : http://jsbin.com/varetibaya/1/edit?html

package.json : http://jsbin.com/sajifojuki/edit?html

main.aot.file : http://jsbin.com/jimonurama/edit?html

ts.config.aot : http://jsbin.com/tatahesoma/edit?html

Body:
@yurzui has found the problem .

Changed :

import {RouterExtensions} from "nativescript-angular";

with

import {RouterExtensions} from "nativescript-angular/router";

Now - there is no compiler in the package.

(With many thanks.).


问:
Custom connections between layers Keras
I would like to manually define connections in neural network between layers using keras with Python. By default connections are beween all pairs of neurons. I need to make connections as in picture below.

How can I be done in Keras?

答:
You can use the functional API model and separate four distinct groups:

```<code>from keras.models import Model
from keras.layers import Dense, Input, Concatenate, Lambda

inputTensor = Input((8,))
</code>```

First, we can use lambda layers to split this input in four:

```<code>group1 = Lambda(lambda x: x[:,:2], output_shape=((2,)))(inputTensor)
group2 = Lambda(lambda x: x[:,2:4], output_shape=((2,)))(inputTensor)
group3 = Lambda(lambda x: x[:,4:6], output_shape=((2,)))(inputTensor)
group4 = Lambda(lambda x: x[:,6:], output_shape=((2,)))(inputTensor)
</code>```

Now we follow the network:

```<code>#second layer in your image
group1 = Dense(1)(group1)
group2 = Dense(1)(group2)
group3 = Dense(1)(group3)
group4 = Dense(1)(group4)
</code>```

Before we connect the last layer, we concatenate the four tensors above:

```<code>outputTensor = Concatenate()([group1,group2,group3,group4])
</code>```

Finally the last layer:

```<code>outputTensor = Dense(2)(outputTensor)

#create the model:
model = Model(inputTensor,outputTensor)
</code>```

Beware of the biases. If you want any of those layers to have no bias, use use_bias=False.

Old answer: backwards

Sorry, I saw your image backwards the first time I answered. I'm keeping this here just because it's done...

```<code>from keras.models import Model
from keras.layers import Dense, Input, Concatenate

inputTensor = Input((2,))

#four groups of layers, all of them taking the same input tensor
group1 = Dense(1)(inputTensor)
group2 = Dense(1)(inputTensor)
group3 = Dense(1)(inputTensor)
group4 = Dense(1)(inputTensor)

#the next layer in each group takes the output of the previous layers
group1 = Dense(2)(group1)
group2 = Dense(2)(group2)
group3 = Dense(2)(group3)
group4 = Dense(2)(group4)

#now we join the results in a single tensor again:
outputTensor = Concatenate()([group1,group2,group3,group4])

#create the model:
model = Model(inputTensor,outputTensor)
</code>```

Title: Custom connections between layers Keras

Body:
You can use the functional API model and separate four distinct groups:

from keras.models import Model
from keras.layers import Dense, Input, Concatenate, Lambda

inputTensor = Input((8,))

First, we can use lambda layers to split this input in four:

group1 = Lambda(lambda x: x[:,:2], output_shape=((2,)))(inputTensor)
group2 = Lambda(lambda x: x[:,2:4], output_shape=((2,)))(inputTensor)
group3 = Lambda(lambda x: x[:,4:6], output_shape=((2,)))(inputTensor)
group4 = Lambda(lambda x: x[:,6:], output_shape=((2,)))(inputTensor)

Now we follow the network:

#second layer in your image
group1 = Dense(1)(group1)
group2 = Dense(1)(group2)
group3 = Dense(1)(group3)
group4 = Dense(1)(group4)

Before we connect the last layer, we concatenate the four tensors above:

outputTensor = Concatenate()([group1,group2,group3,group4])

Finally the last layer:

outputTensor = Dense(2)(outputTensor)

#create the model:
model = Model(inputTensor,outputTensor)

Beware of the biases. If you want any of those layers to have no bias, use use_bias=False.

Old answer: backwards

Sorry, I saw your image backwards the first time I answered. I'm keeping this here just because it's done...

from keras.models import Model
from keras.layers import Dense, Input, Concatenate

inputTensor = Input((2,))

#four groups of layers, all of them taking the same input tensor
group1 = Dense(1)(inputTensor)
group2 = Dense(1)(inputTensor)
group3 = Dense(1)(inputTensor)
group4 = Dense(1)(inputTensor)

#the next layer in each group takes the output of the previous layers
group1 = Dense(2)(group1)
group2 = Dense(2)(group2)
group3 = Dense(2)(group3)
group4 = Dense(2)(group4)

#now we join the results in a single tensor again:
outputTensor = Concatenate()([group1,group2,group3,group4])

#create the model:
model = Model(inputTensor,outputTensor)


问:
JSONException : at jsonData of type java.lang.String cannot be converted to JSONArray
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.

My error :

```<code>JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
</code>```

My JSON:

```<code>{
 "jsonData" : {
    "11-13-2017" : {
      "Clau" : {
        "-KyokKjL9UQpsfKZYZqM" : [ {
          "pret" : "80",
          "produs" : "Shirt",
          "produsId" : "-Kyok58s0dOAnVOnbJPk"
        } ]
      }
    }
  }
}
</code>```

I looked over tutorials on StackOverFlow but absolutely no solution.

My code :

```<code> private void writeJSON(String metodaPlata) throws JSONException {
    String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
    String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");

    int totalPrice = 0;
    for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
    {
        int vPrice = Integer.parseInt(v.getPret());
        totalPrice = totalPrice + vPrice;

    }
    String pretTotal = Integer.toString(totalPrice);
    String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());

    JSONObject jsonData;
    JSONArray dateJSON;
    JSONObject obj;
    JSONArray arrayForList;

    if (jsonDataFromShared.equals("")) {

        jsonData = new JSONObject();
        dateJSON = new JSONArray();
        obj = new JSONObject();
        arrayForList = new JSONArray();

        JSONObject objListaSiModalitate = new JSONObject();

        //       arrayForList.put(stock_list.toString());

        objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
        objListaSiModalitate.put("metodaPlata", metodaPlata);

        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);
        jsonData.put("jsonData", dateJSON.toString());

        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    } else {

        jsonData = new JSONObject(jsonDataFromShared);
        dateJSON = jsonData.getJSONArray("jsonData");

        obj = new JSONObject();

        JSONObject objListaSiModalitate = new JSONObject();
        objListaSiModalitate.put("metodaPlata", metodaPlata);
        obj.put("produseSelectate", produseSelectate);
        obj.put("sumaProduse", pretTotal);
        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);

        jsonData.put("jsonData", dateJSON);

        System.out.println("jsonData" + dateJSON);
        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    }
}
</code>```

Please help me I have no idea what to idea even if I look over tutorials.

答:
Error causes from this line

```<code>jsonData.put("jsonData", dateJSON.toString());
</code>```

Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.

Then You try to retrieve JsonArray from string

```<code>jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");
</code>```

EDITED

If you want to retreive array from dateJson object
Replace this line

```<code>jsonData.put("jsonData", dateJSON.toString());
</code>```

To

```<code>jsonData.put("jsonData", dateJSON);
</code>```

Body:
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.

My error :

JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray

My JSON:

{
 "jsonData" : {
    "11-13-2017" : {
      "Clau" : {
        "-KyokKjL9UQpsfKZYZqM" : [ {
          "pret" : "80",
          "produs" : "Shirt",
          "produsId" : "-Kyok58s0dOAnVOnbJPk"
        } ]
      }
    }
  }
}

I looked over tutorials on StackOverFlow but absolutely no solution.

My code :

 private void writeJSON(String metodaPlata) throws JSONException {
    String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
    String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");

    int totalPrice = 0;
    for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
    {
        int vPrice = Integer.parseInt(v.getPret());
        totalPrice = totalPrice + vPrice;

    }
    String pretTotal = Integer.toString(totalPrice);
    String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());

    JSONObject jsonData;
    JSONArray dateJSON;
    JSONObject obj;
    JSONArray arrayForList;

    if (jsonDataFromShared.equals("")) {

        jsonData = new JSONObject();
        dateJSON = new JSONArray();
        obj = new JSONObject();
        arrayForList = new JSONArray();

        JSONObject objListaSiModalitate = new JSONObject();

        //       arrayForList.put(stock_list.toString());

        objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
        objListaSiModalitate.put("metodaPlata", metodaPlata);

        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);
        jsonData.put("jsonData", dateJSON.toString());

        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    } else {

        jsonData = new JSONObject(jsonDataFromShared);
        dateJSON = jsonData.getJSONArray("jsonData");

        obj = new JSONObject();

        JSONObject objListaSiModalitate = new JSONObject();
        objListaSiModalitate.put("metodaPlata", metodaPlata);
        obj.put("produseSelectate", produseSelectate);
        obj.put("sumaProduse", pretTotal);
        obj.put("data", getDate(calendarData.getTimeInMillis()));
        obj.put("numeVanzator", numeVanzator);
        obj.put("numarClient", numarVanzare);

        dateJSON.put(obj);

        jsonData.put("jsonData", dateJSON);

        System.out.println("jsonData" + dateJSON);
        SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());

    }
}

Please help me I have no idea what to idea even if I look over tutorials.

Body:
Error causes from this line

jsonData.put("jsonData", dateJSON.toString());

Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.

Then You try to retrieve JsonArray from string

jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");

EDITED

If you want to retreive array from dateJson object
Replace this line

jsonData.put("jsonData", dateJSON.toString());

To

jsonData.put("jsonData", dateJSON);


问:
Can I use svg pattern to create shapes with rotational symmetry?
I am working on producing an animated codewars logo. It looks good enough for my project: https://codepen.io/forTheLoveOfCode/pen/GOERRE

However, the following block of code surely can be re-written without copying and pasting the same line. Yet, neither my research, nor attempts to guess where "transform=rotate" can be put in SVG pattern got me any results. Any ideas how could I have achieved the same result with fewer lines?

```<code><svg class="codewars" width="300" height="300">
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(60, 150, 150)"/>
    <path d="M148 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(120, 150, 150)"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(180, 150, 150)"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(240, 150, 150)"/>
    <path d="M148 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(300, 150, 150)"/>
</code>```

答:
You've gone down the wrong path, <use> is what you want, not a pattern.

.codewars{
  stroke:red;
  stroke-dasharray: 0.1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg class="codewars" width="320" height="320">
  <defs>
      <path id="curve" d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"/>
  </defs>
  <use href="#curve"/>
  <use href="#curve" transform="rotate(60, 150, 150)"/>
  <use href="#curve" transform="rotate(120, 150, 150)"/>
  <use href="#curve" transform="rotate(180, 150, 150)"/>
  <use href="#curve" transform="rotate(240, 150, 150)"/>
  <use href="#curve" transform="rotate(300, 150, 150)"/>
</svg></code>```

Body:
I am working on producing an animated codewars logo. It looks good enough for my project: https://codepen.io/forTheLoveOfCode/pen/GOERRE

However, the following block of code surely can be re-written without copying and pasting the same line. Yet, neither my research, nor attempts to guess where "transform=rotate" can be put in SVG pattern got me any results. Any ideas how could I have achieved the same result with fewer lines?

<svg class="codewars" width="300" height="300">
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(60, 150, 150)"/>
    <path d="M148 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(120, 150, 150)"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(180, 150, 150)"/>
    <path d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(240, 150, 150)"/>
    <path d="M148 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"transform="rotate(300, 150, 150)"/>

Body:
You've gone down the wrong path, <use> is what you want, not a pattern.

.codewars{
  stroke:red;
  stroke-dasharray: 0.1em;
}

<svg class="codewars" width="320" height="320">
  <defs>
      <path id="curve" d="M150 150 A 75 75 0 1 0 270 200" stroke-width="4" fill="none"/>
  </defs>
  <use href="#curve"/>
  <use href="#curve" transform="rotate(60, 150, 150)"/>
  <use href="#curve" transform="rotate(120, 150, 150)"/>
  <use href="#curve" transform="rotate(180, 150, 150)"/>
  <use href="#curve" transform="rotate(240, 150, 150)"/>
  <use href="#curve" transform="rotate(300, 150, 150)"/>
</svg>


问:
new A() vs. static new A()
What is the difference from

```<code>class Test {
    A a = new A();
}
</code>```

to

```<code>class Test {
   static A a = new A();
}
</code>```

Does the virtual machine perform differently in the initialization?

答: In the first class there will be a member variable for each instance of the class Test. In the Second class there will be just one member variable for the whole class Test.</p>

Title: new A() vs. static new A()

Body:
What is the difference from

class Test {
    A a = new A();
}

to

class Test {
   static A a = new A();
}

Does the virtual machine perform differently in the initialization?


问:
Perl: JSON::XS Is it possible to force boolean decoding as 1/0?
Package JSON::XS uses JSON::XS::Boolean objects to represent true/false. Is it possible to force decoding true/false json values as 1/0 Perl numbers?

```<code>#!/usr/bin/env perl

use JSON::XS;
use Data::Dumper;

my $json = decode_json(join('', <DATA>));
print Dumper $json;

__DATA__
{
    "test_true": true,
    "test_false": false
}
</code>```

Output:

```<code>$VAR1 = {
          'test_true' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' ),
          'test_false' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' )
        };
</code>```

I want something like this after decode_json:

```<code>$VAR1 = {
          'test_true' => 1,
          'test_false' => 0
        };
</code>```

Reason: In some cases, it's hard to predict how JSON::XS::Boolean will be serialized with, for example, SOAP serializer or another one.

PerlMonks discussion.

答: No. The values are blessed objects. They can only have the values allowed in JSON::XS::Boolean.</p>

Body:
Package JSON::XS uses JSON::XS::Boolean objects to represent true/false. Is it possible to force decoding true/false json values as 1/0 Perl numbers?

#!/usr/bin/env perl

use JSON::XS;
use Data::Dumper;

my $json = decode_json(join('', <DATA>));
print Dumper $json;

__DATA__
{
    "test_true": true,
    "test_false": false
}

Output:

$VAR1 = {
          'test_true' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' ),
          'test_false' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' )
        };

I want something like this after decode_json:

$VAR1 = {
          'test_true' => 1,
          'test_false' => 0
        };

Reason: In some cases, it's hard to predict how JSON::XS::Boolean will be serialized with, for example, SOAP serializer or another one.

PerlMonks discussion.


问:
How to display sibling menu items in a menu object in DDRMenu
I'm working with nav.cshtml in DNN's DDRMenu. On pages for this website, I'd like to display a menu at the top of the page that only shows the child pages of the current page, if there are any, and if not shows the sibling pages of the current page.

Here's the code:

@using DotNetNuke.Web.DDRMenu;
@using System.Dynamic;
@inherits DotNetNuke.Web.Razor.DotNetNukeWebPage<dynamic>

@{
 var root = Model.Source.root;
}

@helper RenderNodes(IList<MenuNode> nodes)
{
if (nodes.Count > 0)
{

   @foreach (var node in nodes)
   {
    String isActive = "";
    string isDisabled = "";
    if (node.Selected) { isActive = "active"; }
    if (!node.Enabled) { isDisabled = "disabled"; }

    if (node.HasChildren())
    {

      @node.Text
      <button class="submenuButton" onclick="$(this).toggleClass('active'); return false;">

      </button>
      @RenderChildNodes(node.Children)

    }
    else
    {

@node.Text

    }
   }

}
}

@helper RenderChildNodes(IList<MenuNode> nodes)
{
if (nodes.Count > 0)
{

   @foreach (var node in nodes)
   {
    String isActive = "";
    string isDisabled = "";
    if (node.Selected) { isActive = "active"; }
    if (!node.Enabled) { isDisabled = "disabled"; }

    if (node.HasChildren())
    {

      <button class="submenuButton" onclick="$(this).toggleClass('active'); return false;">

      </button>
      @node.Text
      @RenderChildNodes(node.Children)

    }
    else
    {

@node.Text

    }

```
</div>
</div>
</p>

<p>Essentially, I need to figure out how to display the siblings, if the current page is selected but doesn't have children:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>if (!node.HasChildren() && node.Selected) {
    <!--Display Sibling nodes-->
}</code>```

Any help will be much appreciated.

答:
Here's what we ended up with.

@using DotNetNuke.Web.DDRMenu;
@using System.Dynamic;
@using DotNetNuke.Entities.Portals;
@inherits DotNetNuke.Web.Razor.DotNetNukeWebPage<dynamic>

@{
 var root = Model.Source.root;
}

@helper RenderNodes(IList<MenuNode> nodes)
{
 if (nodes.Count > 0)
 {

   @foreach (var node in nodes)
   {
    foreach (var child in node.Children)
    {
     if (child.Text == PortalSettings.Current.ActiveTab.TabName)
     {
      if (node.Parent.Children.Count > 0)
      {
       @RenderChildNodes(node.Children)
      }
     }
    }

    if(node.Selected && node.Depth == 0 && node.HasChildren())
    {
     @RenderChildNodes(node.Children)
    }
   }

 }
}

@helper RenderChildNodes(IList<MenuNode> nodes)
{
 if (nodes.Count > 0)
 {
  foreach (var node in nodes)
  {
   string isActive = "";
   string isDisabled = "";
   if (node.Selected) { isActive = "active"; }
   if (!node.Enabled) { isDisabled = "disabled"; }

    @node.Text

  }
 }
}

@RenderNodes(root.Children)

```

Body:
I'm working with nav.cshtml in DNN's DDRMenu. On pages for this website, I'd like to display a menu at the top of the page that only shows the child pages of the current page, if there are any, and if not shows the sibling pages of the current page.

Here's the code:

@using DotNetNuke.Web.DDRMenu;
@using System.Dynamic;
@inherits DotNetNuke.Web.Razor.DotNetNukeWebPage<dynamic>

@{
 var root = Model.Source.root;
}

@helper RenderNodes(IList<MenuNode> nodes)
{
if (nodes.Count > 0)
{

   @foreach (var node in nodes)
   {
    String isActive = "";
    string isDisabled = "";
    if (node.Selected) { isActive = "active"; }
    if (!node.Enabled) { isDisabled = "disabled"; }

    if (node.HasChildren())
    {

      @node.Text
      <button class="submenuButton" onclick="$(this).toggleClass('active'); return false;">

      </button>
      @RenderChildNodes(node.Children)

    }
    else
    {

@node.Text

    }
   }

}
}

@helper RenderChildNodes(IList<MenuNode> nodes)
{
if (nodes.Count > 0)
{

   @foreach (var node in nodes)
   {
    String isActive = "";
    string isDisabled = "";
    if (node.Selected) { isActive = "active"; }
    if (!node.Enabled) { isDisabled = "disabled"; }

    if (node.HasChildren())
    {

      <button class="submenuButton" onclick="$(this).toggleClass('active'); return false;">

      </button>
      @node.Text
      @RenderChildNodes(node.Children)

    }
    else
    {

@node.Text

    }

Essentially, I need to figure out how to display the siblings, if the current page is selected but doesn't have children:

if (!node.HasChildren() && node.Selected) {

}

Any help will be much appreciated.

Body:
Here's what we ended up with.

@using DotNetNuke.Web.DDRMenu;
@using System.Dynamic;
@using DotNetNuke.Entities.Portals;
@inherits DotNetNuke.Web.Razor.DotNetNukeWebPage<dynamic>

@{
 var root = Model.Source.root;
}

@helper RenderNodes(IList<MenuNode> nodes)
{
 if (nodes.Count > 0)
 {
  <ol class="breadcrumb">
   @foreach (var node in nodes)
   {
    foreach (var child in node.Children)
    {
     if (child.Text == PortalSettings.Current.ActiveTab.TabName)
     {
      if (node.Parent.Children.Count > 0)
      {
       @RenderChildNodes(node.Children)
      }
     }
    }

    if(node.Selected && node.Depth == 0 && node.HasChildren())
    {
     @RenderChildNodes(node.Children)
    }
   }<!-- ./ for loop -->
  </ol>
 }<!-- ./ node count -->
}<!-- ./ helper -->

@helper RenderChildNodes(IList<MenuNode> nodes)
{
 if (nodes.Count > 0)
 {
  foreach (var node in nodes)
  {
   string isActive = "";
   string isDisabled = "";
   if (node.Selected) { isActive = "active"; }
   if (!node.Enabled) { isDisabled = "disabled"; }

   <li class="breadcrumb-item @isActive">
    <a href="@node.Url" class=" @isDisabled">@node.Text</a>
   </li>
  }
 }
}

@RenderNodes(root.Children)

<script>
 if ($('.breadcrumb-item').length > 0)
  $('.breadcrumb').show();
 else
  $('.breadcrumb').hide();
</script>


问:
How to add jar file into the class-path while running another jar file during run time
I have a jar file(mts.jar) to run and it requires another jar(hook.jar) to be added at the runtime.

mts.jar is dependent on some of the classes present in hook.jar.
And our requirement is to pass this hook.jar in classpath at runtime while running mts.jar.

I have tried the combinations below:

```<code>java -cp "bin:hook.jar" mts.jar ccp.mts.server.websocket.Server

java -cp "hook.jar" mts.jar ccp.mts.server.websocket.Server
</code>```

I have also tried to set the classpath like below:

```<code>set CLASSPATH="C:\Users\Desktop\mts 4.3\hook.jar"
</code>```

then tried running as usual like below :

```<code>java -cp mts.jar ccp.mts.server.websocket.Server
</code>```

But I am getting class not found exception.

Where I might be wrong ?

答:
Make sure both files are inside the same directory, then call it like this

java -cp mts.jar;hook.jar ccp.mts.server.websocket.Server

You can also specify whole path, e.g.:

java -cp c:\mts.jar;c:\hook.jar ccp.mts.server.websocket.Server

To run your application, make sure that class: ccp.mts.server.websocket.Server is located inside one of the JAR files and has main method.

Body:
I have a jar file(mts.jar) to run and it requires another jar(hook.jar) to be added at the runtime.

mts.jar is dependent on some of the classes present in hook.jar.
And our requirement is to pass this hook.jar in classpath at runtime while running mts.jar.

I have tried the combinations below:

java -cp "bin:hook.jar" mts.jar ccp.mts.server.websocket.Server

java -cp "hook.jar" mts.jar ccp.mts.server.websocket.Server

I have also tried to set the classpath like below:

set CLASSPATH="C:\Users\Desktop\mts 4.3\hook.jar"

then tried running as usual like below :

java -cp mts.jar ccp.mts.server.websocket.Server

But I am getting class not found exception.

Where I might be wrong ?


问:
Why current working directory affects install path of setup.py? How to prevent that?
I have created a custom python package following this guide, so I have the following structure:

```<code>mypackage/     <-- VCS root
  mypackage/
    submodule1/
    submodule2/
  setup.py
</code>```

And setup.py contains exactly the same information as in the guide:

```<code>from setuptools import setup, find_packages

setup(name='mypackage',
      version='0.1',
      description='desc',
      url='vcs_url',
      author='Hodossy, Szabolcs',
      author_email='myemail@example.com',
      license='MIT',
      packages=find_packages(),
      install_requires=[
          # deps
      ],
      zip_safe=False)
</code>```

I have noticed if I go into the folder where setup.py is, and then call python setup.py install in a virtual environment, in site-packages the following structure is installed:

```<code>.../site-packages/mypackage-0.1-py3.6.egg/mypackage/
  submodule1/
  submodule2/
</code>```

but if I call it from one folder up like python mypackage/setup.py install, then the structure is the following:

```<code>.../site-packages/mypackage-0.1-py3.6.egg/mypackage/
  mypackage/
    submodule1/
    submodule2/
</code>```

This later one ruins all imports from my module, as the path is different for the submodules.

Could you explain what is happening here and how to prevent that kind of behaviour?

This is experienced with Python 3.6 on both Windows and Linux.

答:
Your setup.py does not contain any paths, but seems to only find the files via find_packages. So of course it depends from where you run it. The setup.py isn't strictly tied to its location. Of course you could do things like chdir to the basename of the setup file path in sys.argv[0], but that's rather ugly.

The question is, WHY do you want to build it that way? It looks more like you would want a structure like

```<code>mypackage-source
  mypackage
    submodule1
    submodule2
  setup.py
</code>```

And then execute setup.py from the work directory. If you want to be able to run it from anywhere, the better workaround would be to put a shellscript next to it, like

```<code>#!/bin/sh
cd ``basename $0``
python setup.py $@
</code>```

which separates the task of changing to the right directory (here I assume the directory with setup.py in the workdir) from running setup.py

Body:
I have created a custom python package following this guide, so I have the following structure:

mypackage/     <-- VCS root
  mypackage/
    submodule1/
    submodule2/
  setup.py

And setup.py contains exactly the same information as in the guide:

from setuptools import setup, find_packages

setup(name='mypackage',
      version='0.1',
      description='desc',
      url='vcs_url',
      author='Hodossy, Szabolcs',
      author_email='myemail@example.com',
      license='MIT',
      packages=find_packages(),
      install_requires=[
          # deps
      ],
      zip_safe=False)

I have noticed if I go into the folder where setup.py is, and then call python setup.py install in a virtual environment, in site-packages the following structure is installed:

.../site-packages/mypackage-0.1-py3.6.egg/mypackage/
  submodule1/
  submodule2/

but if I call it from one folder up like python mypackage/setup.py install, then the structure is the following:

.../site-packages/mypackage-0.1-py3.6.egg/mypackage/
  mypackage/
    submodule1/
    submodule2/

This later one ruins all imports from my module, as the path is different for the submodules.

Could you explain what is happening here and how to prevent that kind of behaviour?

This is experienced with Python 3.6 on both Windows and Linux.

Body:
Your setup.py does not contain any paths, but seems to only find the files via find_packages. So of course it depends from where you run it. The setup.py isn't strictly tied to its location. Of course you could do things like chdir to the basename of the setup file path in sys.argv[0], but that's rather ugly.

The question is, WHY do you want to build it that way? It looks more like you would want a structure like

mypackage-source
  mypackage
    submodule1
    submodule2
  setup.py

And then execute setup.py from the work directory. If you want to be able to run it from anywhere, the better workaround would be to put a shellscript next to it, like

#!/bin/sh
cd ``basename $0``
python setup.py $@

which separates the task of changing to the right directory (here I assume the directory with setup.py in the workdir) from running setup.py