问:
Why does the VBA IDE's Intellisense in Microsoft Word 2007 keep on changing the case of the name of a particular variable type?
This is the most bizarre question I've ever asked. I'm not even sure how to phrase it. I remember something like this happening way back in the VB6 IDE, but I've forgotten the fix. If this is the case, then this is a really old bug in the VB IDE.

Here's the problem:

I'm writing a simple MS Word macro when I accidently typed:

```<code>Dim cell as Cell
</code>```

This activated the dreaded IDE bug. Now, no matter what I do; remove the module, edit it outside the IDE or whatever, the IDE's intellisense formats the variable type "Cell" as "cell"

If I name a new variable:

```<code>Dim tcell as Cell
</code>```

The IDE changes it to:

```<code>Dim tcell As cell
</code>```

This infuriates me to no end. I've tried everything to no avail.
This happens even if I edit the module file (.bas) outside of the IDE and reimport it back.

How can I stop this madness?

Updated

Apparently this behavior is not a bug, but by design. See answer.

答:
Try putting a

```<code>Dim Cell as Cell
</code>```

somewhere, then delete it and try again...
I seem to recall that variable declarations take precedence in setting the casing, thus this should force the casing back to how it should be...

Body:
This is the most bizarre question I've ever asked. I'm not even sure how to phrase it. I remember something like this happening way back in the VB6 IDE, but I've forgotten the fix. If this is the case, then this is a really old bug in the VB IDE.

Here's the problem:

I'm writing a simple MS Word macro when I accidently typed:

Dim cell as Cell

This activated the dreaded IDE bug. Now, no matter what I do; remove the module, edit it outside the IDE or whatever, the IDE's intellisense formats the variable type "Cell" as "cell"

If I name a new variable:

Dim tcell as Cell

The IDE changes it to:

Dim tcell As cell

This infuriates me to no end. I've tried everything to no avail.
This happens even if I edit the module file (.bas) outside of the IDE and reimport it back.

How can I stop this madness?

Updated

Apparently this behavior is not a bug, but by design. See answer.

Body:
Try putting a

Dim Cell as Cell

somewhere, then delete it and try again...
I seem to recall that variable declarations take precedence in setting the casing, thus this should force the casing back to how it should be...


来源: stackexchange

问:
Can't pip install GDAL for python 3.6 on mac os
I can pip install GDAL for the python2.7 on my mac just fine using pip. However when I try to install the package for my python3.6 using
pip3 install gdal I get a long error message that ends with this:

```<code>warning: unknown warning option '-Werror=unused-command-line-argument-hard-error-in-future'; did you mean '-Werror=unused-command-line-argument'? [-Wunknown-warning-option]
    extensions/gdal_wrap.cpp:3168:10: fatal error: 'cpl_port.h' file not found
    #include "cpl_port.h"
             ^~~~~~~~~~~~
    1 warning and 1 error generated.
    error: command 'clang' failed with exit status 1
</code>```

I tried re-installing GDAL using homebrew as suggested here, Unable to install GDAL in python 3 using pip (clang failed with exit status 1), but no luck.  Looking for any suggestions.

答:
I have tried a lot to install GDAL package using PIP and ended up in either missing some modules or encountered errors. So, best solution for installing GDAL is to setup condo environment and install gdal which will work :

```<code>conda create --name yourenvnamehere python=python3.7

conda activate yourenvnamehere

conda install -c anaconda numpy

conda install -c conda-forge gdal
</code>```

if you have followed the above code:

import gdal

should work. Happy coding with spatial data:)

ContentLicense: CC BY-SA 3.0

Body:
I can pip install GDAL for the python2.7 on my mac just fine using pip. However when I try to install the package for my python3.6 using
pip3 install gdal I get a long error message that ends with this:

warning: unknown warning option '-Werror=unused-command-line-argument-hard-error-in-future'; did you mean '-Werror=unused-command-line-argument'? [-Wunknown-warning-option]
    extensions/gdal_wrap.cpp:3168:10: fatal error: 'cpl_port.h' file not found
    #include "cpl_port.h"
             ^~~~~~~~~~~~
    1 warning and 1 error generated.
    error: command 'clang' failed with exit status 1

I tried re-installing GDAL using homebrew as suggested here, Unable to install GDAL in python 3 using pip (clang failed with exit status 1), but no luck.  Looking for any suggestions.

Body:
I have tried a lot to install GDAL package using PIP and ended up in either missing some modules or encountered errors. So, best solution for installing GDAL is to setup condo environment and install gdal which will work :

conda create --name yourenvnamehere python=python3.7

conda activate yourenvnamehere

conda install -c anaconda numpy

conda install -c conda-forge gdal

if you have followed the above code:

import gdal

should work. Happy coding with spatial data:)

ContentLicense: CC BY-SA 4.0


问:
Monitor backup script with Prometheus
I want to monitor my simple bash script for backup cassandra, so here is my script

!/bin/bash

```<code>### Check for incomplete backups

if medusa list-backups  | grep Incomplete
then
echo cassandra_backup_status{status='"success"'} 0  > /var/lib/node_exporter/textfile_collector/cassandra_backup_status.prom
else
echo "all is ok tho"
fi
</code>```

so as you can see here, i use textfile collector, which node_exporter builtin
and then i want to select this using alertmanager like this
cassandra_backup_status =! 0; then alert_to_telegram

is this scenario right?

答:
Beyond the means to expose the metric (textfile or push gateway). The approach is not right because:

the metric will only be present in one state (namely when it fails) which means you won't be able to detect if/when the script run

in the other case or your if, you don't remove the textfile which means that it will always stay (with a failed state)

Finally, the label is not meant to pass a state, but only the value should report that. It will also save you a lot of pain when determining what is the last state; whenever a label change a new metric is created and the old one is still in prometheus until it become stale (5 minutes).

As a conclusion, the script should:

use a metric with value 0 for failed and 1 for success

add a metric to indicate the date of the last run of the script (to detect flatlining)

Appart from that, I recommand that you use a temporary file or use sponge to write atomically to the file.

Title: Monitor backup script with Prometheus

Body:
I want to monitor my simple bash script for backup cassandra, so here is my script

!/bin/bash

### Check for incomplete backups

if medusa list-backups  | grep Incomplete
then
echo cassandra_backup_status{status='"success"'} 0  > /var/lib/node_exporter/textfile_collector/cassandra_backup_status.prom
else
echo "all is ok tho"
fi

so as you can see here, i use textfile collector, which node_exporter builtin
and then i want to select this using alertmanager like this
cassandra_backup_status =! 0; then alert_to_telegram

is this scenario right?


问:
VBA End-user upgrading Microsoft Office 2007 to 2010 (VBA 6 to VBA7) problems and need for documentation, help, tips. (Enough with keywords)
As typical small-business user, when my laptop broke I HAD to upgrade to Office 2010 (2007 isn’t on market anymore). Now I have a bunch of quick-and-dirty VBA to go with my old worksheets. None of them were programming masterpieces, but those worked and got work done with excel, and office 2007.

Now I tried to use my old stuff on Office 2010, and everything is just little bit off to be usable. For two days I searched web, trying to find any documentation for the end user, no luck. I found a lot of blogs aimed to professional programmers who are hoping to make bullet proof code to serve anything from Office 0 to Office2010, 32 bits to 64 bits (No 8 bits here?), but none of the articles talked about the main business, The End User with whole lot of homemade coding to survive a day.

How do I make my old 2007 VBA to work with 2010?

No, I don’t need it to backwards compatible with anything, it is enough that it works with my new computer, and new software (In my case it is 64 bits, if anyone wonders). I just need to know why my code doesn’t work anymore, and what to do about it.
What I really want is some pointers to real information, if there is any!
Of course I could copy-paste every piece of my code to programmers discussion forums, get laughed at, and  after some weeks I might get some of them to work, but what I really need is real information written to basic VBA user. I need to learn this.

So What Is Your Problem?

What has changed?

Calendar active-X component was missing. I found solution: http://answers.microsoft.com/en-us/office/forum/officeversion_other-customize/missing-calendar-control/03ad5d05-ca3f-4081-9989-e757223ebdde now I just have to redo every calendar on all my forms… Thanks.

