问:
The "X" property on "Y" could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'
When I run my application and I click a specific button I get the error:

```<code>"The "X" property on "Y" could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'."
</code>```

Cool so I go to my Entity project, go to Y table, find X column, right-click and go to X's properties and find that Nullable is set to False.

I verify in SQL that in Y table, X is set to allow nulls, and it is.

I then go back to my Entity project, set Nullable to True, save and build and I receive:

```<code>Error 3031: Problem in mapping fragments starting at line 4049:Non-nullable column "X" in table "Y" is mapped to a nullable entity property.
</code>```

I've heard that deleting the table from the .edmx file and then re-adding it is a possibility but have never done that and don't understand the implications enough to feel comfortable in doing that.

I've heard that it could be in the view, could be in the stored procedure...

Also have heard that this is a bug.

Has anyone come across this and found an "across the board" fix or somewhat of a road map of sorts on where to look for this error?

Thanks!

答:
This may happen when the database table allows NULL and there are records that have a null value and you try to read this record with EF and the mapping class does not allow a null value.

The solution is either change the database table so that it does not allow null or change your class to allow null.

Body:
When I run my application and I click a specific button I get the error:

"The "X" property on "Y" could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'."

Cool so I go to my Entity project, go to Y table, find X column, right-click and go to X's properties and find that Nullable is set to False.

I verify in SQL that in Y table, X is set to allow nulls, and it is.

I then go back to my Entity project, set Nullable to True, save and build and I receive:

Error 3031: Problem in mapping fragments starting at line 4049:Non-nullable column "X" in table "Y" is mapped to a nullable entity property.

I've heard that deleting the table from the .edmx file and then re-adding it is a possibility but have never done that and don't understand the implications enough to feel comfortable in doing that.

I've heard that it could be in the view, could be in the stored procedure...

Also have heard that this is a bug.

Has anyone come across this and found an "across the board" fix or somewhat of a road map of sorts on where to look for this error?

Thanks!


来源: stackexchange

问:
RxSwift — background task without freezing UI
I would like to do some heavy lifting in the background thread of my iOS app and NOT freeze the UI while it is being performed. What I try is:

```<code>self.someDisposable = heavyLiftingFuncReturningObservable()
            .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
            .observeOn(MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] image in
                    // update UI
                },
                onError: { ... }
            )
</code>```

Why does the above not work as expected and how to make it work?

答:
I believe the problem lies in your implementation of .heavyLiftingFuncReturningObservable(), namely in the fact that apparently it starts working on current thread instead of waiting until being subscribed to and running on background scheduler. Solution for that is to use .deferred() inside of .heavyLiftingFuncReturningObservable() function.

See http://adamborek.com/top-7-rxswift-mistakes/

ContentLicense: CC BY-SA 3.0

Body:
I would like to do some heavy lifting in the background thread of my iOS app and NOT freeze the UI while it is being performed. What I try is:

self.someDisposable = heavyLiftingFuncReturningObservable()
            .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
            .observeOn(MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] image in
                    // update UI
                },
                onError: { ... }
            )

Why does the above not work as expected and how to make it work?

ContentLicense: CC BY-SA 4.0


问:
Take screenshot with Excel macro
```<code>Sub google()
    Set objIE = CreateObject("InternetExplorer.Application")
    WebSite = "www.google.com"
    With objIE
        .Visible = True
        .navigate WebSite
        Do While .Busy Or .readyState <> 4
            Application.SendKeys "({1068})", True
            DoEvents
        Loop
        AppActivate "Internet Explorer"
        ActiveSheet.Paste

        Dim shp As Shape
        With ActiveSheet
            Set shp = .Shapes(.Shapes.Count)
        End With
        shp.Height = 600
        shp.Width = 800
        .Document.Forms(0).Submit
        '.Quit
    End With
End Sub
</code>```

I am using this code to take screenshot using Excel VBA Macro. However, this code is taking a screenshot of my whole screen. I need the screenshot of a webpage alone. Can someone help me with this?

答:
PrtSc takes a screenshot of the entire desktop. To take a screenshot of the current application window use Alt+PrtSc.

```<code>Application.SendKeys "%{1068}", True
</code>```

Title: Take screenshot with Excel macro

Body:
Sub google()
    Set objIE = CreateObject("InternetExplorer.Application")
    WebSite = "www.google.com"
    With objIE
        .Visible = True
        .navigate WebSite
        Do While .Busy Or .readyState <> 4
            Application.SendKeys "({1068})", True
            DoEvents
        Loop
        AppActivate "Internet Explorer"
        ActiveSheet.Paste

        Dim shp As Shape
        With ActiveSheet
            Set shp = .Shapes(.Shapes.Count)
        End With
        shp.Height = 600
        shp.Width = 800
        .Document.Forms(0).Submit
        '.Quit
    End With
End Sub

I am using this code to take screenshot using Excel VBA Macro. However, this code is taking a screenshot of my whole screen. I need the screenshot of a webpage alone. Can someone help me with this?

Body:
PrtSc takes a screenshot of the entire desktop. To take a screenshot of the current application window use Alt+PrtSc.

Application.SendKeys "%{1068}", True


问:
Facebook conversion event callback
I cant find in the documentation if there is any callback functionality in the conversion tracking (https://developers.facebook.com/docs/ads-for-websites/tag-api)

In order to track an event you just need to call:

```<code>window._fbq = window._fbq || [];
window._fbq.push(['track', 'FBCONVERSIONCODE', {'value':'0.00','currency':'USD'}]);
</code>```

That is very similar to google analytics conversion code, only though they allow you to call a function when the ajax call finish:

```<code>ga('send', 'pageview', {
  'page': '/my-new-page',
  'hitCallback': function() {
    alert('analytics.js done sending data');
  }
});
</code>```

Is there a way to achieve the same functionality with Facebook API?

答:
As of today, Facebook still does not support it.
However, since I had this issue due to immediate redirect, I used the following solution:

basically I set on localStorage the variable I needed to track =>

```<code> window.localStorage.setItem('documentTitle', document.title);
</code>```

then I did the redirect, and on the targeted page I used the following to properly track fb event

```<code>if (typeof(fbq) !== 'undefined' && window.localStorage.getItem('documentTitle')) {
    fbq('track', 'Lead', {content_name: window.localStorage.getItem('documentTitle')});
    window.localStorage.removeItem('documentTitle');}
</code>```

Hope this helps someone ;)

PS: this will work only if the redirected page is on the same host of the initial page, since localStorage is unique per: protocol://host:port

Title: Facebook conversion event callback

Body:
I cant find in the documentation if there is any callback functionality in the conversion tracking (https://developers.facebook.com/docs/ads-for-websites/tag-api)

In order to track an event you just need to call:

window._fbq = window._fbq || [];
window._fbq.push(['track', 'FBCONVERSIONCODE', {'value':'0.00','currency':'USD'}]);

That is very similar to google analytics conversion code, only though they allow you to call a function when the ajax call finish:

ga('send', 'pageview', {
  'page': '/my-new-page',
  'hitCallback': function() {
    alert('analytics.js done sending data');
  }
});

Is there a way to achieve the same functionality with Facebook API?

Body:
As of today, Facebook still does not support it.
However, since I had this issue due to immediate redirect, I used the following solution:

basically I set on localStorage the variable I needed to track =>

 window.localStorage.setItem('documentTitle', document.title);

then I did the redirect, and on the targeted page I used the following to properly track fb event

if (typeof(fbq) !== 'undefined' && window.localStorage.getItem('documentTitle')) {
    fbq('track', 'Lead', {content_name: window.localStorage.getItem('documentTitle')});
    window.localStorage.removeItem('documentTitle');}

Hope this helps someone ;)

PS: this will work only if the redirected page is on the same host of the initial page, since localStorage is unique per: protocol://host:port


问:
How to refresh components
First of all, sorry if my question is too silly, I'm still new with Polymer 2.

I'm facing a little issue. I've created a custom component, where I load some dynamic data via xhr.
Everything seems to work correctly, but I've noticed that when I leave and come back to this view, the component has not changed, even if it raises all the xhr to get new data.

I'm wondering if the issue is that the data is updated, but the DOM is still the same.

Is it possible to force the system to "reload" the component each time I visit the page?

Thanks in advance.

答:
It's a custom "tree view component".