Textbox.Text wasn’t working, I found and run Microsoft Excel Code Compatibility Inspector  (CII), and it showed that I have few thousand of those Textbox.Text elements that are “Deprecated” – “Potentially contains removed items the object model” – What?

It keeps getting better, same Microsoft software stated:
“TYPE:      DEPRECATION
ITEM:       [xls]SmartTagRecognizer.FullName
URL:        http://go.microsoft.com/?linkid=9719761
CODE:       MyFullName = ThisWorkbook.FullName””
No explanation… (Btw. only way to stop the Inspector and see the results was CRT-ALT-DEL –Stop…)

I visited the links given by the Inspector, no help there.

I run the Inspector few times, and It gave different results every time. Now that is interesting.

I hear your problem, now show me your problem

Where do I start. Here is one.
I have a form where user can make a new ‘appointment’, when saving, VBA creates piece of code and new Shape into calendar worksheet (and to Outlook, but that is not the point here). When user comes back and clicks that shape – button – Button runs a piece of code that was created. here is the code:

```<code>Private Sub myMacro2001_Click()
    Dim meetingId As Integer
    meetingId = 2001
    Load formHours
    Call formHours.selectMeeting(meetingId)
    formHours.Show vbModeless
End Sub
</code>```

Which is supposed, and did back in 2007, open up form formHours with information stored for that meeting 2001 (meetingId)

And the code in formHours  starts as:

```<code>Sub selectMeeting (ByRef IdNo As Integer) ’Bring in the meeting ID
Meeting = IdNo
    ….
</code>```

Not very elegant, but it worked. Doesn’t do that anymore.

If you can help me with this case, I appreciate, But it would be even better if you inform me where was I supposed to find the answer.
What has changed? Worked before, doesn’t anymore. What to do?

(PS. I know my code is crappy, but it worked… And I just would like to find out what has changed, and how do I need to change.

Ps.Ps Yes I know I should be asking Microsoft, but you know how that is…)

FOLLOWUP

After some kind advice from Barrowc and others I managed to fix some of problems. Changing Text.Text to Text.Value created bunch of new problems, some of Text-Values were used on formulas, and now I needed to change them Val(FooTextBox.Value)

What is really surprising is that 2010 seems very SLOW! I ran 2007 and 2010 side by side at office, and 2007 won hands down. One of my workers had already invoiced a customer using 2007, when 2010 was still opening up! Funny, since 2007 was running on AMD Athlon X2 Dual-Core with limited memory, and 2010 was on my new laptop with Core i7-740QM, 6 GB, both on win7-64. I surfed the net and didn't find any complaints that VBA7 on Office 2010 is so much slower than VBA6 on Office2007. I don't know if this is just my problem, but my employees voted for 2007 single minded...

答:
For all of your TextBox instances change .Text to .Value

The SmartTagRecognizer issue would appear to be a false positive so no action needed there

On the error with the form, you could try creating the form this way to see if it helps:

```<code>Private Sub myMacro2001_Click()

Dim meetingId As Integer
Dim fmHours As formHours

meetingId = 2001
Set fmHours = New formHours

fmhours.selectMeeting meetingId
fmHours.Show vbModeless

End Sub
</code>```

Also, you could change Sub selectMeeting to Public Sub selectMeeting

Documentation on the actual differences in VBA between Office 2007 and Office 2010 seems to be a bit sparse. This page specifically mentions that 32-bit ActiveX controls (both custom and built-in) will not work in the 64-bit version of Office 2010. Therefore, this may well be the root of your problem.

There is also a quote from Microsoft here:

Will a 64-bit version of the Office 2010 product be available?

Yes, 64-bit Office 2010 product
  upgrades will be available. However
  we strongly recommend most users
  install 32-bit version of Office 2010
  on both 32 and 64-bit Operating
  Systems because currently many common
  add-ins for Office will not function
  in the 64-bit edition. The 64-bit
  installation of Microsoft Office 2010
  products will be available for users
  who commonly use very large documents
  or data set and need Excel 2010
  programs to access greater than 2GB of
  memory. There may be technical issues
  with the 64-bit version and in order
  to install a 64-bit version of Office
  2010 product users must have a 64-bit
  supported operating system on their
  PC.

(my emphasis)

If you can, try installing to the 32-bit version of Office 2010 instead

Body:
As typical small-business user, when my laptop broke I HAD to upgrade to Office 2010 (2007 isn’t on market anymore). Now I have a bunch of quick-and-dirty VBA to go with my old worksheets. None of them were programming masterpieces, but those worked and got work done with excel, and office 2007.

Now I tried to use my old stuff on Office 2010, and everything is just little bit off to be usable. For two days I searched web, trying to find any documentation for the end user, no luck. I found a lot of blogs aimed to professional programmers who are hoping to make bullet proof code to serve anything from Office 0 to Office2010, 32 bits to 64 bits (No 8 bits here?), but none of the articles talked about the main business, The End User with whole lot of homemade coding to survive a day.

How do I make my old 2007 VBA to work with 2010?

No, I don’t need it to backwards compatible with anything, it is enough that it works with my new computer, and new software (In my case it is 64 bits, if anyone wonders). I just need to know why my code doesn’t work anymore, and what to do about it.
What I really want is some pointers to real information, if there is any!
Of course I could copy-paste every piece of my code to programmers discussion forums, get laughed at, and  after some weeks I might get some of them to work, but what I really need is real information written to basic VBA user. I need to learn this.

So What Is Your Problem?

What has changed?

Calendar active-X component was missing. I found solution: http://answers.microsoft.com/en-us/office/forum/officeversion_other-customize/missing-calendar-control/03ad5d05-ca3f-4081-9989-e757223ebdde now I just have to redo every calendar on all my forms… Thanks.

Textbox.Text wasn’t working, I found and run Microsoft Excel Code Compatibility Inspector  (CII), and it showed that I have few thousand of those Textbox.Text elements that are “Deprecated” – “Potentially contains removed items the object model” – What?

It keeps getting better, same Microsoft software stated:
“TYPE:      DEPRECATION
ITEM:       [xls]SmartTagRecognizer.FullName
URL:        http://go.microsoft.com/?linkid=9719761
CODE:       MyFullName = ThisWorkbook.FullName””
No explanation… (Btw. only way to stop the Inspector and see the results was CRT-ALT-DEL –Stop…)

I visited the links given by the Inspector, no help there.

I run the Inspector few times, and It gave different results every time. Now that is interesting.

I hear your problem, now show me your problem

Where do I start. Here is one.
I have a form where user can make a new ‘appointment’, when saving, VBA creates piece of code and new Shape into calendar worksheet (and to Outlook, but that is not the point here). When user comes back and clicks that shape – button – Button runs a piece of code that was created. here is the code:

Private Sub myMacro2001_Click()
    Dim meetingId As Integer
    meetingId = 2001
    Load formHours
    Call formHours.selectMeeting(meetingId)
    formHours.Show vbModeless
End Sub

Which is supposed, and did back in 2007, open up form formHours with information stored for that meeting 2001 (meetingId)

And the code in formHours  starts as:

Sub selectMeeting (ByRef IdNo As Integer) ’Bring in the meeting ID
Meeting = IdNo
    ….

Not very elegant, but it worked. Doesn’t do that anymore.

If you can help me with this case, I appreciate, But it would be even better if you inform me where was I supposed to find the answer.
What has changed? Worked before, doesn’t anymore. What to do?

(PS. I know my code is crappy, but it worked… And I just would like to find out what has changed, and how do I need to change.

Ps.Ps Yes I know I should be asking Microsoft, but you know how that is…)

FOLLOWUP

After some kind advice from Barrowc and others I managed to fix some of problems. Changing Text.Text to Text.Value created bunch of new problems, some of Text-Values were used on formulas, and now I needed to change them Val(FooTextBox.Value)

What is really surprising is that 2010 seems very SLOW! I ran 2007 and 2010 side by side at office, and 2007 won hands down. One of my workers had already invoiced a customer using 2007, when 2010 was still opening up! Funny, since 2007 was running on AMD Athlon X2 Dual-Core with limited memory, and 2010 was on my new laptop with Core i7-740QM, 6 GB, both on win7-64. I surfed the net and didn't find any complaints that VBA7 on Office 2010 is so much slower than VBA6 on Office2007. I don't know if this is just my problem, but my employees voted for 2007 single minded...