<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-if.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-repeat.html">
<link rel="import" href="../../bower_components/paper-collapse-item/paper-collapse-item.html">
<link rel="import" href="../../bower_components/vaadin-icons/vaadin-icons.html">
<link rel="import" href="../../bower_components/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="../../bower_components/iron-location/iron-location.html">

<link rel="import" href="../../portal_components/portal-measurement-units/portal-measurement-units.html">

<dom-module id="portal-tree-view">
     <template>

     <template is="dom-if" if=[[!loading]]>
          <template is="dom-repeat" items={{tree}}>
               <template is="dom-if" if="[[item.deploy]]">
                    <paper-collapse-item icon="icons:label" header="[[item.name]]" id="collapseitem" >
                         <portal-tree-view assets=[[item.children]] tasks=[[tasks]] results=[[results]] network=[[network]]></portal-tree-view>
                    </paper-collapse-item>
               </template>
               <template is="dom-if" if="[[item.mp]]">

                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                         <iron-icon class="icon-big" style="color: black; float: right; margin-top: 40px" icon="vaadin:info-circle-o" on-click="goDetail"></iron-icon>
                          [[item.name]]

                              <iron-icon class="icon-small" style="color: [[item.lastacq_status]]" icon="vaadin:spark-line"></iron-icon>
                              [[getLastAcq(item)]]

                               Speed: [[checkSpeed(item)]]

                               Acceleration: [[checkAcc(item)]]

                               Temperature: [[checkTemp(item)]]</item>

               </template>
               <template is="dom-if" if="[[item.transmitter]]">

                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                          [[item.name]]

                         <iron-icon class="icon-small" style="color: [[item.latcom_status]]" icon="settings-input-antenna"></iron-icon>
                         [[getLastCom(item)]]

               </template>
               <template is="dom-if" if="[[item.endpoint]]">

                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                          [[item.name]]

               </template>
          </template>
     </template>
     <template is="dom-if" if=[[loading]]>

     </template>
     <portal-lite-global-variables id="GLOBALS"></portal-lite-global-variables>
     <portal-measurement-units id="UNITS"></portal-measurement-units>
     <iron-location id="location"></iron-location>

</template>

</dom-module>```
</div>
</div>
</p>

<p>On this.$.UNITS I have a set of functions to make a conversion of values (Metric, Imperial, etc...).</p>

<p>The function checkSpeed(item) is executed each time I show the view.
Via console.log I can check that the value returned is always correct, but when leaving, I change the unity (from metric to imperial, for instance), and when I'm back again the view in the component remains in the old unities (even if the console.log in the function returns the correct value).</p>

<p>Hope it's useful.</p>

<p>Thanks in advance.</p>

<p>[EDIT]</p>

<p>Finally found out the solution here: https://easyusedev.wordpress.com/2015/11/06/dynamically-loading-polymer-elements-on-the-fly/</p>

<p>In order to be sure that the component is refresed each time I call the view, create the component manually when everything's ready to load the component:</p>

```var tree = document.createElement('portal-tree-view');
```

<p>And, when leaving, I remove it:</p>

```var element = this.$.container.querySelector("portal-tree-view");
element.parentNode.removeChild(element)
```

En cualquier caso, muchas gracias por tu tiempo Álvaro.

Best regards.

Title: How to refresh components

Body:
It's a custom "tree view component".

<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-if.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-repeat.html">
<link rel="import" href="../../bower_components/paper-collapse-item/paper-collapse-item.html">
<link rel="import" href="../../bower_components/vaadin-icons/vaadin-icons.html">
<link rel="import" href="../../bower_components/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="../../bower_components/iron-location/iron-location.html">

<link rel="import" href="../../portal_components/portal-measurement-units/portal-measurement-units.html">

<dom-module id="portal-tree-view">
     <template>
     <style include="iron-flex iron-flex-alignment">
     <style>
     :host {
          display: block;
     }
     .icon
     {
          margin-right: 24px;
          --iron-icon-height: 34px;
          --iron-icon-width: 34px;
          color: var(--disabled-text-color);
     }

     .icon-small
     {
          margin-right: 24px;
          --iron-icon-height: 20px;
          --iron-icon-width: 20px;
          color: var(--disabled-text-color);
     }

     .icon-big
     {
          margin-right: 24px;
          --iron-icon-height: 40px;
          --iron-icon-width: 40px;
          color: var(--disabled-text-color);
     }

     .alert {
          color: orange;
     }
     .emergency {
          color: red;
     }
     </style>
     <template is="dom-if" if=[[!loading]]>
          <template is="dom-repeat" items={{tree}}>
               <template is="dom-if" if="[[item.deploy]]">
                    <paper-collapse-item icon="icons:label" header="[[item.name]]" id="collapseitem" >
                         <portal-tree-view assets=[[item.children]] tasks=[[tasks]] results=[[results]] network=[[network]]></portal-tree-view>
                    </paper-collapse-item>
               </template>
               <template is="dom-if" if="[[item.mp]]">
                    <span style= "font-size: var(--paper-font-subhead_-_font-size); margin-left: 15px;">
                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                         <iron-icon class="icon-big" style="color: black; float: right; margin-top: 40px" icon="vaadin:info-circle-o" on-click="goDetail"></iron-icon>
                          [[item.name]] <br/>
                          <span style="margin-left: 96px">
                              <iron-icon class="icon-small" style="color: [[item.lastacq_status]]" icon="vaadin:spark-line"></iron-icon>
                              <span style="color: [[checkLastAcqStatus(item)]]">[[getLastAcq(item)]]</span>
                         </span><br/>
                          <span style="margin-left: 86px">
                               Speed: <span style="color: [[checkSpeedStatus(item)]]">[[checkSpeed(item)]] </span>
                          </span><br/>
                          <span style="margin-left: 86px">
                               Acceleration: <span style="color: [[checkAccStatus(item)]]">[[checkAcc(item)]]</span>
                          </span><br/>
                          <span style="margin-left: 86px">
                               Temperature: <span style="color: [[checkTempStatus(item)]]">[[checkTemp(item)]]</item>
                          </span><br/>
                    </span><br/>
               </template>
               <template is="dom-if" if="[[item.transmitter]]">
                    <span style= "font-size: var(--paper-font-subhead_-_font-size); margin-left: 15px;">
                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                          [[item.name]]<br/>
                    </span>
                    <span style="margin-left: 96px">
                         <iron-icon class="icon-small" style="color: [[item.latcom_status]]" icon="settings-input-antenna"></iron-icon>
                         <span style="color: [[checkLastComStatus(item)]]">[[getLastCom(item)]]</span>
                    </span><br/>
               </template>
               <template is="dom-if" if="[[item.endpoint]]">
                    <span style= "font-size: var(--paper-font-subhead_-_font-size); margin-left: 15px;">
                         <iron-icon class="icon" icon="label-outline"></iron-icon>
                          [[item.name]]<br/>
                    </span>
               </template>
          </template>
     </template>
     <template is="dom-if" if=[[loading]]>
          <div class="center-center layout horizontal">
               <img src="portal_components/portal-tree-view/loading.gif" />
          </div>
     </template>
     <portal-lite-global-variables id="GLOBALS"></portal-lite-global-variables>
     <portal-measurement-units id="UNITS"></portal-measurement-units>
     <iron-location id="location"></iron-location>

</template>

<script>
/**
* `portal-tree-view`
*
*
* @customElement
* @polymer
* @demo demo/index.html
*/
class portalTreeView extends Polymer.Element {
     static get is() { return 'portal-tree-view'; }
     static get properties() {
          return {
               assets: {
                    type: Array,
                    notify: true,
               },
               tasks: {
                    type: Object,
                    notify: true,
               },
               results: {
                    type: Object,
                    notify: true,
               },
               network: {
                    type: Array,
                    notify: true
               },
               tree: {
                    type: Array,
                    notify: true
               },
               trigger: {
                    type: Boolean,
                    observer: '_trigger'
               }
          };
     }
     static get observers() {
          return [
               'fullAssets(tasks, results)'
          ]
     }

     _trigger()
     {
          if (this.trigger)
          {
               this.ready();
               console.log("trigger")
               this.fullAssets();
          }
     }

     toFixed(value, precision) {
        return Number(value).toFixed(precision);
      }
     goDetail(event)
     {
          var item = event.model.item;
          this.$.location.path="portal-lite-asset-details/"+item._id;

     }
     checkLastComStatus(item)
     {
          if (this.network[item.mac] !== undefined)
          {
               var current = this.$.GLOBALS.getUTCTimeStamp(new Date());
               if (current < this.$.GLOBALS.getUTCTimeStamp(new Date(this.network[item.mac].last_com)) + 54000)
                    return 'orange';
               else if (current > this.$.GLOBALS.getUTCTimeStamp(new Date(this.network[item.mac].last_com)) + 54000)
                    return 'red';
          }

     }
     getLastAcq(item)
     {
          if (this.results[item._id] !== undefined)
               return new Date(this.results[item._id].acqend).toLocaleDateString() + " " + new Date(this.results[item._id].acqend).toLocaleTimeString();
     }
     getLastCom(item)
     {
          if (this.network[item.mac] !== undefined)
               return new Date(this.network[item.mac].last_com).toLocaleDateString() + " " + new Date(this.network[item.mac].last_com).toLocaleTimeString();
     }
     checkLastAcqStatus(item)
     {
          if (this.tasks[item._id] !== undefined)
               return this.$.GLOBALS.checkTask(this.tasks[item._id], this.results[item._id]);
     }
     checkSpeed(item)
     {
          if (this.results[item._id] !== undefined)
          {
               if (this.results[item._id].globals.vib !== undefined &&
                    this.results[item._id].globals.vib.v !== undefined)
                    {
                         var aux = this.$.UNITS.speed(this.results[item._id].globals.vib.v[0]);
                         return aux.value.toFixed(2) + " " + aux.desc;
                    }
          }
     }

     checkSpeedStatus(item)
     {
          if (this.results[item._id] !== undefined)
          {

               if (this.results[item._id].globals.vib !== undefined &&
                    this.results[item._id].globals.vib.v !== undefined)
               {
                    if (this.results[item._id].globals.vib.v[1] == 1) return "orange";
                    else if (this.results[item._id].globals.vib.v[1] == 2) return "red";
               }
          }
     }

     checkAccStatus(item)
     {
          if (this.results[item._id] !== undefined)
          {
               if (this.results[item._id].globals.vib !== undefined &&
                    this.results[item._id].globals.vib.a !== undefined)
               {
                    if (this.results[item._id].globals.vib.a[1] == 1) return "orange";
                    else if (this.results[item._id].globals.vib.a[1] == 2) return "red";
               }
          }
     }

     checkTempStatus(item)
     {
          if (this.results[item._id] !== undefined)
               if (this.results[item._id].globals.temp !== undefined &&
                    this.results[item._id].globals.temp !== null)
               {
                    if (this.results[item._id].globals.temp[1] == 1) return "orange";
                    else if (this.results[item._id].globals.temp[1] == 2) return "red";
               }
     }
     checkAcc(item)
     {
          if (this.results[item._id] !== undefined)
          {

               if (this.results[item._id].globals.vib !== undefined &&
                    this.results[item._id].globals.vib.a !== undefined)
               {
                    var aux = this.$.UNITS.g(this.results[item._id].globals.vib.a[0]);
                    return aux.value.toFixed(2) + " " + aux.desc;
               }
          }
     }

     checkTemp(item)
     {
          if (this.results[item._id] !== undefined)
          {
               if (this.results[item._id].globals.temp !== undefined &&
                    this.results[item._id].globals.temp !== null)
               {
                    var aux = this.$.UNITS.temp(this.results[item._id].globals.temp[0]);
                    return aux.value.toFixed(1) + " " + aux.desc;
               }
          }
     }

     fullAssets()
     {
          if (this.assets !== undefined && this.network !== undefined)
          {
               this.loading = false;
               this.assets.sort(function(d1,d2)
               {
                    if (d1.children.length > 0) return -1;
                    return 1;
               });
               for (var i = 0; i < this.assets.length; i++)
               {
                    this.assets[i].endpoint = false;
                    this.assets[i].mp = false;
                    this.assets[i].transmitter = false;
                    if (this.assets[i].children.length === 0)
                         this.assets[i].endpoint = true;
                    if (this.assets[i].t == 33554435)
                    {
                         this.assets[i].endpoint = false;
                         this.assets[i].transmitter = true;
                         this.assets[i].mac = this.assets[i].optionals.mac.toUpperCase();
                    }
                    if (this.assets[i].t == 16777218)
                    {
                         this.assets[i].endpoint = false;
                         this.assets[i].mp = true
                    }
                    this.assets[i].deploy = !this.assets[i].mp && !this.assets[i].endpoint && !this.assets[i].transmitter;
               }
               this.notifyPath('tree', this.assets);
          }
     }
     constructor()
     {
          super();
          this.loading = true;
          this.queue_results = 0;
     }
     ready()
     {
          super.ready();
     }
}
window.customElements.define(portalTreeView.is, portalTreeView);
</script>
</dom-module>

On this.$.UNITS I have a set of functions to make a conversion of values (Metric, Imperial, etc...).

The function checkSpeed(item) is executed each time I show the view.
Via console.log I can check that the value returned is always correct, but when leaving, I change the unity (from metric to imperial, for instance), and when I'm back again the view in the component remains in the old unities (even if the console.log in the function returns the correct value).

Hope it's useful.

Thanks in advance.

[EDIT]

Finally found out the solution here: https://easyusedev.wordpress.com/2015/11/06/dynamically-loading-polymer-elements-on-the-fly/

In order to be sure that the component is refresed each time I call the view, create the component manually when everything's ready to load the component:

var tree = document.createElement('portal-tree-view');

And, when leaving, I remove it:

var element = this.$.container.querySelector("portal-tree-view");
element.parentNode.removeChild(element)

En cualquier caso, muchas gracias por tu tiempo Álvaro.

Best regards.


问:
Creating a calculator script
I am trying to make a calculator with a bash script.
 The user enters a number, chooses whether they wish to add, subtract, multiply or divide. Then the user enters a second number and is able to choose whether to do the sum, or add, subtract, multiply or divide again on a loop.

I cannot rack my head around this right now

```<code>echo Please enter a number
read number

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide
read operation

case $operation in
    1) math='+';;
    2) math='-';;
    3) math='*';;
    4) math='/';;
    *) math='not an option, please select again';;
esac
echo "$number $math"

echo Please enter a number
read number2

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide, 5: Equals
read operation2
case $operation2 in
    1)math2='Add';;
    2)math2='Subtract';;
    3)math2='Multiply';;
    4)math2='Divide';;
    5)math2='Equals';;
    *)math2='not an option, please select again';;
esac
echo You have selected $math2

exit 0
</code>```

This is what I have done so far, but can anyone help me work out how to loop back on the calculator?

答:
```<code>#calculator

while (true) # while loop 1
do
echo "enter first no"
read fno
if [ $fno -eq $fno 2>/dev/null ]; # if cond 1 -> checking integer or not
then
c=1
else
echo "please enter an integer"
c=0
fi # end of if 1
if [ $c -eq 1 ]; #if 2
then
break
fi # end of if 2
done # end of whie 1

while(true) #while loop 2
do
echo "enter second no"
read sno
if [ $sno -eq $sno >/dev/null 2>&1 ] # if cond 3 -> checking integer or not
then
c=1
else
echo "please enter an integer"
c=0
fi # end of if 3
if [ $c -eq 1 ] # if cond 4
then
break
fi # end of if 4
done #2

while(true) # while loop 3
do
printf "enter the operation (add,div,mul,sub) of $fno and $sno\n"
read op
count=0
##addition

if [ $op = add ] #if cond 5
then
echo "$fno+$sno is `expr $fno + $sno`"

#multiplication

elif [ $op = mul ];
then
echo "$fno*$sno is `expr $fno \* $sno`"

#substraction

elif [ $op = sub ]
then
while(true) #while loop 3.1
do
printf "what do you want to do??? \n 1. $fno-$sno \n 2. $sno-$fno"
printf "\n press the option you want to perform?(1 or 2)\n"
read opt
if [ $opt = 1 ] #if cond 5.1
then
echo "$fno-$sno is `expr $fno - $sno`"
break
elif [ $opt = 2 ]
then
echo " $sno-$fno  is `expr $sno - $fno`"
break
else "please enter valid options to proceed(1 or 2)";
clear
fi #end of if 5.1
done  # end of 3.1