Body:
For all of your TextBox instances change .Text to .Value

The SmartTagRecognizer issue would appear to be a false positive so no action needed there

On the error with the form, you could try creating the form this way to see if it helps:

Private Sub myMacro2001_Click()

Dim meetingId As Integer
Dim fmHours As formHours

meetingId = 2001
Set fmHours = New formHours

fmhours.selectMeeting meetingId
fmHours.Show vbModeless

End Sub

Also, you could change Sub selectMeeting to Public Sub selectMeeting

Documentation on the actual differences in VBA between Office 2007 and Office 2010 seems to be a bit sparse. This page specifically mentions that 32-bit ActiveX controls (both custom and built-in) will not work in the 64-bit version of Office 2010. Therefore, this may well be the root of your problem.

There is also a quote from Microsoft here:

Will a 64-bit version of the Office 2010 product be available?

Yes, 64-bit Office 2010 product
  upgrades will be available. However
  we strongly recommend most users
  install 32-bit version of Office 2010
  on both 32 and 64-bit Operating
  Systems because currently many common
  add-ins for Office will not function
  in the 64-bit edition. The 64-bit
  installation of Microsoft Office 2010
  products will be available for users
  who commonly use very large documents
  or data set and need Excel 2010
  programs to access greater than 2GB of
  memory. There may be technical issues
  with the 64-bit version and in order
  to install a 64-bit version of Office
  2010 product users must have a 64-bit
  supported operating system on their
  PC.

(my emphasis)

If you can, try installing to the 32-bit version of Office 2010 instead


问:
Failed: parentContexts.onChildOutletCreated is not a function
I've been working on the unit tests of an app and I run into a failure that I don't seem able to find anywhere.
I'm currently using Iconic 5 with Angular 9.
Jasmine says:

```<code>StatisticsPage > should create
Failed: parentContexts.onChildOutletCreated is not a function
    at <Jasmine>
    at new IonRouterOutlet (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:2723:1)
    at NodeInjectorFactory.IonRouterOutlet_Factory [as factory] (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:2948:61)
    at getNodeInjectable (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:5993:1)
    at instantiateAllDirectives (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12984:1)
    at createDirectivesInstances (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12196:1)
    at Module.ɵɵelementStart (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:21289:1)
    at IonTabs_Template (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:3081:30)
    at executeTemplate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12156:1)
    at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11926:1)
    at renderComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:13505:1)
Expected undefined to be truthy.
Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/statistics/statistics/statistics.page.spec.ts:39:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)
</code>```

This is the HTML page (the problem does not appear if I eliminate the tabs of the footer, so those are guilty of all this)

<ion-content>

<ion-content>

<ion-footer>

<ion-toolbar>
  <ion-tabs id='tabs'>
    <ion-tab-bar slot="bottom">
      <ion-tab-button (click)= "selectChart('personal')">
        <ion-icon name="person"></ion-icon>
        <ion-label>Personal statistics</ion-label>
      </ion-tab-button>
      <ion-tab-button>
        <ion-icon name="globe" (click)= "selectChart('national')"></ion-icon>
        <ion-label>National rates</ion-label>
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>
</ion-toolbar>

</ion-footer>```
</div>
</div>
</p>

<p>This is the test file:</p>

<pre class="lang-ts prettyprint-override"><code>describe('StatisticsPage', () => {
  let component: StatisticsPage;
  let fixture: ComponentFixture<StatisticsPage>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ StatisticsPage ],
      imports: [IonicModule.forRoot(), RouterTestingModule],
      providers: [
        { provide: Storage, useClass: MockStorage },
        { provide: NavController, useClass: MockNavController },
        { provide: ChildrenOutletContexts, useClass: MockChildrenOutletContexts },
        { provide: ActivatedRoute, useClass: MockActivatedRoute },
        { provide: Router, useClass: MockRouter },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(StatisticsPage);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
</code>```

All the providers were created as jasmine asked for them, but when it ended asking for injections, I run into this issue. I've created most of them as empty classes and I've added methods as needed

答:
Finally figured it out!
so, in the test file, the "ChildrenOutletContexts" should be provided, but not mocked!