#division
elif [ $op = div ]
then
while(true) # whilw loop 3.2
do
printf "what do you want to do??? \n 1. $fno/$sno \n 2. $sno/$fno"
printf "\n press the option you want to perform?(1 or 2)\n"
read opt
if [ $opt = 1 ] #if cond 5.2
then
echo "$fno divided by $sno is  `expr $fno / $sno`"
break
elif [ $opt = 2 ]
then
echo " $sno divided by $fno  is `expr $sno / $fno`"
break
else
clear
fi #end of if 5.2
done  # end of 3.2
else
echo "valid option please!!!"
count=1
fi # end of if 5

if [ $count -eq 0 ] #if cond 6
then
echo "Do you want to do more ops"
echo "(y/n)"
read ans
clear
if [ $ans = n ] # if 6.1
then
break
fi # end of if 6.1
fi #end of if 6
done  #end of while 3
</code>```

Title: Creating a calculator script

Body:
I am trying to make a calculator with a bash script.
 The user enters a number, chooses whether they wish to add, subtract, multiply or divide. Then the user enters a second number and is able to choose whether to do the sum, or add, subtract, multiply or divide again on a loop.

I cannot rack my head around this right now

echo Please enter a number
read number

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide
read operation

case $operation in
    1) math='+';;
    2) math='-';;
    3) math='*';;
    4) math='/';;
    *) math='not an option, please select again';;
esac
echo "$number $math"

echo Please enter a number
read number2

echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide, 5: Equals
read operation2
case $operation2 in
    1)math2='Add';;
    2)math2='Subtract';;
    3)math2='Multiply';;
    4)math2='Divide';;
    5)math2='Equals';;
    *)math2='not an option, please select again';;
esac
echo You have selected $math2

exit 0

This is what I have done so far, but can anyone help me work out how to loop back on the calculator?


问:
PHP file not opening with html head tag
When I open this php file, it does not load:

```<code><?php
    echo "I am awesome";
?>
<html>
<head> </head>
</html>
</code>```

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.

答:
First make sure that your Apache is started successfully (either in xampp or wamp).

If Apache is not started. Try closing applications that might use port 80 of your computer.

OR

Change server port in xampp or wamp configurations.
Here is guides to perform that:

Change port in xampp

Change port in wamp

Title: PHP file not opening with html head tag

Body:
When I open this php file, it does not load:

<?php
    echo "I am awesome";
?>

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.


问:
UWP app webview get url and append params whenever there is Navigation starting
I am working on a Universal Windows Platform Web App.where i am showing just a Web View. what i want is whenever there is a transition/Navigation i want to attach few parameters with URL inside NavigationStartingor where to attach parameter.Help appreciated

答:
This has been solved one can check if the URL has the specified parameters or not. and then cancel the Navigation and provides new URL

```<code> private void OnNavigationStaring(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        if(!workingProgressRing.IsActive && (workingProgressRing.Visibility != Visibility.Visible)){
            this.ShowHideUiControls(true);
        }

        if (!args.Uri.ToString().Contains("yourcheck"))
        {
            args.Cancel = true;
            string url_new = args.Uri.ToString() + "&" + myDetails[0] + "&" + myDetails[1] + "&" + myDetails[2];

            webView.Navigate(new Uri(url_new, UriKind.Absolute));
        }
        Debug.WriteLine("Navigation Starting",args.Uri.ToString());
    }
</code>```

Body:
This has been solved one can check if the URL has the specified parameters or not. and then cancel the Navigation and provides new URL

 private void OnNavigationStaring(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        if(!workingProgressRing.IsActive && (workingProgressRing.Visibility != Visibility.Visible)){
            this.ShowHideUiControls(true);
        }

        if (!args.Uri.ToString().Contains("yourcheck"))
        {
            args.Cancel = true;
            string url_new = args.Uri.ToString() + "&" + myDetails[0] + "&" + myDetails[1] + "&" + myDetails[2];

            webView.Navigate(new Uri(url_new, UriKind.Absolute));
        }
        Debug.WriteLine("Navigation Starting",args.Uri.ToString());
    }


问:
Get react native client, firebase token
I'm a react-native newbee, trying to build an app which will receive notifications from an app server. The flow will be like this: App server -> FCM Cloud -> App client(android or ios).

I've started with [1] and I'm trying to generate and get a device token to be sent to the app server for identification. However I'm getting an error:

```<code>import * as firebase from 'firebase';

const defaultAppConfig = {
   ...
};

var defaultApp = firebase.initializeApp(defaultAppConfig);
var defaultMessaging = firebase.messaging();  // -> here, messaging not found
</code>```

Can someone help me figure out how to get a reference to the cloud messaging object, and get that token, eventually?

[1] https://facebook.github.io/react-native/docs/getting-started.html

答:
Firebase SDK is made for the web so some functionalities won't work as you expect them to work, also to use push notifications in your project you'll need to write some native code to ask for permission in the user device and import firebase messaging in Android and almost the same (but with a little bit more configuration, notifications certificate from Apple and of course a paid developer account) to run it on iOS.

I'll recommend you to use react-native-firebase as they have a lot of very well writen documentations that will help you configure everything.

Hope this helps! :)

Title: Get react native client, firebase token

Body:
I'm a react-native newbee, trying to build an app which will receive notifications from an app server. The flow will be like this: App server -> FCM Cloud -> App client(android or ios).

I've started with [1] and I'm trying to generate and get a device token to be sent to the app server for identification. However I'm getting an error:

import * as firebase from 'firebase';

const defaultAppConfig = {
   ...
};

var defaultApp = firebase.initializeApp(defaultAppConfig);
var defaultMessaging = firebase.messaging();  // -> here, messaging not found

Can someone help me figure out how to get a reference to the cloud messaging object, and get that token, eventually?

[1] https://facebook.github.io/react-native/docs/getting-started.html


问:
Pivot For Dynamic Column Value
May Some One Please help me how to get the below output.
SQL SERVER 2008

```<code>CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'
</code>```

result for each Generic Name , Design, Material,other, Power and TYPE as Value of the column under Column Name as Desc1, Desc2....DescN

```<code>**Generic Name    DESC1   ,DESC2  ,DESC2, DESC4
RESISTOR        POWER   , Type    DESIGN, Material**
</code>```

答:
Here is how to do it dynamicly:

```<code>CREATE TABLE T1
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT T1

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material';

DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description)
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description) + ' AS DESC'+CAST(row_number () over (order by (Description)) as varchar(10))
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT [Generic Name], '+ @Sel+ N'
FROM T1
    pivot
    (
           MAX(Description) For Description IN ('+ @Cols + N')
        ) P';

EXECUTE( @SQL);
</code>```

Results:

```<code>+--------------+--------+----------+-------+-------+
| Generic Name | DESC1  |  DESC2   | DESC3 | DESC4 |
+--------------+--------+----------+-------+-------+
| RESISTOR     | DESIGN | Material | POWER | Type  |
+--------------+--------+----------+-------+-------+
</code>```

Demo

Title: Pivot For Dynamic Column Value

Body:
May Some One Please help me how to get the below output.
SQL SERVER 2008

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'

result for each Generic Name , Design, Material,other, Power and TYPE as Value of the column under Column Name as Desc1, Desc2....DescN

**Generic Name    DESC1   ,DESC2  ,DESC2, DESC4
RESISTOR        POWER   , Type    DESIGN, Material**

Body:
Here is how to do it dynamicly:

CREATE TABLE T1
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT T1

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material';

DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description)
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description) + ' AS DESC'+CAST(row_number () over (order by (Description)) as varchar(10))
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT [Generic Name], '+ @Sel+ N'
FROM T1
    pivot
    (
           MAX(Description) For Description IN ('+ @Cols + N')
        ) P';

EXECUTE( @SQL);

Results:

+--------------+--------+----------+-------+-------+
| Generic Name | DESC1  |  DESC2   | DESC3 | DESC4 |
+--------------+--------+----------+-------+-------+
| RESISTOR     | DESIGN | Material | POWER | Type  |
+--------------+--------+----------+-------+-------+

Demo


问:
Printing parsed JSON in Python
Assuming this is the .JSON file I have to parse:

```<code>{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}
</code>```

How would I go about printing the total values like:

```<code>1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0
</code>```

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

```<code>import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)
</code>```

答:
You are almost there:

```<code>for item in stats.items():
    print '%d - %d' % item
</code>```

What this does is that stats is already a dict. Looking at the documentation, there is the items method which returns "a copy of the dictionary’s list of (key, value) pairs". And each pair is formatted as two numbers, i.e. '%d - %d'.

Title: Printing parsed JSON in Python

Body:
Assuming this is the .JSON file I have to parse:

{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}

How would I go about printing the total values like:

1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)

Body:
You are almost there:

for item in stats.items():
    print '%d - %d' % item

What this does is that stats is already a dict. Looking at the documentation, there is the items method which returns "a copy of the dictionary’s list of (key, value) pairs". And each pair is formatted as two numbers, i.e. '%d - %d'.


问:
How to get all the app users current location on map?
I am making two apps. one which is for users which is simply doing work of getting user location. I have created app to get user location. now I want to make another app for admin which will get the location of all the users who have installed that app. Now the problem is how to distinguish users data while sending it to the server.

I don't want the user to sign up. just install the app and admin can view the user. I am thinking to make database if I will somehow be able to send some id with user's last location. If there's any alternative for this please suggest.

答:
You can use android is for distinguish user.

import android.provider.Settings.Secure;

```<code>private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);
</code>```

Body:
You can use android is for distinguish user.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);


问:
How to fix an error "java.lang.IllegalStateException: Layout state should be one of 100 but it is 10"?
I have the error java.lang.IllegalStateException: Layout state should be one of 100 but it is 10. Beneath the followed information of the error.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Layout state should be one of 100 but it is 10
at android.support.v7.widget.RecyclerView$State.assertLayoutStep(RecyclerView.java:10053)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3045)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2917)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:596)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2029)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1850)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1143)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4667)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Please, help me to correct this error. Thanks

答:
I had meet this error too,My error is produced by the method onBindViewHolder, caused by classCastException.But the exception stack not shown this clearly.

I think this may help.

Body:
I have the error java.lang.IllegalStateException: Layout state should be one of 100 but it is 10. Beneath the followed information of the error.

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Layout state should be one of 100 but it is 10
at android.support.v7.widget.RecyclerView$State.assertLayoutStep(RecyclerView.java:10053)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3045)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2917)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:596)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13916)
at android.view.ViewGroup.layout(ViewGroup.java:4424)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2029)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1850)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1143)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4667)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)

Please, help me to correct this error. Thanks


问:
How to add two stored values by load in assembly using 1 addressing mode?
I want to add two values x and y which are stored but I only want to use 1 addressing mode.<br>
Following is the example: </p>

```<code>lda x
sta x
// store the final result in x

lda y
sta y
// store the final result in y

//now I want to add x and y like x+y. Is the following pattern correct? whats wrong?
lda x
lda y
add x
sta x
</code>```

答:
Is the following pattern correct? whats wrong?

No.

Addition is always done with the accumulator.

There is no ADD instruction only ADC add with carry

You need to manage the carry flag.

If you have two memory locations x and y and you want to store the result in x, the cannonical way to do this is:

```<code>; x = x + y
LDA x      ; Load one operand into the accumulator.
CLC        ; Clear the carry flag so it does not get added into the result
ADC y      ; Add the other operand
STA x      ; Store the operand back to x
</code>```

You can use any address mode for y and any address mode for x except immediate.

If x and y are the addresses of 16 bit values, the 16 bit addition will look like this:

```<code>LDA x      ; Load one operand into the accumulator.
CLC        ; Clear the carry flag so it does not get added into the result
ADC y      ; Add the other operand
STA x      ; Store the operand back to x
LDA x+1    ; Now do the high byte
ADC y+1    ; Note we do not clear the carry this time.
STA x+1
</code>```

Body:
I want to add two values x and y which are stored but I only want to use 1 addressing mode.

Following is the example:

lda x
sta x
// store the final result in x

lda y
sta y
// store the final result in y

//now I want to add x and y like x+y. Is the following pattern correct? whats wrong?
lda x
lda y
add x
sta x

Body:
Is the following pattern correct? whats wrong?

No.

Addition is always done with the accumulator.

There is no ADD instruction only ADC add with carry

You need to manage the carry flag.

If you have two memory locations x and y and you want to store the result in x, the cannonical way to do this is:

; x = x + y
LDA x      ; Load one operand into the accumulator.
CLC        ; Clear the carry flag so it does not get added into the result
ADC y      ; Add the other operand
STA x      ; Store the operand back to x

You can use any address mode for y and any address mode for x except immediate.

If x and y are the addresses of 16 bit values, the 16 bit addition will look like this:

LDA x      ; Load one operand into the accumulator.
CLC        ; Clear the carry flag so it does not get added into the result
ADC y      ; Add the other operand
STA x      ; Store the operand back to x
LDA x+1    ; Now do the high byte
ADC y+1    ; Note we do not clear the carry this time.
STA x+1


问:
Google maps API - compute distance between clicked area and const location
I would like to compute distance between a clicked area and const lat lng location.

I would like to combine these two pieces of code, but somehow I am not able to do it.

```<code><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

<script>
var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = HERE I WOULD LIKE TO HAVE A POSITION OF THE PLACED MARKER;

alert(calcDistance(p1, p2));

//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
</script>
</code>```

and

```<code>google.maps.event.addListener(map, 'click', function(event){
placeMarker(event.latLng);
});

function placeMarker(location) {
var marker = new google.maps.Marker({
    position: location,
    map: map,
    draggable: true
});
}
</code>```

答:
It looks like you just need to move the code that alerts the distance into the correct place...</p>

```<code>google.maps.event.addListener(map, 'click', function(event){
    placeMarker(event.latLng);

    var p1 = new google.maps.LatLng(45.463688, 9.18814);

    setTimeout(function() {
        alert(calcDistance(p1, event.latLng));
    }, 500);
});
</code>```

Body:
I would like to compute distance between a clicked area and const lat lng location.

I would like to combine these two pieces of code, but somehow I am not able to do it.

and

google.maps.event.addListener(map, 'click', function(event){
placeMarker(event.latLng);
});

function placeMarker(location) {
var marker = new google.maps.Marker({
    position: location,
    map: map,
    draggable: true
});
}

Body:
It looks like you just need to move the code that alerts the distance into the correct place...

google.maps.event.addListener(map, 'click', function(event){
    placeMarker(event.latLng);

    var p1 = new google.maps.LatLng(45.463688, 9.18814);

    setTimeout(function() {
        alert(calcDistance(p1, event.latLng));
    }, 500);
});


问:
variable === undefined vs. typeof variable === "undefined"
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

Global Variables: typeof variable === "undefined"

Local Variables: variable === undefined

Properties: object.prop === undefined

Why does jQuery use one approach for global variables and another for locals and properties?

答:
I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.

I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.]  However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.

For example, the following is used in IE for parsing XML:

```<code>var x = new ActiveXObject("Microsoft.XMLDOM");
</code>```

To check whether it has a loadXML method safely:

```<code>typeof x.loadXML === "undefined"; // Returns false
</code>```

On the other hand:

```<code>x.loadXML === undefined; // Throws an error
</code>```

UPDATE

Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to @LinusKleen for reminding me. For example:

```<code>typeof someUndeclaredVariable; // "undefined"
someUndeclaredVariable === undefined; // throws a ReferenceError
</code>```

Bottom line: always use the typeof check.

Body:
I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.

I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.]  However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.

For example, the following is used in IE for parsing XML:

var x = new ActiveXObject("Microsoft.XMLDOM");

To check whether it has a loadXML method safely:

typeof x.loadXML === "undefined"; // Returns false

On the other hand:

x.loadXML === undefined; // Throws an error

UPDATE

Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to @LinusKleen for reminding me. For example:

typeof someUndeclaredVariable; // "undefined"
someUndeclaredVariable === undefined; // throws a ReferenceError

Bottom line: always use the typeof check.


问:
Get number of years between two timestamp objects in Java
I am having two timestamp objects.

```<code>java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
System.out.println(timestamp);

Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
System.out.println(ctimestamp);
System.out.println(ctimestamp.getYear() - timestamp.getYear());
</code>```

Output :

```<code>1800-01-01 00:00:00.0
2017-11-13 11:42:44.56
217
</code>```

It works and gives proper value of 217. The problem here is getYear() is deprecated.

Is there any other way to get it, so that I don't get any deprecation warnings?

答:
API java.time

We can easily convert a  java.sql.Timestamp into a LocalDateTime using Timestamp.toLocalDateTime().

From that LocalDateTime, we can extract the LocalDate using LocalDateTime.toLocalDate().

Now that we have a LocalDate, we can use a Period. A complete explanation is available on Oracle : Period and Duration

```<code>java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
java.time.LocalDate lDate = timestamp.toLocalDateTime().toLocalDate();