providers: [
  { provide: Storage, useClass: MockStorage },
  { provide: NavController, useClass: MockNavController },
  { provide: ChildrenOutletContexts },
  { provide: ActivatedRoute, useClass: MockActivatedRoute },
  { provide: Router, useClass: MockRouter },
]
```

that solved everything! :)

Body:
I've been working on the unit tests of an app and I run into a failure that I don't seem able to find anywhere.
I'm currently using Iconic 5 with Angular 9.
Jasmine says:

StatisticsPage > should create
Failed: parentContexts.onChildOutletCreated is not a function
    at <Jasmine>
    at new IonRouterOutlet (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:2723:1)
    at NodeInjectorFactory.IonRouterOutlet_Factory [as factory] (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:2948:61)
    at getNodeInjectable (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:5993:1)
    at instantiateAllDirectives (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12984:1)
    at createDirectivesInstances (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12196:1)
    at Module.ɵɵelementStart (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:21289:1)
    at IonTabs_Template (http://localhost:9876/_karma_webpack_/node_modules/@ionic/angular/__ivy_ngcc__/fesm2015/ionic-angular.js:3081:30)
    at executeTemplate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12156:1)
    at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11926:1)
    at renderComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:13505:1)
Expected undefined to be truthy.
Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/statistics/statistics/statistics.page.spec.ts:39:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)

This is the HTML page (the problem does not appear if I eliminate the tabs of the footer, so those are guilty of all this)

<ion-content>

<ion-content>

<ion-footer>

<ion-toolbar>
  <ion-tabs id='tabs'>
    <ion-tab-bar slot="bottom">
      <ion-tab-button (click)= "selectChart('personal')">
        <ion-icon name="person"></ion-icon>
        <ion-label>Personal statistics</ion-label>
      </ion-tab-button>
      <ion-tab-button>
        <ion-icon name="globe" (click)= "selectChart('national')"></ion-icon>
        <ion-label>National rates</ion-label>
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>
</ion-toolbar>

</ion-footer>

This is the test file:

describe('StatisticsPage', () => {
  let component: StatisticsPage;
  let fixture: ComponentFixture<StatisticsPage>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ StatisticsPage ],
      imports: [IonicModule.forRoot(), RouterTestingModule],
      providers: [
        { provide: Storage, useClass: MockStorage },
        { provide: NavController, useClass: MockNavController },
        { provide: ChildrenOutletContexts, useClass: MockChildrenOutletContexts },
        { provide: ActivatedRoute, useClass: MockActivatedRoute },
        { provide: Router, useClass: MockRouter },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(StatisticsPage);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

All the providers were created as jasmine asked for them, but when it ended asking for injections, I run into this issue. I've created most of them as empty classes and I've added methods as needed

Body:
Finally figured it out!
so, in the test file, the "ChildrenOutletContexts" should be provided, but not mocked!

providers: [
  { provide: Storage, useClass: MockStorage },
  { provide: NavController, useClass: MockNavController },
  { provide: ChildrenOutletContexts },
  { provide: ActivatedRoute, useClass: MockActivatedRoute },
  { provide: Router, useClass: MockRouter },
]

that solved everything! :)


问:
Am I using select2 incorrectly? Receiving JQuery reference error
I just started using select2, and I added to my header the following:

```<code><link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
</code>```

and in the debug console I receive the following error:
ReferenceError: Can't find variable: jQuery

I have included these lines after my jQuery reference.

Screenshot of the console:

It seems to be working otherwise.  I get the reference error in both chrome and safari.

Am I doing something wrong?

答: I figured this out, as I suspected, it was my own fault.  A bit complicated to explain, but as it turns out I was somehow loading it twice in a modal pop-up via PHP.  No issue with select2.  </p>

Body:
I just started using select2, and I added to my header the following:

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />

and in the debug console I receive the following error:
ReferenceError: Can't find variable: jQuery

I have included these lines after my jQuery reference.

Screenshot of the console:

It seems to be working otherwise.  I get the reference error in both chrome and safari.

Am I doing something wrong?


问:
Why does Java's BitSet internally store long array but use int for set method?
According to the BitSet implementation, it internally uses an array of longs:

```<code>/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;
</code>```

But for the set method it uses int:

```<code>public void set(int bitIndex) {...}
</code>```

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.

答:
The documentation of java.util.BitSet states:

The bits of a BitSet are indexed by nonnegative integers.

This is what it is supposed to do, so no long indexes needed.

That it's internal data structure could support more than 2^31 individual bits is an implementation detail that has no relevance for the public interface of the class (they could have used a boolean[] array and the class would still work, albeit with a bigger memory footprint and more runtime for some methods.)

The question remains: will the public interface of this class change to support long indexes?

This is highly unlikely, because supporting long indexes would mean that methods like

int cardinality()

int nextClearBit() (and similar methods: next/previous clear/set bit)

int size()

IntStream stream()

would also need to be changed, which would break existing code.

The only way I can think of a BitSet like class with long indexes would be an additional class BigBitSet (or LongBitSet or whatever you like) so that people needing bitsets with more then 2^31 bits could switch to that new class.

Whether such a class would ever be added to the java.util package is another question - for that you would have to convince the JCP executive board that this is a important addition / gaping hole in the current Java ecosystem.

Body:
According to the BitSet implementation, it internally uses an array of longs:

/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;

But for the set method it uses int:

public void set(int bitIndex) {...}

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.


问:
How to output the largest number in keySet if there are several such numbers?
How to output the largest word if there are several such numbers? (should output the one, which occurs earlier). My code didn't work properly.</p>

```<code>import java.io.*;
import java.util.*;
public class solved {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> hashMap = new LinkedHashMap<>();
        Scanner scan = new Scanner(System.in);
        String[] str = scan.nextLine().split(" ");
        for (int i=1; i < str.length; i++) {
             int n = str[i].length();
             String s = str[i];
             hashMap.put(n, s);
         }
         int maxKey = Collections.max(hashMap.keySet());
         System.out.println(hashMap.get(maxKey));
    }
}
</code>```

答:
You may use putIfAbsent to avoid ovewriting an existing value and keep the earliest values

```<code>for (int i=1; i < str.length; i++) {
    int n = str[i].length();
    String s = str[i];
    hashMap.putIfAbsent(n, s);
}
</code>```

⚠ Starting i at 1 makes the first word unused be careful, array are 0-indexed so start at 0 to get on every word

Body:
How to output the largest word if there are several such numbers? (should output the one, which occurs earlier). My code didn't work properly.

import java.io.*;
import java.util.*;
public class solved {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> hashMap = new LinkedHashMap<>();
        Scanner scan = new Scanner(System.in);
        String[] str = scan.nextLine().split(" ");
        for (int i=1; i < str.length; i++) {
             int n = str[i].length();
             String s = str[i];
             hashMap.put(n, s);
         }
         int maxKey = Collections.max(hashMap.keySet());
         System.out.println(hashMap.get(maxKey));
    }
}

Body:
You may use putIfAbsent to avoid ovewriting an existing value and keep the earliest values

for (int i=1; i < str.length; i++) {
    int n = str[i].length();
    String s = str[i];
    hashMap.putIfAbsent(n, s);
}

⚠ Starting i at 1 makes the first word unused be careful, array are 0-indexed so start at 0 to get on every word


问:
jQuery. Filtering out list items
My html is about a searchbox

```<code><input type="text" id="myInputList" placeholder="search...">
</code>```

and a list of checkboxes rendered via

```<code><ul class="list-group container" id="myList">
    @foreach (var v in Model)
    {
    <li class="list-group-item">
        <div class="custom-control custom-checkbox">
            <input type="checkbox" class="chkbx custom-control-input" id="@v.GuidId.ToString()">
            <label class="custom-control-label" for="@v.GuidId.ToString()">@v.Name</label>
        </div>
    </li>
    }