java.time.Period prd = java.time.Period.between(lDate, java.time.LocalDate.now());

System.out.println("Years : " + prd.getYears());
System.out.println("Month : " + prd.getMonths());
System.out.println("Days : " + prd.getDays());
</code>```

And here you have on today date (2017-11-13)

```<code>Years : 217
Month : 10
Days : 12
</code>```

As suggested by Ole V.V, if you only need a specific field, you can use ChronoUnit like :

```<code>java.time.temporal.ChronoUnit.YEARS.between(
        timestamp.toLocalDateTime(),
        java.time.LocalDateTime.now()
)
</code>```

Note : I used absolute path here for my classes, if this is shocking, please let me know, I will clean this to be more readable.

Body:
I am having two timestamp objects.

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
System.out.println(timestamp);

Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
System.out.println(ctimestamp);
System.out.println(ctimestamp.getYear() - timestamp.getYear());

Output :

1800-01-01 00:00:00.0
2017-11-13 11:42:44.56
217

It works and gives proper value of 217. The problem here is getYear() is deprecated.

Is there any other way to get it, so that I don't get any deprecation warnings?

Body:
API java.time

We can easily convert a  java.sql.Timestamp into a LocalDateTime using Timestamp.toLocalDateTime().

From that LocalDateTime, we can extract the LocalDate using LocalDateTime.toLocalDate().

Now that we have a LocalDate, we can use a Period. A complete explanation is available on Oracle : Period and Duration

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
java.time.LocalDate lDate = timestamp.toLocalDateTime().toLocalDate();

java.time.Period prd = java.time.Period.between(lDate, java.time.LocalDate.now());

System.out.println("Years : " + prd.getYears());
System.out.println("Month : " + prd.getMonths());
System.out.println("Days : " + prd.getDays());

And here you have on today date (2017-11-13)

Years : 217
Month : 10
Days : 12

As suggested by Ole V.V, if you only need a specific field, you can use ChronoUnit like :

java.time.temporal.ChronoUnit.YEARS.between(
        timestamp.toLocalDateTime(),
        java.time.LocalDateTime.now()
)

Note : I used absolute path here for my classes, if this is shocking, please let me know, I will clean this to be more readable.


问:
How to change the CSS attributes inside the particulate class using only JavaScript
I know how to change the class of div using JavaScript classList.add and classList.add. But my purpose is change data inside the class using JavaScript.

as example,

let think I have class called example,

```<code>.example {
position:bsolute;
width:100;
}
</code>```

Is it possible change the width of example class using JavaScript. If yes, how can I change it?

Pure JavaScript only. cant use any libraries.

答:
Here is a javascript solution:

var example = document.getElementByClassName("example");
example.style.width = "50px";```

Body:
I know how to change the class of div using JavaScript classList.add and classList.add. But my purpose is change data inside the class using JavaScript.

as example,

let think I have class called example,

.example {
position:bsolute;
width:100;
}

Is it possible change the width of example class using JavaScript. If yes, how can I change it?

Pure JavaScript only. cant use any libraries.


问:
Visual Studio 2017 and WinJS - Autocomplete for "Windows" namespace
I'm writing a UWP windows 10 app with html/javascript in VS 2017. When I used to write Windows8 apps in VS 2015, the "Windows" namespace would autocomplete for me, intellisense and all that, but now it's not.

For example, if I have var vault = new Windows.Security.Credentials.PasswordVault();, I don't get any autocomlete options with vault., but I would have on VS2015.

What's going wrong? How can I add whatever files necessary to my project to get the intellisense working for this?

答: I discovered it was because Resharper was hiding some intellisense from me. When I turn it off I get the Windows apis back.</p>


问:
How to make friendly custom URL for deployed app
After deploying an App Maker app, how does one set a friendly URL, or custom domain, or make it appear in the list of your G Suite domain apps?

I've looked through App Settings and Edit Deployment, but there is nothing to be found, the unique deployment URL's a fairly difficult to remember.

答:
This is currently not possible to my knowledge. Workarounds:
- add icon to the G Suite start button (via internal marketplace app)
- create a start workspace in Google Sites for all of your apps (or use Google orbitera)
- push a bookmark to your apps via Chrome management (login to chrome required by your user)</p>


问:
unable to hide div in angular js using ng-if
unable to hide div on loading page.
I want to show the div if the value of array is empty.</p>

```<code>    <div ng-hide="loading"  ng-if="users== null || users.length === 0" >
        <h3>No Result Found</h3>
    </div>
</code>```

答:
This may work for you</p>

```<code><div ng-if="!loading && (typeof(users) === 'undefined'  || users== null || users.length === 0)" >
    <h3>No Result Found</h3>
</div>
</code>```

Body:
unable to hide div on loading page.
I want to show the div if the value of array is empty.

No Result Found

Body:
This may work for you

<div ng-if="!loading && (typeof(users) === 'undefined'  || users== null || users.length === 0)" >
    <h3>No Result Found</h3>
</div>


问:
How do I create expandable lists on Appcelerator Titanium?
Is there any way to create expandable lists on Titanium? I want the ListItem to expand and show extra info when the user clicks on a dropdown icon, just like in the image below:

I'm not sure if this can be achieved in Titanium.

答:
This should not be a Titanium specific question because there are multiple ways to create such a list in any platform, be it Titanium, native Android/iOS or any other platform.

It depends on you which way you prefer. Using ListView, you can simply create a ListView & add ListItems or child-views in a ListItem upon clicking a parent list-item, and do vice-versa on deleting or hiding the content.

You will need to take care about the clicking events when to add/when to delete or hide the content, though it will require lot of coding but it will be worth doing so because then you can understand how things behind the scenes work. It's time taking to provide you a code-base here, so I suggest you to start working on to create this feature or you can take a look here at this sample code - Expandable ListView


问:
Excel VBA macro:
I want to split quarterly the dates from a year (with some colors).

Right now I have a macro for 2 years only, but I want to make it automatically for every year. (ex: with Red color: between date 01/01/YYYY-01/05/YYYY..... and so on)

This is what did:

```<code>Private Sub CheckBox1_Click()

    If CheckBox1.Value = True Then
    Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2015", Formula2:="01/05/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2015", Formula2:="01/08/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2015", Formula2:="01/01/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With

      Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2016", Formula2:="01/05/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2016", Formula2:="01/08/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2016", Formula2:="01/01/2017"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With
End Sub
</code>```

The result:
enter image description here

答:
At the start of the code add

```<code> Private Sub CheckBox1_Click()
 Const DesiredYear = "2017"  'change this for each year you want
</code>```

Then change lines like this:

```<code>  Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
    Formula1:="01/01/2015", Formula2:="01/05/2015"
</code>```

to

```<code>  Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
    Formula1:="01/01/" & DesiredYear, Formula2:="01/05/" & DesiredYear
</code>```

Title: Excel VBA macro:

Body:
I want to split quarterly the dates from a year (with some colors).

Right now I have a macro for 2 years only, but I want to make it automatically for every year. (ex: with Red color: between date 01/01/YYYY-01/05/YYYY..... and so on)

This is what did:

Private Sub CheckBox1_Click()

    If CheckBox1.Value = True Then
    Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2015", Formula2:="01/05/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2015", Formula2:="01/08/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2015", Formula2:="01/01/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With

      Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2016", Formula2:="01/05/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2016", Formula2:="01/08/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2016", Formula2:="01/01/2017"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With
End Sub

The result:
enter image description here

Body:
At the start of the code add

 Private Sub CheckBox1_Click()
 Const DesiredYear = "2017"  'change this for each year you want

Then change lines like this:

  Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
    Formula1:="01/01/2015", Formula2:="01/05/2015"

to

  Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
    Formula1:="01/01/" & DesiredYear, Formula2:="01/05/" & DesiredYear