</ul>
</code>```

By using the following i can filter out the desired info

```<code>$("#myInputList").on("keyup", function () {
    var value = $(this).val().toLowerCase();
    $("#myList li").filter(function () {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
});
</code>```

Now i wish to extend the functionality by using three buttons

```<code><div id="Group" class="btn-group btn-group-toggle" style="width:100%" data-toggle="buttons">
    <label id="b1" active">
        <input class="selected" type="radio" name="options" checked="checked"> All
    </label>
    <label id="b2">
        <input class="selected" type="radio" name="options"> Checked
    </label>
    <label id="b3">
        <input class="selected" type="radio" name="options"> Unchecked
    </label>
</div>
</code>```

Upon clicking b1, i wish to show all li's

by clicking b2, display the li's where child checkboxes are checked and

by clicking b3, display the li's where child checkboxes are unchecked.

For b1 this one works great

```<code>$("#b1").on("click", function () {
    $("#myInputList").val("");
    $("#myInputList").trigger("keyup");
});
</code>```

but what about b2 and b3?

答:
On change of radio buttons you need to filter li by the checked status of checkbox inside it and show / hide.

$("input[name='options']").change(function() {
  var id = $(this).parent().attr('id');
  var $li = $('#myList li').hide();

  if (id == 'b1') {
    $li.show();
  } else if (id == 'b2') {
    $li.filter(function() {
      return $(this).find('input').is(':checked');
    }).show();
  } else if (id == 'b3') {
    $li.filter(function() {
      return !$(this).find('input').is(':checked');
    }).show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Group" class="btn-group btn-group-toggle" style="width:100%" data-toggle="buttons">
  <label id="b1">
    <input class="selected" type="radio" name="options" checked="checked"> All
  </label>
  <label id="b2">
    <input class="selected" type="radio" name="options"> Checked
  </label>
  <label id="b3">
    <input class="selected" type="radio" name="options"> Unchecked
  </label>
</div>

<ul id="myList">
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
</ul></code>```

Title: jQuery. Filtering out list items

Body:
My html is about a searchbox

<input type="text" id="myInputList" placeholder="search...">

and a list of checkboxes rendered via

    @foreach (var v in Model)
    {

            <input type="checkbox" class="chkbx custom-control-input" id="@v.GuidId.ToString()">
            @v.Name

    }

By using the following i can filter out the desired info

$("#myInputList").on("keyup", function () {
    var value = $(this).val().toLowerCase();
    $("#myList li").filter(function () {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
    });
});

Now i wish to extend the functionality by using three buttons

        <input class="selected" type="radio" name="options" checked="checked"> All

        <input class="selected" type="radio" name="options"> Checked

        <input class="selected" type="radio" name="options"> Unchecked

Upon clicking b1, i wish to show all li's

by clicking b2, display the li's where child checkboxes are checked and

by clicking b3, display the li's where child checkboxes are unchecked.

For b1 this one works great

$("#b1").on("click", function () {
    $("#myInputList").val("");
    $("#myInputList").trigger("keyup");
});

but what about b2 and b3?

Body:
On change of radio buttons you need to filter li by the checked status of checkbox inside it and show / hide.

$("input[name='options']").change(function() {
  var id = $(this).parent().attr('id');
  var $li = $('#myList li').hide();

  if (id == 'b1') {
    $li.show();
  } else if (id == 'b2') {
    $li.filter(function() {
      return $(this).find('input').is(':checked');
    }).show();
  } else if (id == 'b3') {
    $li.filter(function() {
      return !$(this).find('input').is(':checked');
    }).show();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Group" class="btn-group btn-group-toggle" style="width:100%" data-toggle="buttons">
  <label id="b1">
    <input class="selected" type="radio" name="options" checked="checked"> All
  </label>
  <label id="b2">
    <input class="selected" type="radio" name="options"> Checked
  </label>
  <label id="b3">
    <input class="selected" type="radio" name="options"> Unchecked
  </label>
</div>

<ul id="myList">
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input" checked>
      <label class="custom-control-label">Name 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="chkbx custom-control-input">
      <label class="custom-control-label">Name 2</label>
    </div>
  </li>
</ul>


问:
Best strategy to reset Oracle sequence monthly
I'm looking for the best strategy to reset a sequence which is used to generate unique keys. These keys are build using a prefix value, also generated by a combination of month and year values, like the following example:

2020060100000001 - Year(4d)Month(2d)Sequence(8d)

The sequence value must be restarted at the first second of each new month.

Is there any Oracle event that allows calling a function or procedure based in this situation to do this job?

Can anyone help me with opinions and experiences?

Thanks a lot!
Rodrigo

答:
Resetting sequence every month is not a valid approach. Basically you are violating the utilization of sequence. From your question i could understand, you wanted to append year and month to your column. In this case you can simple concatenate while inserting,

```<code>year||month||sequence_name.nextval

Eg: 2020||02||sequence_name.nextval
</code>```

If you still wanted to reset, you can create a trigger to reset the sequence every month,

Body:
Resetting sequence every month is not a valid approach. Basically you are violating the utilization of sequence. From your question i could understand, you wanted to append year and month to your column. In this case you can simple concatenate while inserting,

year||month||sequence_name.nextval

Eg: 2020||02||sequence_name.nextval

If you still wanted to reset, you can create a trigger to reset the sequence every month,


问:
Unable to get spring boot to automatically create database schema
I'm unable to get spring boot to automatically load my database schema when I start it up.

Here is my application.properties:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=
spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.jpa.database = MYSQL

spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
</code>```

Here is my Application.java:

```<code>@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(final String[] args){
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Here is a sample entity:

```<code>@Entity
@Table(name = "survey")
public class Survey implements Serializable {

    private Long _id;

    private String _name;

    private List<Question> _questions;

    /**
     * @return survey's id.
     */
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "survey_id", unique = true, nullable = false)
    public Long getId() {
        return _id;
    }

    /**
     * @return the survey name.
     */
    @Column(name = "name")
    public String getName() {
        return _name;
    }

    /**
     * @return a list of survey questions.
     */
    @OneToMany(mappedBy = "survey")
    @OrderBy("id")
    public List<Question> getQuestions() {
        return _questions;
    }

    /**
     * @param id the id to set to.
     */
    public void setId(Long id) {
        _id = id;
    }

    /**
     * @param name the name for the question.
     */
    public void setName(final String name) {
        _name = name;
    }

    /**
     * @param questions list of questions to set.
     */
    public void setQuestions(List<Question> questions) {
        _questions = questions;
    }
}
</code>```

Any ideas what I'm doing wrong?

答:
If you had this problem on Spring Boot, double check your package names which should be exactly like:</p>

```<code>com.example.YOURPROJECTNAME - consists main application class
com.example.YOURPROJECTNAME.entity - consists entities
</code>```

Body:
I'm unable to get spring boot to automatically load my database schema when I start it up.

Here is my application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=
spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.jpa.database = MYSQL

spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy

Here is my Application.java:

@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(final String[] args){
        SpringApplication.run(Application.class, args);
    }
}

Here is a sample entity:

@Entity
@Table(name = "survey")
public class Survey implements Serializable {

    private Long _id;

    private String _name;

    private List<Question> _questions;

    /**
     * @return survey's id.
     */
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "survey_id", unique = true, nullable = false)
    public Long getId() {
        return _id;
    }

    /**
     * @return the survey name.
     */
    @Column(name = "name")
    public String getName() {
        return _name;
    }

    /**
     * @return a list of survey questions.
     */
    @OneToMany(mappedBy = "survey")
    @OrderBy("id")
    public List<Question> getQuestions() {
        return _questions;
    }

    /**
     * @param id the id to set to.
     */
    public void setId(Long id) {
        _id = id;
    }

    /**
     * @param name the name for the question.
     */
    public void setName(final String name) {
        _name = name;
    }

    /**
     * @param questions list of questions to set.
     */
    public void setQuestions(List<Question> questions) {
        _questions = questions;
    }
}

Any ideas what I'm doing wrong?

Body:
If you had this problem on Spring Boot, double check your package names which should be exactly like:

com.example.YOURPROJECTNAME - consists main application class
com.example.YOURPROJECTNAME.entity - consists entities


问:
Merge columns that are separated by character in order
I have a table that has two columns with information separated by ":". Te problem is that not all of them has the same size.

I'll write an example:

Col1              ol2

AA:BB:CC          1:2:3

AA:DD:BB:CC       4:5:6:7

And I would like a third column that is

Col3

AA=1:BB=2:CC=3

AA=4:DD=5:BB=6:CC=7

I've not idea where to start, I've try to split them, but it took me nowere

答:
We can use strsplit to split the 'Col1', 'Col2' by :, then concatenate the corresponding list elements with str_c to create the 'Col3'

```<code>library(dplyr)
library(purrr)
library(stringr)
df1 %>%
   mutate(col3 = map2_chr(strsplit(Col1, ":"), strsplit(Col2, ":"),
      ~ str_c(.x, .y, sep="=", collapse=':')))
#      Col1    Col2                col3
#1    AA:BB:CC   1:2:3      AA=1:BB=2:CC=3
#2 AA:DD:BB:CC 4:5:6:7 AA=4:DD=5:BB=6:CC=7
</code>```

data

```<code>df1 <- structure(list(Col1 = c("AA:BB:CC", "AA:DD:BB:CC"), Col2 = c("1:2:3",
"4:5:6:7")), class = "data.frame", row.names = c(NA, -2L))
</code>```

Body:
We can use strsplit to split the 'Col1', 'Col2' by :, then concatenate the corresponding list elements with str_c to create the 'Col3'

library(dplyr)
library(purrr)
library(stringr)
df1 %>%
   mutate(col3 = map2_chr(strsplit(Col1, ":"), strsplit(Col2, ":"),
      ~ str_c(.x, .y, sep="=", collapse=':')))
#      Col1    Col2                col3
#1    AA:BB:CC   1:2:3      AA=1:BB=2:CC=3
#2 AA:DD:BB:CC 4:5:6:7 AA=4:DD=5:BB=6:CC=7

data

df1 <- structure(list(Col1 = c("AA:BB:CC", "AA:DD:BB:CC"), Col2 = c("1:2:3",
"4:5:6:7")), class = "data.frame", row.names = c(NA, -2L))


问:
Getting JSONP via jQuery
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

```<code>{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}
</code>```

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

```<code>$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});
</code>```

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?

答:
The JSONP "protocol" relies on the site replying to your request with a JavaScript statement of the form,

```<code> someFunction( someJSON )
</code>```

The name of the function is supplied as an argument from your code, with the idea being that the response script, once consumed and interpreted by the browser, will result in a call to that function with a parsed blob of JSON — which is to say, a JavaScript object. The jQuery library will do some of the bookeeping work for you, even to the extent of creating the globally-scoped function to call (which will be code that just calls the callback you supply as the "success" argument).

Thus, you should check what the actual response from that server looks like.  It sounds to me as if it may not be a server prepared to respond that way. You might need to make sure there's an extra parameter on your URL, of the form "callback=?".

Title: Getting JSONP via jQuery

Body:
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?

Body:
The JSONP "protocol" relies on the site replying to your request with a JavaScript statement of the form,

 someFunction( someJSON )

The name of the function is supplied as an argument from your code, with the idea being that the response script, once consumed and interpreted by the browser, will result in a call to that function with a parsed blob of JSON — which is to say, a JavaScript object. The jQuery library will do some of the bookeeping work for you, even to the extent of creating the globally-scoped function to call (which will be code that just calls the callback you supply as the "success" argument).

Thus, you should check what the actual response from that server looks like.  It sounds to me as if it may not be a server prepared to respond that way. You might need to make sure there's an extra parameter on your URL, of the form "callback=?".


问:
Plotting a function over surface of a cube in Octave
I have a function which is defined for a set of points over the surface of a cube. I know the value of the function for the coordinates. How to generate a plot which will assign a color to every point on the surface of the cube, depending on the value of the function at that point?

On 2D, I can generate colorful contour plots, but how to do something similar in 3D?

Suppose, the function which I want to plot is f(x,y,z) = x^2 + yz.
And, the points on the cube are defined as
xvar = linspace(-1,1,20), yvar = linspace(-1,1,20), zvar = linspace(-1,1,20).

答:
From:

https://octave.sourceforge.io/octave/function/scatter3.html

scatter3 (x, y, z, s, c)

Draw a 3-D scatter plot.

A marker is plotted at each point defined by the coordinates in the
  vectors x, y, and z.

The size of the markers is determined by s, which can be a scalar or a
  vector of the same length as x, y, and z. If s is not given, or is an
  empty matrix, then a default value of 8 points is used.

The color of the markers is determined by c, which can be a string
  defining a fixed color; a 3-element vector giving the red, green, and
  blue components of the color; a vector of the same length as x that
  gives a scaled index into the current colormap; or an Nx3 matrix
  defining the RGB color of each marker individually.

If you use colors, you can try different color profiles.
colormap(rainbow), colormap(jet) etc. These color profiles assign darker color to higher values (which the default colormap does not do), which might make the plots look better.


问:
Drive API App OAuth Permissions Not Updating
I am working on a Golang service that will connect to Google Drive and download a file. The issue is that no matter how I update the projects permissions, when I run application and go to the browser window to OAuth, it only shows the metadata permissions needing granted when have granted more so that I can download files.

Here are the steps I've taken for the service:

I have created a project in Google Developer Console.

In that project I have enabled and updated Google Drive permissions to the capture all auth/drive permission (I have also tried granting all and only some granular).

I create the Golang service from this example: https://developers.google.com/drive/api/v3/quickstart/go

I run the Golang app which prompts me to open a URL in browser to OAuth authenticate.

I open link in browser, auth with my app-owner gmail account and every single time no matter what I do this is the only OAuth scope that shows:

If I use the Drive API Explorer to perform the file download it shows that I need these permissions:

When i click "Execute" in the explorer the OAuth popup shows all the permissions I would expect for my app and works correctly:

What am I doing wrong or missing?

Could this be because the app is an "internal" app?

答:
The issue was in the Golang Quick-Start boilerplate code that I used to scaffold the application.

This line was overriding the permission settings I was explicitly setting in console.

    // If modifying these scopes, delete your previously saved token.json.
    config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
```

<p>fixed when changed to:</p>

<pre class="lang-golang prettyprint-override"><code>    // If modifying these scopes, delete your previously saved token.json.
    config, err := google.ConfigFromJSON(b, drive.DriveScope)
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
</code>```

Body:
The issue was in the Golang Quick-Start boilerplate code that I used to scaffold the application.

This line was overriding the permission settings I was explicitly setting in console.

    // If modifying these scopes, delete your previously saved token.json.
    config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }

fixed when changed to:

    // If modifying these scopes, delete your previously saved token.json.
    config, err := google.ConfigFromJSON(b, drive.DriveScope)
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }


答:
Since you're using a HashMap, if you have an entry later with a duplicate key, the previous entry will be overwritten. One way to deal with this would be to have a Map<Integer, List<String>> but that's just too complicated. It's better to just do it like this:

```<code>int longestN = -1;
String longest;
for (String s : str) {
  int n = s.length();
  if (n > longestN) {
    longestN = n;
    longest = s;
  }
}
System.out.println(longest);
</code>```

Title: How to output the largest number in keySet if there are several such numbers?

Body:
Since you're using a HashMap, if you have an entry later with a duplicate key, the previous entry will be overwritten. One way to deal with this would be to have a Map<Integer, List<String>> but that's just too complicated. It's better to just do it like this:

int longestN = -1;
String longest;
for (String s : str) {
  int n = s.length();
  if (n > longestN) {
    longestN = n;
    longest = s;
  }
}
System.out.println(longest);


问:
Cannot type Japanase kanji from windows IME into oracle 12c database sqlplus in windows 10
my column,"ideograph", is of varchar2(1000) datatype. I inserted one character into the column with Microsoft IME, 寺, Oracle sqlplus just gives me a "?".
  I checked v$nls_parameters.
  nls_characterset= AL32UTF8
  nls_nchar_characterset= AL16UTF16

Now,based on what i've read in other questions here, if I'm using varchar2 datatype, then based on the v$nls_parameters query, the db is using AL32UTF8, but this is a " national characterset", I think, I have no idea what is the " database" character set is.

I also used the dump function with the dual table.
  select dump('寺',1016) from dual;
 I got typ=96 len=1 characterset=AL32UTF8: 3F

I did the same thing in livesql.oracle.com, which uses apex on a cloud, and I got this:
    typ=96 len=3 characterset=AL32UTF8: e5,af,ba

why the hexadecimal codes are different if it says is the same character set?

I have no idea what encoding microsoft IME is using, maybe that is the problem.

How can I fix this? I can create another database, because I don't have any data in the one I'm doing this, is just for training purposes. but I want to see if I can fix it without having to do that.

答: General solution is learning NLS_LANG setting in Oracle and understanding that you may have different NLS_LANG settings on Windows because Windows command line mode does not work the same way as Windows graphical user interface as far as character set settings are concerned.</p>


问:
Application only runs if you run as administrator?
Edit: This problem only occurs on windows 7 and vista from what I've heard.

I have a very simple app developed with an external graphics library. If I install this app into a program files directory and run it, it will crash immediately but it works fine normally, with exactly the same files. I have realised it is because you need to run the application as administrator for it to work.

I appreciate if this is a problem directly related to the graphics engine I am using, but I don't really think so (but I'm clueless). Can anyone help me?

Edit for more detail:

The application executable and files that are needed to run it are installed into the default program directory - for me, C:\Program Files (x86). If you try and run with without clicking run as administrator, it will simple freeze and say "App has stopped working. Windows is checking for a solution to the problem..." My question is basically, how can I make it so run as administrator isn't necessary?

答:
When a program cannot perform an operation, it (the operation) should fail gracefully.  My guess is your application is attempting to do something that it cannot do as a normal user and then fails to check for a return code, and then subsequently crashes.  You need to identify what it is your program is doing that it should not be able to do as a normal user.  For example (off the top of my head):

Write a file to Program Files (x86)

Write to HKLM


问:
How do I create a makefile from a Visual Studio solution file?
I have a Visual Studio project that uses a solution file to build it. I want to generate a makefile so that I can build it using the makefile instead of the solution file. (The reason I need to do this in case you are wondering is that I am incorporating my project into a larger software system that uses makefiles to build, and I want to be able to build the whole thing using the makefiles.)

Is there a way to automatically get the information from the Visual Studio solution and convert it into a makefile format, or do I need to do that manually?

答: Good advice - Avoid wasting a couple of days on tools for a job that'll take a few hours at most.  They guy who built my first house had one 30 year old table saw and built the whole house iwth it.  I now have at least 10 saws and never build anything.</p>

ContentLicense: CC BY-SA 2.5


问:
How to get the value of a first key-value pair in Python
I'm trying to sole exercise where I have dictionary like this:

```<code>[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]
</code>```

Output is supposed to be:

```<code>["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
</code>```

My problem stems from the fact that the first key can be either state or country so I cannot just use that key name to access value, so how can I print the first key value if the name can be different across inputs?

答:
Use the dict.get method. It will return a default value if the key is not present.

```<code>a = [{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]
for d in a:
    place = d.get('state',d.get('country',None))
    s = 'The capital of {} is {}'.format(place,d['capital'])
    print(s)
    # or
    print("The capital of {}{} is {}".format(d.get('state',''),d.get('country',''),d['capital']))
</code>```

Body:
I'm trying to sole exercise where I have dictionary like this:

[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]

Output is supposed to be:

["The capital of Maine is Augusta", "The capital of Spain is Madrid"]

My problem stems from the fact that the first key can be either state or country so I cannot just use that key name to access value, so how can I print the first key value if the name can be different across inputs?

Body:
Use the dict.get method. It will return a default value if the key is not present.

a = [{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]
for d in a:
    place = d.get('state',d.get('country',None))
    s = 'The capital of {} is {}'.format(place,d['capital'])
    print(s)
    # or
    print("The capital of {}{} is {}".format(d.get('state',''),d.get('country',''),d['capital']))


问:
Javascript array, building from a set of variables
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
```

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']

答:
Just like the map approach but using Array.prototype.from:

var Car = function (maker, type, model) {
this.maker = maker;
this.type = type;
this.model = model;
}
var golf = new Car ('VW', 'Hatchback', 'Golf');
var sentra = new Car ('Nissan', 'Sedan', 'Sentra');
var _328i = new Car ('BMW', 'Convertible', "328i");
var gallardo = new Car ('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;

// Solution here
const makersList = Array.from([golf, sentra, _328i, gallardo, corniche], car => car.maker );

// should print an array of makers string names
console.log(makersList);
```

Body:
The variables following are defined through a Car prototype:

var Car = function(maker, type, model) {
  this.maker = maker;
  this.type = type;
  this.model = model;
}

var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");

Car.prototype.year = 0;

golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;

How does one build an array of the var values for the property maker

Something that might console log like this:

(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']


问:
create a feature in pandas based on another column (i.e. when it goes from positive to negative)
I have the following dataset:

```<code>data = {'ROC_9': [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)
</code>```

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vica versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

```<code>price_data['ROC9_signal'] = 0
</code>```

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

Body:
I have the following dataset:

data = {'ROC_9': [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}

price_data = pd.DataFrame (data)

It is an indicator about a stock price, namely rate of change.

I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vica versa.

It is easier explained through an example: lets use the feature ROC9.

I create a new variable called ROC9_signal and set it equal to 0:

price_data['ROC9_signal'] = 0

When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.

When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).

Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).

Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).

It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.

I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.

Thanks in advance for the help.

This is what the full data looks like:

Full Data

Body:
You can use np.sign to extract the signs. Something like this:

signs = np.sign(price_data.ROC_9)
price_data['signal'] = np.sign(signs.diff()).fillna(0)

Output:

      ROC_9  signal
0  0.006250     0.0
1  0.087230     0.0
2  0.045028     0.0
3  0.165738     0.0
4 -0.006993    -1.0
5 -0.432736     0.0
6 -0.111620     0.0
7  0.057466     1.0
8  0.203138     0.0
9 -0.008234    -1.0


问:
Symfony Form - Add required fields to form depending on other field value
I want to add some required fields to my form when an other field has some value. I've tried to do it with PRE_SET_DATA event but I cannot get data in my event.

My example here is to add partner name field when a user is married.

My UserType

```<code>    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('familyStatus', ChoiceType::class, [
                'label' => 'Statut de famille',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true,
                'choices' => [
                    'Married' => 'M',
                    'Single' => 'S'
                ]
            ])
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $form = $event->getForm();
                $user = $event->getData();
                $status = $user->getFamilyStatus(); // Give me NULL
                //$status = $form->get('familyStatus')->getData() Give me NULL too

                /*
                if ($user && $status === 'M') {
                    $form->add('partnerName', TextType::class, [
                        'required' => true,
                        'mapped' => false
                   ]);
                )
                */
            })
        ;
    }
</code>```

What's wrong ? How can I add dynamically new fields depending on other field ?
I also tried with POST_SET_DATA but it's not working.

答:
You need the second example from this part of the docs link.

Basically you set the event listener to the entire form. You should add another listener to the field itself with POST_SUBMIT event.

Body:
I want to add some required fields to my form when an other field has some value. I've tried to do it with PRE_SET_DATA event but I cannot get data in my event.

My example here is to add partner name field when a user is married.

My UserType

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('familyStatus', ChoiceType::class, [
                'label' => 'Statut de famille',
                'label_attr' => [
                    'class' => 'fg-label'
                ],
                'attr' => [
                    'class' => 'sc-gqjmRU fQXahQ'
                ],
                'required' => true,
                'choices' => [
                    'Married' => 'M',
                    'Single' => 'S'
                ]
            ])
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $form = $event->getForm();
                $user = $event->getData();
                $status = $user->getFamilyStatus(); // Give me NULL
                //$status = $form->get('familyStatus')->getData() Give me NULL too

                /*
                if ($user && $status === 'M') {
                    $form->add('partnerName', TextType::class, [
                        'required' => true,
                        'mapped' => false
                   ]);
                )
                */
            })
        ;
    }

What's wrong ? How can I add dynamically new fields depending on other field ?
I also tried with POST_SET_DATA but it's not working.


问:
How to treat null values after joining multiple tables
I am creating a new dataframe by joining 4 dataframes
After which I need to concatenate two same columns from different dataframes
data:

```<code>col1   col2 expected
Acc1   Acc1 Acc1Acc1
Acc2   null Acc2
null   Acc3 Acc3
</code>```

Issue:
If i do concat without replacing null values; i loose info
So after joining; since pyspark doesnt delete the common columns, we have two Account columns from 2 tables
I tried replacing it with empty string;it didnt work and throws error : dataframe is not iteratable

Query:
How do I replace null values with empty string after joining tables?
or is there any way null and concat can be handled at the sametime?

```<code>df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('Account',F.when(df2('Account').isNull(),'').otherwise(df2('Account')))\
.withColumn('Account',F.when(df3('Account').isNull(),'').otherwise(df3('Account')))\
.withColumn("Account",F.concat(F.trim(df2.Account), F.trim(df3.Account)))
</code>```

答:
Hi and welcome to StackOverflow. A function such as pyspark.sql.functions.concat_ws should do the trick here, such as:

```<code>import pyspark.sql.functions as f

df = spark.createDataFrame([
    (1, "John", "Smith"),
    (2, "Monty", "Python"),
    (3, "Donald", None),
], ['id', 'firstname', 'lastname']
)
df.show()
+---+---------+--------+
| id|firstname|lastname|
+---+---------+--------+
|  1|     John|   Smith|
|  2|    Monty|  Python|
|  3|   Donald|    null|
+---+---------+--------+

df.select(
    "*",
    f.concat_ws(
      "",
      f.trim(f.col("firstname")), f.trim(f.col("lastname"))
    ).alias("concatenated")
).show()
+---+---------+--------+------------+
| id|firstname|lastname|concatenated|
+---+---------+--------+------------+
|  1|     John|   Smith|   JohnSmith|
|  2|    Monty|  Python| MontyPython|
|  3|   Donald|    null|      Donald|
+---+---------+--------+------------+
</code>```