问:
Memory/Address Sanitizer vs Valgrind
I want some tool to diagnose use-after-free bugs and uninitialized bugs. I am considering Sanitizer(Memory and/or Address) and Valgrind. But I have very little idea about their advantages and disadvantages. Can anyone tell the main features, differences and pros/cons of Sanitizer and Valgrind?

Edit: I found some of comparisons like: Valgrind uses DBI(dynamic binary instrumentation) and Sanitizer uses CTI(compile-time instrumentation). Valgrind makes the program much slower(20x) whether Sanitizer runs much faster than Valgrind(2x). If anyone can give me some more important points to consider, it will be a great help.

答:
I think you'll find this wiki useful.

TLDR main advantages of sanitizers are

much smaller CPU overheads (Lsan is practically free, UBsan/Isan is 1.25x, Asan and Msan are 2-4x for computationally intensive tasks and 1.05-1.1x for GUIs, Tsan is 5-15x)

wider class of detected errors (stack and global overflows, use-after-return/scope)

full support of multi-threaded apps (Valgrind support for multi-threading is a joke)

much smaller memory overhead (up to 2x for Asan, up to 3x for Msan, up to 10x for Tsan which is way better than Valgrind)

Disadvantages are

more complicated integration (you need to teach your build system to understand Asan and sometimes work around limitations/bugs in Asan itself, you also need to use relatively recent compiler)

MemorySanitizer is not reall^W easily usable at the moment as it requires one to rebuild all dependencies under Msan (including all standard libraries e.g. libc++); this means that casual users can only use Valgrind for detecting uninitialized errors

sanitizers typically can not be combined with each other (the only supported combination is Asan+UBsan+Lsan) which means that you'll have to do separate QA runs to catch all types of bugs

Title: Memory/Address Sanitizer vs Valgrind


问:
Using function in Javascript
Example:

```<code>function pcs()
{
    var t1 = document.getElementById("tot1").value
    var pb = document.getElementById("pcbox").value
    var pc = ""

    if (t1==! && pb==!)
    {
        document.getElementId("rbox").innerHTML = ""
    }
}
</code>```

My question is if t1 and pb are null the function pcs() is not called... Why?

答:
The line

```<code>if(t1==! && pb==!)</code>```