Hope this helps, you can find more about the function in here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.concat

Body:
I am creating a new dataframe by joining 4 dataframes
After which I need to concatenate two same columns from different dataframes
data:

col1   col2 expected
Acc1   Acc1 Acc1Acc1
Acc2   null Acc2
null   Acc3 Acc3

Issue:
If i do concat without replacing null values; i loose info
So after joining; since pyspark doesnt delete the common columns, we have two Account columns from 2 tables
I tried replacing it with empty string;it didnt work and throws error : dataframe is not iteratable

Query:
How do I replace null values with empty string after joining tables?
or is there any way null and concat can be handled at the sametime?

df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('Account',F.when(df2('Account').isNull(),'').otherwise(df2('Account')))\
.withColumn('Account',F.when(df3('Account').isNull(),'').otherwise(df3('Account')))\
.withColumn("Account",F.concat(F.trim(df2.Account), F.trim(df3.Account)))

Body:
Hi and welcome to StackOverflow. A function such as pyspark.sql.functions.concat_ws should do the trick here, such as:

import pyspark.sql.functions as f

df = spark.createDataFrame([
    (1, "John", "Smith"),
    (2, "Monty", "Python"),
    (3, "Donald", None),
], ['id', 'firstname', 'lastname']
)
df.show()
+---+---------+--------+
| id|firstname|lastname|
+---+---------+--------+
|  1|     John|   Smith|
|  2|    Monty|  Python|
|  3|   Donald|    null|
+---+---------+--------+

df.select(
    "*",
    f.concat_ws(
      "",
      f.trim(f.col("firstname")), f.trim(f.col("lastname"))
    ).alias("concatenated")
).show()
+---+---------+--------+------------+
| id|firstname|lastname|concatenated|
+---+---------+--------+------------+
|  1|     John|   Smith|   JohnSmith|
|  2|    Monty|  Python| MontyPython|
|  3|   Donald|    null|      Donald|
+---+---------+--------+------------+

Hope this helps, you can find more about the function in here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.concat