is not legal syntax.  If this is exactly how you have written the code it will not parse and thus the function will not be defined (plus you'll be getting Javascript errors).

Perhaps you meant

```<code>if(t1 != null && pb != null)</code>```

Additionally, while semicolons at the end of lines can be inferred by the interpreter, they are meant to be there (as opposed to being actually optional) and adding them is good practice.

EDIT and while I didn't understand your final question 100%, remember that the code you've written (assuming the syntax were correct) merely defines a function.  You will need to have some other code call this function at an appropriate point in order to have it executed, e.g. for some element onblur = pcs();

OwnerDisplayName: aravinth

LastEditorDisplayName: RoBorg

ContentLicense: CC BY-SA 2.5

Title: Using function in Javascript

Body:
Example:

function pcs()
{
    var t1 = document.getElementById("tot1").value
    var pb = document.getElementById("pcbox").value
    var pc = ""

    if (t1==! && pb==!)
    {
        document.getElementId("rbox").innerHTML = ""
    }
}

My question is if t1 and pb are null the function pcs() is not called... Why?

Body:
The line

if(t1==! && pb==!)

is not legal syntax.  If this is exactly how you have written the code it will not parse and thus the function will not be defined (plus you'll be getting Javascript errors).

Perhaps you meant

if(t1 != null && pb != null)

Additionally, while semicolons at the end of lines can be inferred by the interpreter, they are meant to be there (as opposed to being actually optional) and adding them is good practice.

EDIT and while I didn't understand your final question 100%, remember that the code you've written (assuming the syntax were correct) merely defines a function.  You will need to have some other code call this function at an appropriate point in order to have it executed, e.g. for some element onblur = pcs();

OwnerDisplayName: dtsazza


问:
How to read/write a boolean when implementing the Parcelable interface?
I'm trying to make an ArrayList Parcelable in order to pass to an activity a list of custom object. I start writing a myObjectList class which extends ArrayList<myObject> and implement Parcelable.

Some attributes of MyObject are boolean but Parcel don't have  any method read/writeBoolean.

What is the best way to handle this?

答:
Short and simple implementation in Kotlin, with nullable support:

Add methods to Parcel

```<code>fun Parcel.writeBoolean(flag: Boolean?) {
    when(flag) {
        true -> writeInt(1)
        false -> writeInt(0)
        else -> writeInt(-1)
    }
}

fun Parcel.readBoolean(): Boolean? {
    return when(readInt()) {
        1 -> true
        0 -> false
        else -> null
    }
}
</code>```

And use it:

```<code>parcel.writeBoolean(isUserActive)

parcel.readBoolean()        // For true, false, null
parcel.readBoolean()!!      // For only true and false
</code>```

Body:
Short and simple implementation in Kotlin, with nullable support:

Add methods to Parcel

fun Parcel.writeBoolean(flag: Boolean?) {
    when(flag) {
        true -> writeInt(1)
        false -> writeInt(0)
        else -> writeInt(-1)
    }
}

fun Parcel.readBoolean(): Boolean? {
    return when(readInt()) {
        1 -> true
        0 -> false
        else -> null
    }
}

And use it:

parcel.writeBoolean(isUserActive)

parcel.readBoolean()        // For true, false, null
parcel.readBoolean()!!      // For only true and false


问:
Optional parameters in ABAP CDS views?
I'm trying to create a CDS view for consumption with optional parameters. But at the moment, optional parameters are not supported.

Is there a workaround available to somehow choose which where clauses are to be executed/used based on input parameters ?

答:
At the moment the following are the only parameters you can use as optional.</p>

```<code>p_date : sydatum
@<Environment.systemField:#SYSTEM_DATE
, p_language : spras
@<Environment.systemField:#SYSTEM_LANGUAGE
</code>```

Title: Optional parameters in ABAP CDS views?

Body:
At the moment the following are the only parameters you can use as optional.

p_date : sydatum
@<Environment.systemField:#SYSTEM_DATE
, p_language : spras
@<Environment.systemField:#SYSTEM_LANGUAGE


问:
How to unlock a VSS database
How do I unlock a VSS database?  One of our VSS administrators ran the "Analyze & Fix" routine and it has prevented user from checking out files. </p>

答:
Open the Start menu -> All Programs -> Microsoft Visual SourceSafe -> Visual SourceSafe 6.0 Admin.

Then go to Tools->Lock SourceSafe Database->uncheck the "Lock all users out of Visual SourceSafe" check box.

Title: How to unlock a VSS database


问:
How to search and replace using regular expressions in Visual Studio
I need to replace all the urls with empty string:

```<code>""regular"": ""http://fonts.gstatic.com/s/abhayalibre/v3/zTLc5Jxv6yvb1nHyqBasVy3USBnSvpkopQaUR-2r7iU.ttf"",
""500"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc5MQuUSAwdHsY8ov_6tk1oA.ttf"",
""600"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc2v8CylhIUtwUiYO7Z2wXbE.ttf"",
""700"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc0D2ttfZwueP-QU272T9-k4.ttf"",
""800"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc_qsay_1ZmRGmC8pVRdIfAg.ttf""
</code>```

I've tried using the Regular Expressions with:

"http://fonts(*).ttf"

but i can't see the replace working.

答:
Your mistake is (*), use instead:

```<code>http://fonts.+\.ttf
</code>```

Body:
I need to replace all the urls with empty string:

""regular"": ""http://fonts.gstatic.com/s/abhayalibre/v3/zTLc5Jxv6yvb1nHyqBasVy3USBnSvpkopQaUR-2r7iU.ttf"",
""500"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc5MQuUSAwdHsY8ov_6tk1oA.ttf"",
""600"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc2v8CylhIUtwUiYO7Z2wXbE.ttf"",
""700"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc0D2ttfZwueP-QU272T9-k4.ttf"",
""800"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc_qsay_1ZmRGmC8pVRdIfAg.ttf""

I've tried using the Regular Expressions with:

"http://fonts(*).ttf"

but i can't see the replace working.

Body:
Your mistake is (*), use instead:

http://fonts.+\.ttf


问:
Printing parsed JSON in Python
Assuming this is the .JSON file I have to parse:

```<code>{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}
</code>```

How would I go about printing the total values like:

```<code>1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0
</code>```

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

```<code>import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)
</code>```

Title: Printing parsed JSON in Python

Body:
Assuming this is the .JSON file I have to parse:

{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}

How would I go about printing the total values like:

1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)

Body:
You can try:

>>> import json
>>> data= """{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}"""
>>> data = json.loads(data)
>>> print data["item"]["allInventory"]["total"]
{'1005': 0, '1004': 12, '1003': 3, '1002': 5, '1001': 6, '1000': 0}


问:
Jupyter Notebook figure size settings
If I plot a graph or display a table in Jupyter Notebook the figures are really small and unreadable. What is the best way to set the figure size settings globally in Jupyter Notebook? For comparison in Quantopian's Notebook version plots and tables are a lot larger. I know there are separate settings for matplotlib and other libraries but I would like to set global settings. I also tried this setting, but it didn't work.

```<code>%config InlineBackend.figure_format='retina'
</code>```

答:
I'm pretty sure there's no "global setting" for all packages in jupyter. The best you can do is configure the defaults for matplotlib and pandas etc. Note that other graphing libraries have larger default outputs (from the top of my head I know plotly has full width graphs by default)

To configure global python settings, run ipython profile create to create a ~/.ipython/profile_default/ipython_kernel_config.py file, and add the line:

c.InlineBackend.rc = { 'figure.figsize': (20.0, 10.0) }

See https://matplotlib.org/users/customizing.html for more info on customising matplotlib

As for pandas, I don't think it has global options for style. You could add stuff to jupyter's custom.css file (`~/.jupyter/custom/custom.css) like so:

```<code>.dataframe {
    font-size: 14px !important;
}
</code>```

Title: Jupyter Notebook figure size settings

Body:
If I plot a graph or display a table in Jupyter Notebook the figures are really small and unreadable. What is the best way to set the figure size settings globally in Jupyter Notebook? For comparison in Quantopian's Notebook version plots and tables are a lot larger. I know there are separate settings for matplotlib and other libraries but I would like to set global settings. I also tried this setting, but it didn't work.

%config InlineBackend.figure_format='retina'

Body:
I'm pretty sure there's no "global setting" for all packages in jupyter. The best you can do is configure the defaults for matplotlib and pandas etc. Note that other graphing libraries have larger default outputs (from the top of my head I know plotly has full width graphs by default)

To configure global python settings, run ipython profile create to create a ~/.ipython/profile_default/ipython_kernel_config.py file, and add the line:

c.InlineBackend.rc = { 'figure.figsize': (20.0, 10.0) }

See https://matplotlib.org/users/customizing.html for more info on customising matplotlib

As for pandas, I don't think it has global options for style. You could add stuff to jupyter's custom.css file (`~/.jupyter/custom/custom.css) like so:

.dataframe {
    font-size: 14px !important;
}


问:
Should I pop after each binmode?
When using binmode, should I pop the layers from a possibly previous used binmode?

```<code>#!/usr/bin/env perl
use warnings;
use 5.012;
use autodie;

open my $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(latin1)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(latin1)', '/dev/tty'; # ...
close $tty;

open $tty, '>:bytes', '/dev/tty';
say "@{[ PerlIO::get_layers( $tty ) ]}"; # unix perlio
close $tty;

say "----------------------------------------";

binmode STDOUT, ':encoding(utf8)'; # ...
binmode STDOUT, ':encoding(latin1)'; # ...
binmode STDOUT, ':encoding(utf8)'; # ...
binmode STDOUT, ':encoding(latin1)'; # ...

binmode STDOUT, ':bytes';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio encoding(utf8) /
# utf8 encoding(iso-8859-1) utf8 encoding(utf8) utf8 encoding(iso-8859-1)

binmode STDOUT, ':pop:pop:pop:pop:bytes';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio
</code>```

.

```<code>#!/usr/bin/env perl
use warnings;
use 5.012;
use autodie;

open my $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;

open $tty, '>:raw', '/dev/tty';
say "@{[ PerlIO::get_layers( $tty ) ]}"; # unix
close $tty;

say "----------------------------------------";

binmode STDOUT, ':encoding(utf8)'; # ...

binmode STDOUT, ':raw';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio

binmode STDOUT, ':pop:raw';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix
</code>```

答:
:pop is required to pop real layers, such as :encoding(...). So yes, if you want to replace a real layer by another one, then you'll have to :pop.

But note that pushing :raw actually results in a series of pop... And :perlio automatically inserts :unix underneath. So the exact number of pops really depends on the current layers.

As the documentation says itself:

A more elegant (and safer) interface is needed.

Title: Should I pop after each binmode?

Body:
When using binmode, should I pop the layers from a possibly previous used binmode?

#!/usr/bin/env perl
use warnings;
use 5.012;
use autodie;

open my $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(latin1)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;
open $tty, '>:encoding(latin1)', '/dev/tty'; # ...
close $tty;

open $tty, '>:bytes', '/dev/tty';
say "@{[ PerlIO::get_layers( $tty ) ]}"; # unix perlio
close $tty;

say "----------------------------------------";

binmode STDOUT, ':encoding(utf8)'; # ...
binmode STDOUT, ':encoding(latin1)'; # ...
binmode STDOUT, ':encoding(utf8)'; # ...
binmode STDOUT, ':encoding(latin1)'; # ...

binmode STDOUT, ':bytes';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio encoding(utf8) /
# utf8 encoding(iso-8859-1) utf8 encoding(utf8) utf8 encoding(iso-8859-1)

binmode STDOUT, ':pop:pop:pop:pop:bytes';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio

.

#!/usr/bin/env perl
use warnings;
use 5.012;
use autodie;

open my $tty, '>:encoding(utf8)', '/dev/tty'; # ...
close $tty;

open $tty, '>:raw', '/dev/tty';
say "@{[ PerlIO::get_layers( $tty ) ]}"; # unix
close $tty;

say "----------------------------------------";

binmode STDOUT, ':encoding(utf8)'; # ...

binmode STDOUT, ':raw';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix perlio

binmode STDOUT, ':pop:raw';
say "@{[ PerlIO::get_layers( *STDOUT ) ]}"; # unix


问:
*ngIf equivalent in TypeScript code
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

```<code><div *ngIf="exampleComponentProperty"></div>
</code>```

Is it possible to do the same check in .ts? How would the expression look then?

```<code>if (this.exampleComponentProperty != null) {
// some code...
}
</code>```

did not seem to work.

答:
If this property is required for display this component you should load it in resolver.
https://angular.io/guide/router#resolve-pre-fetching-component-data</p>

Title: *ngIf equivalent in TypeScript code

Body:
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

Is it possible to do the same check in .ts? How would the expression look then?

if (this.exampleComponentProperty != null) {
// some code...
}

did not seem to work.


问:
Is it a bad design to expect a sorted List?
Lets say I wish to solve the problem - Find maximum product of 3 numbers in an array  in Java .

As its easy to solve the problem provided input List is already sorted so if my API method expects a sorted input , would that be a bad design ?

I am assuming the scenario where my API method wouldn't be controlling the source of data & input list population. That I suppose is the usual assumption when you are writing an API.

I would also assume that input could be very very large ( a million items or so ).

Is it too restrictive to impose such restrictions on upstream ?

Related Question

EDIT : I quoted that problem as an example. I meant to say, does it make more sense to keep a numerical list sorted from the very beginning ( when elements were inserted ) ? Since most problems on a collection of numbers are usually easy when collection is already sorted OR a numerical list being sorted from the very beginning of data flow has some kind of disadvantages too?

答:
I think it is bad design.

Why?

@Kayaman already said, a caller providing an unsorted list will probably end up with wrong results and no hint that he did something wrong.

Second reason: You propagate an implementation detail into your API design. There could be other implementations not needing the list to be sorted (e.g. the three-numbers product can be done in O(n) on an unsorted list).

So:

Provide a method working on an unsorted list.

And if it's likely that your caller might have a sorted version of the list ready for you, add a second method with a name that clearly states the need for a sorted list.

Or, if from the context you are sure that the list is always sorted, then it should not be used as a plain list, but encapsulated in a class that guarantees the "sorted" property.