问:
Add a blog to an existing webpage
How can I insert a blog (not created yet) into an already existing 'static' webpage? The webpage is written mostly in PHP. I'm considering using something like WordPress.org (host install version) and using it to update the website's news page.

From what I've read, its sounds like I would need to do a lot of theme tweaking to get WordPress to display correctly with our website's template. This sounds a bit daunting to me.

答:
Greg is right, an iframe is an easy way to do this. However, I've run into situations where the iframe will throw off session variables in IE, not sure if this impacts WordPress or not.

If you're going to create a page to house a WordPress install in an iframe, why not just have the link you would use to show the page with the iframe just link to a separate sub-domain where the WordPress install will reside?

My guess is you're not wanting to do a lot with theme development if you're wanting to throw WordPress into an iframe. If this is the case you have a few choices:
(a) google for a blank wordpress theme,
(b) develop a theme that looks like you're current site so that when a user clicks on a link, they won't know they're on a different platform,
(c) don't hide anything and make the WordPress install show up with a different theme. Consider American Express in their OPEN Forum site (http://www.openforum.com/), with their blog at http://blogs.openforum.com/ - same header, slightly different body and layout.

Issues w/ going the iframe route is that a WordPress site will grow in height, where you'll have to set the height of an iframe. You can control this by setting the height to something very large, but then your page will be very large, or you can control the amount of posts that show up in the WordPress admin.

My suggestions, scrap the iframe, install your WordPress on a sub-domain and then link to that sub domain instead of linking to your iframe page

OwnerDisplayName: djbender

Title: Add a blog to an existing webpage

LastEditorDisplayName: tinkertim

OwnerDisplayName: Tim Schoffelman


答: (Without more details) The problem is most likely related to the fact that your program tries to write into the directory and then excepts the file creation/modification to actually have an effect. UAC prevents applications from writing the Program Files directories without administrator privilages. The solution is to redesign your application to not rely on such behavior or store the files in question in one of the intended locations (AppData, etc. folders).</p>

Title: Application only runs if you run as administrator?

Body:
Edit: This problem only occurs on windows 7 and vista from what I've heard.

I have a very simple app developed with an external graphics library. If I install this app into a program files directory and run it, it will crash immediately but it works fine normally, with exactly the same files. I have realised it is because you need to run the application as administrator for it to work.

I appreciate if this is a problem directly related to the graphics engine I am using, but I don't really think so (but I'm clueless). Can anyone help me?

Edit for more detail:

The application executable and files that are needed to run it are installed into the default program directory - for me, C:\Program Files (x86). If you try and run with without clicking run as administrator, it will simple freeze and say "App has stopped working. Windows is checking for a solution to the problem..." My question is basically, how can I make it so run as administrator isn't necessary?


问:
Powershell searching for line termination using Select-String
I'm using PS v5.1

Normally, if I want to search for files containing a string I use this pattern:

```<code>Get-ChildItem -recurse | Select-String "searchstring"
</code>```

This doesn't seem to work if what I'm searching for are line termination characters (\r\n).  The Select-String docs state:

Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

So it seems that sls is 'helpfully' removing my line termination characters.
I can do something like this:

```<code>gci *|get-content -raw|sls "\r\r\n" -list
</code>```

but that really isn't the same at all since it loses the filename.  I know I could write a much longer foreach construction such as:

```<code>foreach ($f in (gci -recurse *)) {
    if ($f.PSIsContainer) {
        continue
        }
    $c = Get-Content -raw $f.FullName
    if ($c.Length -ne 0) {
        $i = $c.IndexOf("`r`r`n")
        if ($i -gt 0) {
            Write-Output $f.FullName
            }
        }
    }
</code>```

But that seems rather verbose and complex for what I want to do.

Is there a better (like a concise one liner) way to do this type of search?

答:
Indeed, Select-String by design operates on individual lines when give file-information objects as input, so you cannot inspect newlines that way.

Get-Content -Raw allows you to read a file as a whole, as a single string, and PowerShell's file-system provider also adds NoteProperty members to that string, notably a .PSPath property that reflects the input file path.

Instead of Select-String, you can then use the -match operator on each file-contents string to look for the sequence of interest, and echo the .PSPath property value in case of a match:

```<code>Get-ChildItem -File -Recurse | Get-Content -Raw | ForEach-Object {
  if ($_ -match '\r\r\n') { Convert-Path $_.PSPath }
}
</code>```

Note that Convert-Path is need to convert the PowerShell provider-qualified path reported in .PSPath (e.g, Microsoft.PowerShell.Core\FileSystem::C:\Users\jdoe\file.txt) to a native filesystem path (e.g., C:\Users\jdoe\file.txt).

(This is only necessary because the input file-information objects are supplied via the pipeline.)

Body:
I'm using PS v5.1

Normally, if I want to search for files containing a string I use this pattern:

Get-ChildItem -recurse | Select-String "searchstring"

This doesn't seem to work if what I'm searching for are line termination characters (\r\n).  The Select-String docs state:

Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

So it seems that sls is 'helpfully' removing my line termination characters.
I can do something like this:

gci *|get-content -raw|sls "\r\r\n" -list

but that really isn't the same at all since it loses the filename.  I know I could write a much longer foreach construction such as:

foreach ($f in (gci -recurse *)) {
    if ($f.PSIsContainer) {
        continue
        }
    $c = Get-Content -raw $f.FullName
    if ($c.Length -ne 0) {
        $i = $c.IndexOf("`r`r`n")
        if ($i -gt 0) {
            Write-Output $f.FullName
            }
        }
    }

But that seems rather verbose and complex for what I want to do.

Is there a better (like a concise one liner) way to do this type of search?

Body:
Indeed, Select-String by design operates on individual lines when give file-information objects as input, so you cannot inspect newlines that way.

Get-Content -Raw allows you to read a file as a whole, as a single string, and PowerShell's file-system provider also adds NoteProperty members to that string, notably a .PSPath property that reflects the input file path.

Instead of Select-String, you can then use the -match operator on each file-contents string to look for the sequence of interest, and echo the .PSPath property value in case of a match:

Get-ChildItem -File -Recurse | Get-Content -Raw | ForEach-Object {
  if ($_ -match '\r\r\n') { Convert-Path $_.PSPath }
}

Note that Convert-Path is need to convert the PowerShell provider-qualified path reported in .PSPath (e.g, Microsoft.PowerShell.Core\FileSystem::C:\Users\jdoe\file.txt) to a native filesystem path (e.g., C:\Users\jdoe\file.txt).

(This is only necessary because the input file-information objects are supplied via the pipeline.)


问:
How to input data in classes in python, if number of students I want to input is not known
I want to input data in a class. I don't know  the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...

```<code>class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)
</code>```

Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english

答:
Just another idea. You could store all of the students in a dictionary that is contained within a class. Wrapping the dictionary in a class will let you add or fetch students very easily. </p>

```<code>class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

class Classroom:
    def __init__(self):
        self.students = {}

    def add_student(self, student):
        self.students[student.name] = student

    def get_student(self, name):
        return self.students[name]

classroom = Classroom();
classroom.add_student(Person("John", 12))
classroom.add_student(Person("Sarah", 13))

print(classroom.get_student("Sarah").age)

#Output
#13
</code>```

```<code>def main():
    classroom = Classroom()
    n = input("How many students would you like yo add? ")
    for i in range(int(n)):
        classroom.add_student(Person(input("Enter Name: "), int(input("Enter Age: "))))

</code>```

Body:
I want to input data in a class. I don't know  the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)

Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english

Body:
Just another idea. You could store all of the students in a dictionary that is contained within a class. Wrapping the dictionary in a class will let you add or fetch students very easily.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

class Classroom:
    def __init__(self):
        self.students = {}

    def add_student(self, student):
        self.students[student.name] = student

    def get_student(self, name):
        return self.students[name]

classroom = Classroom();
classroom.add_student(Person("John", 12))
classroom.add_student(Person("Sarah", 13))

print(classroom.get_student("Sarah").age)

#Output
#13

def main():
    classroom = Classroom()
    n = input("How many students would you like yo add? ")
    for i in range(int(n)):
        classroom.add_student(Person(input("Enter Name: "), int(input("Enter Age: "))))