问:
Fetch last three orders from a table
Consider a table with the following columns:

Customer Email ID

Payment Method (COD/ Netbanking/ CreditCard/ DebitCard)

Order ID

Order Creation Date

Order Status(Success/ Failed/ Cancelled)

How do I fetch the last three successful orders past 3 months for each customer from these table in SQL along with the relevant details?

答:
This is a bit painful in MySQL.  Probably the simplest method is to use variables.

Your column names are not clear.  And you have some additional conditions, but this is the basic idea:

```<code>select t.*
from (select t.*,
             (@rn := if(@c = customerid, @rn + 1,
                        if(@c := customerid, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @rn := 0, @c := '') params
      order by customerid, orderdate desc
     ) t
where rn <= 3;
</code>```

You can add the additional where conditions to the subquery.

Title: Fetch last three orders from a table

Body:
This is a bit painful in MySQL.  Probably the simplest method is to use variables.

Your column names are not clear.  And you have some additional conditions, but this is the basic idea:

select t.*
from (select t.*,
             (@rn := if(@c = customerid, @rn + 1,
                        if(@c := customerid, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @rn := 0, @c := '') params
      order by customerid, orderdate desc
     ) t
where rn <= 3;

You can add the additional where conditions to the subquery.


来源: stackexchange

问:
How to check what type is store?
In ExtJS framework we can define different types of stores. Such as

Ext.data.BufforedStore, Ext.data.ChainedStore, Ext.data.Store etc.

Example store definition:

```<code>Ext.define('App.store.Admins', {
    extend: 'Ext.data.ChainedStore',
    ...
    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};
        me.callParent([Ext.apply({
        ...
            alias: 'admins',
            storeId: 'admins',
            source: 'users'
        ...
    }
})
</code>```

In view configuration of Ext.grid.Panel class we must set data source to which the grid / tree is bound.

```<code>Ext.define('App.view.Grid',{
    extend: 'Ext.grid.Panel',
    ...
    id: 'admins-grid',
    store: 'admins',
    ...
});
</code>```

On a some controller, I would like to get information about the type of store defined in this grid. How to do it?

```<code>var grid = Ext.getCmp('admins-grid');
var store = grid.getStore();
//what's next?
</code>```

I've found solution, but is it the best way?

```<code>var isChained = store instanceof Ext.data.ChainedStore;
</code>```

答:
Instanceof is the plain javascript way which should always work.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/instanceof

If a store has the source config and no load method it will be most likely a ChainedStore.

http://docs.sencha.com/extjs/6.0.1/classic/src/ChainedStore.js.html#Ext.data.ChainedStore

If a store has the config buffered and isBufferedStore it will be a buffered store.

http://docs.sencha.com/extjs/6.0.1/classic/src/BufferedStore.js.html#Ext.data.BufferedStore

Depending on your use case i would go the same way Thomas described here already and add to method to your extended chainedStore.

ContentLicense: CC BY-SA 3.0

Title: How to check what type is store?

Body:
In ExtJS framework we can define different types of stores. Such as

Ext.data.BufforedStore, Ext.data.ChainedStore, Ext.data.Store etc.

Example store definition:

Ext.define('App.store.Admins', {
    extend: 'Ext.data.ChainedStore',
    ...
    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};
        me.callParent([Ext.apply({
        ...
            alias: 'admins',
            storeId: 'admins',
            source: 'users'
        ...
    }
})

In view configuration of Ext.grid.Panel class we must set data source to which the grid / tree is bound.

Ext.define('App.view.Grid',{
    extend: 'Ext.grid.Panel',
    ...
    id: 'admins-grid',
    store: 'admins',
    ...
});

On a some controller, I would like to get information about the type of store defined in this grid. How to do it?

var grid = Ext.getCmp('admins-grid');
var store = grid.getStore();
//what's next?

I've found solution, but is it the best way?

var isChained = store instanceof Ext.data.ChainedStore;


问:
Accessing remote folder from win form C#
I am developing a winform application on C# where I need to access a network folder but i get logon user password exception. How can i provide user credentials through application?</p>

```<code>double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) / 1024;
</code>```

答:
Try this

```<code>using (new NetworkConnection(@"\\192.168.50.107\Destination", readCredentials))
using (new NetworkConnection(@"\\192.168.50.107\Destination", writeCredentials)) {
   double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*",    SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) /   1024;
}
</code>```

Font: How to provide user name and password when connecting to a network share

Body:
I am developing a winform application on C# where I need to access a network folder but i get logon user password exception. How can i provide user credentials through application?

double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) / 1024;

Body:
Try this

using (new NetworkConnection(@"\\192.168.50.107\Destination", readCredentials))
using (new NetworkConnection(@"\\192.168.50.107\Destination", writeCredentials)) {
   double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*",    SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) /   1024;
}

Font: How to provide user name and password when connecting to a network share


问:
cordova plugin file transfer
I have a cordova app with functionality to download a pdf doc and store in a cordova file location. Any help or advice would be appreciated.

cordova version : 6.4.0

plugin version : cordova-plugin-file-transfer 1.4.0 "File Transfer"

platform : ios 10.2.1

url returning error code 2 :

file:///var/mobile/Containers/Data/Application/4FC21BCF-DFC4-4A85-BA17-1F9C300B45F3/Documents/4092477_Unlock Scanner Guide.pdf

Here is the function :

```<code>function downloadAsset(err) {
isDownloaded = true;
window.resolveLocalFileSystemURL(cordova.file.documentsDirectory, function (dirEntry) {
    console.log('file system open: ', dirEntry);
    target = dirEntry.toURL();
    target = target + fileName;
    var fileTransfer = new FileTransfer();
    console.log("About to start transfer");
    console.log(target+fileName);
    fileTransfer.download(assetURL, target,
        function(entry) {
            console.log("Success!");
            appStart(target);
        },
        function(e) {
            console.log("Error");
            console.dir(e);
        });
}, resOnError);
</code>```

}

答:
```<code>var url = "YOUR URL";
var dest = "YOUR DEST FILE PATH";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
    fs.root.getFile(dest, { create: true, exclusive: false }, function (fileEntry) {
        var fileTransfer = new FileTransfer();
        fileTransfer.download(
            encodeURI(url),
            fileEntry.toURL(),
            function(entry){
                //DOWNLOAD OK
            },
            function(err){
                //ERROR
            },
            null,
            {}
        );
    }, function(err){
        //ERROR
    });
}, function(err){
    //ERROR
});
</code>```

Title: cordova plugin file transfer

Body:
I have a cordova app with functionality to download a pdf doc and store in a cordova file location. Any help or advice would be appreciated.

cordova version : 6.4.0

plugin version : cordova-plugin-file-transfer 1.4.0 "File Transfer"

platform : ios 10.2.1

url returning error code 2 :

file:///var/mobile/Containers/Data/Application/4FC21BCF-DFC4-4A85-BA17-1F9C300B45F3/Documents/4092477_Unlock Scanner Guide.pdf

Here is the function :

function downloadAsset(err) {
isDownloaded = true;
window.resolveLocalFileSystemURL(cordova.file.documentsDirectory, function (dirEntry) {
    console.log('file system open: ', dirEntry);
    target = dirEntry.toURL();
    target = target + fileName;
    var fileTransfer = new FileTransfer();
    console.log("About to start transfer");
    console.log(target+fileName);
    fileTransfer.download(assetURL, target,
        function(entry) {
            console.log("Success!");
            appStart(target);
        },
        function(e) {
            console.log("Error");
            console.dir(e);
        });
}, resOnError);

}


问:
Bash: Check if a string looks like a three part version number using a regular expression
I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

Here's what I tried:

```<code>#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then
     echo "true"
 else
     echo "false"
fi
</code>```

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

What am I doing wrong?

答:
You need to declare the regex as a separate variable inside single quotes, there will be no issues parsing your regex in bash then and make sure the parentheses are placed around the [0-9]{1,2}\. part:

```<code>rx='^([0-9]{1,2}\.){2}[0-9]{1,2}$'
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ $rx ]]
</code>```

See the online Bash demo

Now, the pattern matches:

^ - start of string

([0-9]{1,2}\.){2}  - 2 occurrences of 1 or 2 digits followed with a literal dot

[0-9]{1,2} - 1 or 2 digits

$ - end of string.

Body:
I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

Here's what I tried:

#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then
     echo "true"
 else
     echo "false"
fi

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

What am I doing wrong?

Body:
You need to declare the regex as a separate variable inside single quotes, there will be no issues parsing your regex in bash then and make sure the parentheses are placed around the [0-9]{1,2}\. part:

rx='^([0-9]{1,2}\.){2}[0-9]{1,2}$'
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ $rx ]]

See the online Bash demo

Now, the pattern matches:

^ - start of string

([0-9]{1,2}\.){2}  - 2 occurrences of 1 or 2 digits followed with a literal dot

[0-9]{1,2} - 1 or 2 digits

$ - end of string.


问:
How to create soap service using GET method
I'm beginner to the soap web service. When I create soap service don't think about That service is POST or GET .But when we create REST service we initialize that service is POST or GET.

I created soap web service.Here is my code

```<code>@WebService(targetNamespace = "http://service.test.hameedia.com/", portName = "HameediaTestServicePort", serviceName = "HameediaTestServiceService")

public class SoapServiceTest{

     public String details(String name){
        //some thing in here
     }
}
</code>```

But in here we didn't initialize this is POST or GET .But console show this is POST method.My question is

Is soap web services default method type POST

If is it not

How to create soap web service with GET method

I get some idea from this.But I'm not clear with my question.If you have any idea about this please share.

答:
SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification.

SOAP is not depended upon HTTP and HTTP Method(s), SOAP can extend HTTP for XML messaging.

You can call SOAP Web Service over HTTP and you have to use POST method only because of complex nature of the SOAP Request.

Ref : https://www.tutorialspoint.com/soap/what_is_soap.htm

Body:
I'm beginner to the soap web service. When I create soap service don't think about That service is POST or GET .But when we create REST service we initialize that service is POST or GET.

I created soap web service.Here is my code

@WebService(targetNamespace = "http://service.test.hameedia.com/", portName = "HameediaTestServicePort", serviceName = "HameediaTestServiceService")

public class SoapServiceTest{

     public String details(String name){
        //some thing in here
     }
}

But in here we didn't initialize this is POST or GET .But console show this is POST method.My question is

Is soap web services default method type POST

If is it not

How to create soap web service with GET method

I get some idea from this.But I'm not clear with my question.If you have any idea about this please share.


问:
Ionic 2: View does not update based on model change
I have a very simple page with a couple of controls.

My issue is that the page does not pickup changes to the model when the icon in upper right corner is clicked. This toggles the showFilterPane variable, which again should show or hide a div based on *ngIf="showFilterPane".

I have another page just like this one working, and I can not figure out why this isn't.

Any tips?

(I've tried using the ChangeDetectorRef.detectChanges(); which works, but then the rangeslider will not work. The draggable point doesn't update, or does not move to where you tap.)

The page:

```<code><ion-header>
  <ion-navbar>
    <ion-title>MY AO</ion-title>
    <ion-buttons end>
      <button ion-button (click)="toggleFilterPane()" icon-only>
        <ion-icon name="options"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>
  <div class="container">
    <div class="left">
      <div *ngIf="isSearching" class="spinner-container">
        <ion-spinner></ion-spinner>
      </div>
      <!-- put content here -->

    </div>

    <div class="right" *ngIf="showFilterPane">
      <ion-list inset>
        <ion-list-header>BANA</ion-list-header>
        <ion-item>
          <ion-select multiple="true" [(ngModel)]="woTrackFilter">
            <ion-option>1</ion-option>
            <ion-option>2</ion-option>
            <ion-option>3</ion-option>
            <ion-option>4</ion-option>
            <ion-option>5</ion-option>
          </ion-select>
        </ion-item>
      </ion-list>
      <ion-list inset>
        <ion-list-header>TEKNIKSLAG</ion-list-header>
        <ion-item>
          <ion-select multiple="true" [(ngModel)]="woDisciplineFilter">
            <ion-option>Signal</ion-option>
            <ion-option>Bana</ion-option>
            <ion-option>EL</ion-option>
            <ion-option>Tele</ion-option>
          </ion-select>
        </ion-item>
      </ion-list>
      <ion-list inset>
        <ion-list-header>DAGAR</ion-list-header>
        <ion-item>
          <ion-range min="10" max="80" step="4" [(ngModel)]="woDaysFilter">
            <ion-label range-left>10</ion-label>
            <ion-label range-right>80</ion-label>>
          </ion-range>
        </ion-item>
      </ion-list>
      <button ion-button (click)="doSearch()">Search</button>
    </div>
  </div>
</ion-content>
</code>```

The component:

```<code>    import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { WorkOrderDashboardPage } from "../work-order-dashboard/work-order-dashboard";
@Component({
  selector: 'page-work-order-list',
  templateUrl: 'work-order-list.html'
})
export class WorkOrderListPage {
  private isSearching: boolean = false;
  private showFilterPane: boolean=false;
  private woTrackFilter: string[];
  private woDisciplineFilter: string[];
  private woDaysFilter: number;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    // Initialize storage providers here

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WorkOrderListPage');
  }

  toggleFilterPane(): void {
    this.showFilterPane = !this.showFilterPane;
  }

  viewWorkOrder(event, workOrder): void {
    this.navCtrl.push(WorkOrderDashboardPage, { workOrder: workOrder });
  }

  doSearch(): void {
    console.log(this.woTrackFilter);
    console.log(this.woDisciplineFilter);
    console.log(this.woDaysFilter);
  }
}
</code>```

UPDATE: Found workaround
I tried creating a separate app, where the exact same code is working. That lead me to think something wasn't right on the LoginPage, the page that called setRoot() to the above page.

The login code looked like this:

```<code>WLAuthorizationManager.login("UserLogin", data).then(() => {
  // Success
  console.log("Logged in");
  this.navCtrl.setRoot(WorkOrderListPage);
},
(err) => {
  // failed
  console.error(err);
  this.showError("Username or password is incorrect");
})
</code>```

I then figured it might be some Zone issue, and wrapped the setRoot call in zone.run() like this:

```<code>  WLAuthorizationManager.login("UserLogin", data).then(() => {
  // Success
  console.log("Logged in");
  this.zone.run(() =>
    this.navCtrl.setRoot(WorkOrderListPage)
  );
},
(err) => {
  // failed
  console.error(err);
  this.showError("Username or password is incorrect");
})
</code>```

After that the view started to respond as expected. I feel this is a bit of a hack. Can someone shed some light as to what is happening here?

答:
Seems like you are basically using ngZone to make sure Angular knows you changed things so it will reload that part of the DOM to reflect the changes. I don't feel like it's a hack, because you are just making sure that it works as intended.

Angular 2 has some optimization features that help make your app run smoother and one of those is avoiding DOM updates whenever and wherever possible. By using zones (or ngZones) you are basically telling Angular "pay attention to this part, it changes and I need that change to be reflected in the DOM".

I've run into that sort of problem before myself and using zones is usually your best bet. Got into situations where a part of the interface would be stuck unless you touched a button or somesuch.

Another workaround (at least for range sliders) is using the AppllicationRef tick() method, which forces a DOM update. More info about it here.

Body:
I have a very simple page with a couple of controls.

My issue is that the page does not pickup changes to the model when the icon in upper right corner is clicked. This toggles the showFilterPane variable, which again should show or hide a div based on *ngIf="showFilterPane".

I have another page just like this one working, and I can not figure out why this isn't.

Any tips?

(I've tried using the ChangeDetectorRef.detectChanges(); which works, but then the rangeslider will not work. The draggable point doesn't update, or does not move to where you tap.)

The page:

<ion-header>
  <ion-navbar>
    <ion-title>MY AO</ion-title>
    <ion-buttons end>
      <button ion-button (click)="toggleFilterPane()" icon-only>
        <ion-icon name="options"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>

        <ion-spinner></ion-spinner>

      <ion-list inset>
        <ion-list-header>BANA</ion-list-header>
        <ion-item>
          <ion-select multiple="true" [(ngModel)]="woTrackFilter">
            <ion-option>1</ion-option>
            <ion-option>2</ion-option>
            <ion-option>3</ion-option>
            <ion-option>4</ion-option>
            <ion-option>5</ion-option>
          </ion-select>
        </ion-item>
      </ion-list>
      <ion-list inset>
        <ion-list-header>TEKNIKSLAG</ion-list-header>
        <ion-item>
          <ion-select multiple="true" [(ngModel)]="woDisciplineFilter">
            <ion-option>Signal</ion-option>
            <ion-option>Bana</ion-option>
            <ion-option>EL</ion-option>
            <ion-option>Tele</ion-option>
          </ion-select>
        </ion-item>
      </ion-list>
      <ion-list inset>
        <ion-list-header>DAGAR</ion-list-header>
        <ion-item>
          <ion-range min="10" max="80" step="4" [(ngModel)]="woDaysFilter">
            <ion-label range-left>10</ion-label>
            <ion-label range-right>80</ion-label>>
          </ion-range>
        </ion-item>
      </ion-list>
      <button ion-button (click)="doSearch()">Search</button>

</ion-content>

The component:

    import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { WorkOrderDashboardPage } from "../work-order-dashboard/work-order-dashboard";
@Component({
  selector: 'page-work-order-list',
  templateUrl: 'work-order-list.html'
})
export class WorkOrderListPage {
  private isSearching: boolean = false;
  private showFilterPane: boolean=false;
  private woTrackFilter: string[];
  private woDisciplineFilter: string[];
  private woDaysFilter: number;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    // Initialize storage providers here

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WorkOrderListPage');
  }

  toggleFilterPane(): void {
    this.showFilterPane = !this.showFilterPane;
  }

  viewWorkOrder(event, workOrder): void {
    this.navCtrl.push(WorkOrderDashboardPage, { workOrder: workOrder });
  }

  doSearch(): void {
    console.log(this.woTrackFilter);
    console.log(this.woDisciplineFilter);
    console.log(this.woDaysFilter);
  }
}

UPDATE: Found workaround
I tried creating a separate app, where the exact same code is working. That lead me to think something wasn't right on the LoginPage, the page that called setRoot() to the above page.

The login code looked like this:

WLAuthorizationManager.login("UserLogin", data).then(() => {
  // Success
  console.log("Logged in");
  this.navCtrl.setRoot(WorkOrderListPage);
},
(err) => {
  // failed
  console.error(err);
  this.showError("Username or password is incorrect");
})

I then figured it might be some Zone issue, and wrapped the setRoot call in zone.run() like this:

  WLAuthorizationManager.login("UserLogin", data).then(() => {
  // Success
  console.log("Logged in");
  this.zone.run(() =>
    this.navCtrl.setRoot(WorkOrderListPage)
  );
},
(err) => {
  // failed
  console.error(err);
  this.showError("Username or password is incorrect");
})

After that the view started to respond as expected. I feel this is a bit of a hack. Can someone shed some light as to what is happening here?


问:
12 month rolling from a entered month?
Hi can someone please help me, I want to create a script with a month parameter, the results I require is the next 12 month's names as column headings.

For example if the parameter is February the results should be:

```<code>March | April | May | June | July | August | September | October | November | December | January | February |
</code>```

As the column names which I want to use to fill in values at a later stage.
Can someone please advise me on this and how I can achieve this

My script I have so far don't know how to approach this

```<code>declare @MonthParam varchar(20) = 'March'
declare @MonthNumber int = (
Select CASE WHEN @MonthParam = 'January' THEN 1
            WHEN @MonthParam = 'February' THEN 2
            WHEN @MonthParam = 'March' THEN 3
            WHEN @MonthParam = 'April' THEN 4
            WHEN @MonthParam = 'May' THEN 5
            WHEN @MonthParam = 'June' THEN 6
            WHEN @MonthParam = 'July' THEN 7
            WHEN @MonthParam = 'August' THEN 8
            WHEN @MonthParam = 'September' THEN 9
            WHEN @MonthParam = 'October' THEN 10
            WHEN @MonthParam = 'November' THEN 11
            WHEN @MonthParam = 'December' THEN 12
END)
WHILE(@MonthNumber < 13)

    BEGIN

    declare @month varchar(20) = DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
    declare @sql varchar(max)
    set @sql = 'select val as ' + @month + ' from t'
    exec (@sql)

    SET @MonthNumber = @MonthNumber + 1;

    END
</code>```

答:
```<code>declare @date_entered varchar(50) = 'February'
set @date_entered = @date_entered + ' 01 ' + CONVERT(char(4),year(getdate()))
declare @start_month datetime = @date_entered
declare @loop_month datetime = @start_month

declare @sql nvarchar(max)

set @sql = 'CREATE TABLE MyDates ('

WHILE @loop_month < DATEADD(year,1,@start_month)
BEGIN
    set @sql += DATENAME(month,@loop_month) + ' varchar(100),'
    set @loop_month = DATEADD(month,1,@loop_month)
END

-- Get rid of the comma at the end of the string and close the table paranthesis (edit was to the following bit)
set @sql = LEFT(@sql,len(@sql)-1) + ')'

print @sql
--Uncomment below to run
--exec(@sql)
</code>```

Title: 12 month rolling from a entered month?

Body:
Hi can someone please help me, I want to create a script with a month parameter, the results I require is the next 12 month's names as column headings.

For example if the parameter is February the results should be:

March | April | May | June | July | August | September | October | November | December | January | February |

As the column names which I want to use to fill in values at a later stage.
Can someone please advise me on this and how I can achieve this

My script I have so far don't know how to approach this

declare @MonthParam varchar(20) = 'March'
declare @MonthNumber int = (
Select CASE WHEN @MonthParam = 'January' THEN 1
            WHEN @MonthParam = 'February' THEN 2
            WHEN @MonthParam = 'March' THEN 3
            WHEN @MonthParam = 'April' THEN 4
            WHEN @MonthParam = 'May' THEN 5
            WHEN @MonthParam = 'June' THEN 6
            WHEN @MonthParam = 'July' THEN 7
            WHEN @MonthParam = 'August' THEN 8
            WHEN @MonthParam = 'September' THEN 9
            WHEN @MonthParam = 'October' THEN 10
            WHEN @MonthParam = 'November' THEN 11
            WHEN @MonthParam = 'December' THEN 12
END)
WHILE(@MonthNumber < 13)

    BEGIN

    declare @month varchar(20) = DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
    declare @sql varchar(max)
    set @sql = 'select val as ' + @month + ' from t'
    exec (@sql)

    SET @MonthNumber = @MonthNumber + 1;

    END


问:
How can I find words in matrix of letters
This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

答:
How about:

build a search tree for the dictionary (one level per letter)

for each position in the grid, start searching through the index, one character at a time, and proceed in each allowed direction until there are no entries left in the index, or you hit a grid boundary

I don't think a hash would be a very useful optimization here.

ContentLicense: CC BY-SA 2.5


问:
Identify and extract table from pdf using java
I have different types of pdf which contain multiple things like text, table etc.  The table may exist any place of pdf(top, middle, bottom).
I want to extract only table data(No. of the column, no. of rows & data in a table)  from that pdf using java without passing location.

What I have done till yet:-

1. I have used iText java API to read and extract. Following code used:-

PdfTextExtractor.getTextFromPage

but It is only returning data in form of text. Didn't get any clue to identify where table exists in pdf and how to extract data from that table.

2. I have also used PDFBox java API but it didn't solve my problem too.

3. I have also followed this stack overflow link:-
PDF table extraction
But it is not giving me expected output. This algorithm needs except line position and all.

I am not able to identify where to locate the table in pdf.

Can anybody tell me how to solve this problem using iText & PDF box API or is there any open source API which can help me to solve this problem?

Or can we convert pdf into html so that by table tags we can identify table and read ;)?

答:
It basically depends on your input document, and how much effort you're willing to put into this project.

A pdf does not work like an html-document. In html documents you have logical tags like "table" or "paragraph". A pdf document (in the most basic case) contains only the instructions needed to render the document.
So instead of getting "table" you might get "draw a line here, and another one a bit further away, and then another one that crosses both, and so on"

Also, according to the pdf specification, these instructions don't even have to appear in logical (reading) order.

If you are lucky, your input pdf might be a tagged PDF. Tagged pdfs contain an internal representation of the underlying structure in the document. A tagged pdf might be able to tell you exactly which objects in the document make up the table.

Now, to get back to an actual answer.
If you want a solution that always works, you can implement the iText7 IEventListener class. This class has a method eventOccurred() that gets called every time the parser has finished dealing with an object (like a piece of text, a line, etc)

If you then look out for lines, and build some heuristic to determine when a collection of lines constitutes a table, you should be able to detect tables.

IText also plans on releasing a pdf2Data addon, which will basically do the heavy lifting for you.


问:
Laravel output single row from database
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}
</code>```

}

I would think that I am missing something in the MainController

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}
</code>```

Could that be?

Thanks in advance!

答:
Using with() flashes content to a session, rather you need to pass in the variables to the view

```<code>view('index', $data)
</code>```

Where $data is the data from the database.

Title: Laravel output single row from database

Body:
I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website.
I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this {{ $text->"insert specific id" }}
My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();

    return redirect()->route('texts.index');
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

I would think that I am missing something in the MainController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;

class MainController extends Controller
{
public function index(){

    return view('index');
}

Could that be?

Thanks in advance!

Body:
Using with() flashes content to a session, rather you need to pass in the variables to the view

view('index', $data)

Where $data is the data from the database.


问:
I have a checkbox inside a fragment and i want to it respond on click of a button this button is inside my main activity?
i am just working with fragments for the 1st time, i have a checkbox inside a fragment and a submit button inside my main activity. what i want to do is when i press submit button i want to toast a message whether the checkbox item is checked or not?

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    private Spinner Dspinner;
    private Button Subbtn;

    ArrayAdapter adapter;

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

        Subbtn = (Button)findViewById(R.id.button);

        adapter = ArrayAdapter.createFromResource(this, R.array.spinner_options, android.R.layout.simple_spinner_item);

        spinnerListner();
    }

    public void spinnerListner(){
        Dspinner = (Spinner)findViewById(R.id.spinner);
        Dspinner.setAdapter(adapter);
        Dspinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        switch (position){
                            case 0:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment.newInstance()).addToBackStack(null).commit();
                                break;
                            case 1:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment2.newInstance()).addToBackStack(null).commit();
                                break;
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                }
        );
    }
}
</code>```

BlankFragment.java

```<code>public class BlankFragment extends Fragment {

    public BlankFragment(){

    }

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    public static Fragment newInstance() {
        BlankFragment fragment = new BlankFragment();
        return fragment;
    }
}
</code>```

BlankFragment2.java

```<code>public class BlankFragment2 extends Fragment {

    public BlankFragment2(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank_2, container, false);
    }

    public static Fragment newInstance() {
        BlankFragment2 fragment = new BlankFragment2();
        return fragment;
    }
}
</code>```

答:
This is yet another way different from what i commented that day this might meet your need

In Main Activty

```<code>    Blank1Fragment fragment1 = new Blank1Fragment();
    Blank2Fragment fragment2 = new Blank2Fragment();

Subbtn..setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
if(position==0)
fragment1.function();
else if(position==1)
fragment2.function();
}
);
</code>```

in OnitemClick of spinner

```<code>switch (position){
                            case 0:
                                position=0;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment1).addToBackStack(null).commit();
                                break;
                            case 1:
                                position=1;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment2).addToBackStack(null).commit();
                                break;
                        }
                    }
</code>```

Each fragment will have

```<code>public class Blank1Fragment extends Fragment {

....
    public  void function(){
        //check which checkbox selected and toast;
    }

}

public class Blank2Fragment extends Fragment {

....
    public  void function(){
        //check which checkbox selected and toast;
    }

}
</code>```

Body:
i am just working with fragments for the 1st time, i have a checkbox inside a fragment and a submit button inside my main activity. what i want to do is when i press submit button i want to toast a message whether the checkbox item is checked or not?

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Spinner Dspinner;
    private Button Subbtn;

    ArrayAdapter adapter;

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

        Subbtn = (Button)findViewById(R.id.button);

        adapter = ArrayAdapter.createFromResource(this, R.array.spinner_options, android.R.layout.simple_spinner_item);

        spinnerListner();
    }

    public void spinnerListner(){
        Dspinner = (Spinner)findViewById(R.id.spinner);
        Dspinner.setAdapter(adapter);
        Dspinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        switch (position){
                            case 0:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment.newInstance()).addToBackStack(null).commit();
                                break;
                            case 1:
                                getSupportFragmentManager().beginTransaction().replace(R.id.frag, BlankFragment2.newInstance()).addToBackStack(null).commit();
                                break;
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                }
        );
    }
}

BlankFragment.java

public class BlankFragment extends Fragment {

    public BlankFragment(){

    }

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    public static Fragment newInstance() {
        BlankFragment fragment = new BlankFragment();
        return fragment;
    }
}

BlankFragment2.java

public class BlankFragment2 extends Fragment {

    public BlankFragment2(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank_2, container, false);
    }

    public static Fragment newInstance() {
        BlankFragment2 fragment = new BlankFragment2();
        return fragment;
    }
}

Body:
This is yet another way different from what i commented that day this might meet your need

In Main Activty

    Blank1Fragment fragment1 = new Blank1Fragment();
    Blank2Fragment fragment2 = new Blank2Fragment();

Subbtn..setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
if(position==0)
fragment1.function();
else if(position==1)
fragment2.function();
}
);

in OnitemClick of spinner

switch (position){
                            case 0:
                                position=0;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment1).addToBackStack(null).commit();
                                break;
                            case 1:
                                position=1;
getSupportFragmentManager().beginTransaction().replace(R.id.frag, fragment2).addToBackStack(null).commit();
                                break;
                        }
                    }

Each fragment will have

public class Blank1Fragment extends Fragment {

....
    public  void function(){
        //check which checkbox selected and toast;
    }

}

public class Blank2Fragment extends Fragment {

....
    public  void function(){
        //check which checkbox selected and toast;
    }

}


问:
Is it possible to use winmerge to view git diffs from cygwin?
I like to use git on cygwin, but the only downside I have is when I want to git difftool I cannot use anything useful. git diff is fine for me most of the time, but sometimes I'd like to use winmerge to view these diffs via git difftool is there some way to set this up?

答:
For cygwin, the SO question "How can I configure Mercurial to use WinMerge for merges, under cygwin?" can be applied to git (when combining the following winmerge script with the older question "use Winmerge inside of Git to file diff")

```<code>#!/bin/sh
"/cygdrive/c/Program Files/WinMerge/WinMergeU.EXE" /e /ub /dl other /dr local `cygpath -aw $1` `cygpath -aw $2` `cygpath -aw $3`
</code>```

Process

You have more details in this article "Git + WinMerge + Cygwin" (from Thiru Thirunavukarasu):

(but I would still recommend the WinMergeU.exe options from above)

Add the following lines to your .gitconfig file:

```<code>  [diff]
    tool = winmerge
  [difftool "winmerge"]
    cmd = git-difftool-winmerge-wrapper.sh \"$LOCAL\" \"$REMOTE\"
  [difftool]
    prompt = false
</code>```

The last option (prompt = false) is optional. You can omit it if you do want Git to prompt you before opening each diff.

Create a file named git-difftool-winmerge-wrapper.sh and place it in your path.

  I just dropped it in my home directory. You can change the default Cygwin path to include your home directory by modifying the .bash_profile file (also in your home directory) and adding PATH=${PATH}:${HOME}

Add the following to git-difftool-winmerge-wrapper.sh:

```<code>  #!/bin/sh
  echo "Launching WinMergeU.exe \"$(cygpath -aw "$1")\" \"$(cygpath -aw "$2")\""
  if [ -f "$1" -a -f "$2" ]
  then
    "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -u -wl -dl "Base" -dr "Mine" "$(cygpath -aw "$1")" "$(cygpath -aw "$2")"
  else
    echo "skipping as one file doesn't exist"
  fi
</code>```

(again, do some testing with those WinMerge options)

Scripts

If you want to go "all WinMerge", both for diff and merge git functions, you have this gist page to follow from ecerulm (Ruben Laguna):

diffmerge-diff.sh

```<code>#!/bin/sh
# Use SourceGear DiffMerge as mergetool for git in cygwin.
#   git config --global mergetool.diffmerge.cmd "diffmergetool.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.diffmerge.trustExitCode false
#   git difftool -t diffmerge branch1..branch2

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching DiffMerge.exe - diffmerge-diff.sh:

set_path_vars "$1" "$2" "$3" "$4"

echo "$diffmergewinpath" -t1=FROM_VERSION -t2=TO_VERSION --caption=$caption $localwinpath $remotewinpath
"$diffmergewinpath" -t1=FROM_VERSION -t2=TO_VERSION --caption="$caption" "$localwinpath" "$remotewinpath"
</code>```

diffmerge-merge.sh

```<code>#!/bin/sh
# Use SourceGear DiffMerge as mergetool for git in cygwin.
#   git config --global mergetool.diffmerge.cmd "diffmergetool.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.diffmerge.trustExitCode false
#   git mergetool -t diffmerge

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching DiffMerge.exe - diffmerge-merge.sh:

set_path_vars "$1" "$2" "$3" "$4"

"$diffmergewinpath" --merge -t1=FROM_VERSION -t2=MERGED -t3=TO_VERSION --result="$mergedwinpath" --caption="$caption" "$localwinpath" "$basewinpath" "$remotewinpath"

unix2dos "$merged"
</code>```

githelperfunctions.sh

```<code># Helper functions

convert_path () {
    file=$1

    if [ "$file" == '/dev/null' ] || [ ! -e "$file" ]
        then
           file="/tmp/nulla"
           `echo "">$file`
    fi
    echo `cygpath -w -a "$file"`
}

set_path_vars () {
    local=$1
    remote=$2
    base=$3
    merged=$4

    echo ========= Cygwin paths =======
    echo "LOCAL   :  $local"
    echo "REMOTE  :  $remote"
    echo "BASE    :  $base"
    echo "MERGED  :  $merged"

    localwinpath=$(convert_path "$local")
    remotewinpath=$(convert_path "$remote")
    basewinpath=$(convert_path "$base")
    mergedwinpath=$(convert_path "$merged")

    echo ========= Win paths =======
    echo "LOCAL   :  $localwinpath"
    echo "REMOTE  :  $remotewinpath"
    echo "BASE    :  $basewinpath"
    echo "MERGED  :  $mergedwinpath"

    caption=`basename "$merged"`
    diffmergewinpath="C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe"
    winmergewinpath="C:/Program Files/WinMerge/WinMergeU.exe"
#   diffmergewinpath=`cygpath -u C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe`
#   winmergewinpath=`cygpath -u \"C:\Program Files\WinMerge\WinMergeU.exe\"`
}
</code>```

winmerge-diff.sh

```<code>#!/bin/sh
# Use winmerge as mergetool for git in cygwin.
#   git config --global difftool.winmerge.cmd "winmerge-diff.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\""
#   git config --global mergetool.winmerge.trustExitCode false
#   git difftool -t winmerge branch1..branch2

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf
# Reference: http://winmerge.org/docs/manual/CommandLine.html

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching winmerge.exe - winmerge-diff.sh:

set_path_vars "$1" "$2" "$3" "$4"

"$winmergewinpath" /dl "LOCAL.$caption" /dr "TO_VERSION.$caption" "$localwinpath" "$remotewinpath"
</code>```

winmerge-merge.sh

```<code>#!/bin/sh
# Use winmerge as mergetool for git in cygwin.
#   git config --global mergetool.winmerge.cmd "winmerge-merge.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.winmerge.trustExitCode false
#   git mergetool -t diffmerge

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf
# Reference: http://winmerge.org/docs/manual/CommandLine.html

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching winmerge.exe - winmerge-merge.sh:

set_path_vars "$1" "$2" "$3" "$4"

# -- use WinMergeU conflictFile
"$winmergewinpath" "$mergedwinpath"
</code>```

OwnerDisplayName: Erik Vold

Body:
For cygwin, the SO question "How can I configure Mercurial to use WinMerge for merges, under cygwin?" can be applied to git (when combining the following winmerge script with the older question "use Winmerge inside of Git to file diff")

#!/bin/sh
"/cygdrive/c/Program Files/WinMerge/WinMergeU.EXE" /e /ub /dl other /dr local `cygpath -aw $1` `cygpath -aw $2` `cygpath -aw $3`

Process

You have more details in this article "Git + WinMerge + Cygwin" (from Thiru Thirunavukarasu):

(but I would still recommend the WinMergeU.exe options from above)

Add the following lines to your .gitconfig file:

  [diff]
    tool = winmerge
  [difftool "winmerge"]
    cmd = git-difftool-winmerge-wrapper.sh \"$LOCAL\" \"$REMOTE\"
  [difftool]
    prompt = false

The last option (prompt = false) is optional. You can omit it if you do want Git to prompt you before opening each diff.

Create a file named git-difftool-winmerge-wrapper.sh and place it in your path.

  I just dropped it in my home directory. You can change the default Cygwin path to include your home directory by modifying the .bash_profile file (also in your home directory) and adding PATH=${PATH}:${HOME}

Add the following to git-difftool-winmerge-wrapper.sh:

  #!/bin/sh
  echo "Launching WinMergeU.exe \"$(cygpath -aw "$1")\" \"$(cygpath -aw "$2")\""
  if [ -f "$1" -a -f "$2" ]
  then
    "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -u -wl -dl "Base" -dr "Mine" "$(cygpath -aw "$1")" "$(cygpath -aw "$2")"
  else
    echo "skipping as one file doesn't exist"
  fi

(again, do some testing with those WinMerge options)

Scripts

If you want to go "all WinMerge", both for diff and merge git functions, you have this gist page to follow from ecerulm (Ruben Laguna):

diffmerge-diff.sh

#!/bin/sh
# Use SourceGear DiffMerge as mergetool for git in cygwin.
#   git config --global mergetool.diffmerge.cmd "diffmergetool.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.diffmerge.trustExitCode false
#   git difftool -t diffmerge branch1..branch2

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching DiffMerge.exe - diffmerge-diff.sh:

set_path_vars "$1" "$2" "$3" "$4"

echo "$diffmergewinpath" -t1=FROM_VERSION -t2=TO_VERSION --caption=$caption $localwinpath $remotewinpath
"$diffmergewinpath" -t1=FROM_VERSION -t2=TO_VERSION --caption="$caption" "$localwinpath" "$remotewinpath"

diffmerge-merge.sh

#!/bin/sh
# Use SourceGear DiffMerge as mergetool for git in cygwin.
#   git config --global mergetool.diffmerge.cmd "diffmergetool.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.diffmerge.trustExitCode false
#   git mergetool -t diffmerge

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching DiffMerge.exe - diffmerge-merge.sh:

set_path_vars "$1" "$2" "$3" "$4"

"$diffmergewinpath" --merge -t1=FROM_VERSION -t2=MERGED -t3=TO_VERSION --result="$mergedwinpath" --caption="$caption" "$localwinpath" "$basewinpath" "$remotewinpath"

unix2dos "$merged"

githelperfunctions.sh

# Helper functions

convert_path () {
    file=$1

    if [ "$file" == '/dev/null' ] || [ ! -e "$file" ]
        then
           file="/tmp/nulla"
           `echo "">$file`
    fi
    echo `cygpath -w -a "$file"`
}

set_path_vars () {
    local=$1
    remote=$2
    base=$3
    merged=$4

    echo ========= Cygwin paths =======
    echo "LOCAL   :  $local"
    echo "REMOTE  :  $remote"
    echo "BASE    :  $base"
    echo "MERGED  :  $merged"

    localwinpath=$(convert_path "$local")
    remotewinpath=$(convert_path "$remote")
    basewinpath=$(convert_path "$base")
    mergedwinpath=$(convert_path "$merged")

    echo ========= Win paths =======
    echo "LOCAL   :  $localwinpath"
    echo "REMOTE  :  $remotewinpath"
    echo "BASE    :  $basewinpath"
    echo "MERGED  :  $mergedwinpath"

    caption=`basename "$merged"`
    diffmergewinpath="C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe"
    winmergewinpath="C:/Program Files/WinMerge/WinMergeU.exe"
#   diffmergewinpath=`cygpath -u C:/Program Files/SourceGear/DiffMerge/DiffMerge.exe`
#   winmergewinpath=`cygpath -u \"C:\Program Files\WinMerge\WinMergeU.exe\"`
}

winmerge-diff.sh

#!/bin/sh
# Use winmerge as mergetool for git in cygwin.
#   git config --global difftool.winmerge.cmd "winmerge-diff.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\""
#   git config --global mergetool.winmerge.trustExitCode false
#   git difftool -t winmerge branch1..branch2

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf
# Reference: http://winmerge.org/docs/manual/CommandLine.html

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching winmerge.exe - winmerge-diff.sh:

set_path_vars "$1" "$2" "$3" "$4"

"$winmergewinpath" /dl "LOCAL.$caption" /dr "TO_VERSION.$caption" "$localwinpath" "$remotewinpath"

winmerge-merge.sh

#!/bin/sh
# Use winmerge as mergetool for git in cygwin.
#   git config --global mergetool.winmerge.cmd "winmerge-merge.sh \"\$LOCAL\" \"\$REMOTE\" \"\$BASE\" \"\$MERGED\""
#   git config --global mergetool.winmerge.trustExitCode false
#   git mergetool -t diffmerge

# Reference: http://www.tldp.org/LDP/abs/abs-guide.pdf
# Reference: http://winmerge.org/docs/manual/CommandLine.html

library=githelperfunctions.sh

#[ -f $library ] && . $library
. $library

echo Launching winmerge.exe - winmerge-merge.sh:

set_path_vars "$1" "$2" "$3" "$4"

# -- use WinMergeU conflictFile
"$winmergewinpath" "$mergedwinpath"


问:
javac and scalac warnings as errors only for certain types
I know that with -Werror and -Xfatal-warnings I can make warnings as errors, but is it possible to still see all warnings in the compilation output, but only make a few of them become errors?</p>

答:
I don't think so, with scalac alone.

You could perhaps add a post-build check to your build scripts which grep the output for warnings about your critical classes and fail the build if any are found?


问:
Custom renderer for button
I am pulling my hair with this one. I am trying to create a custom renderer in using Xamarin Forms (Portable Class Library-PCL) to get the result showing in image below:

What I need:

Rounded corners

Button apperance (showing touch)

"Normal" button label in center

Image in the right corner

Smaller text in the lower left.

I have managed to create a custom renderer for a normal button but not being able to add the small text and the image. See image below

Thanks!

答:
Here is the solution for UWP for anyone interested!</p>

```<code>[assembly: ExportRenderer(typeof(RoundedButton), typeof(RoundedButtonRenderer))]
namespace Platformspecific.Buttons
{
    public class RoundedButtonRenderer : ViewRenderer<RoundedButton, Windows.UI.Xaml.Shapes.Rectangle>
    {
        Xamarin.Forms.Color originalBackground;
        private RoundedButton _control;

        protected override void OnElementChanged(ElementChangedEventArgs<RoundedButton> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                _control = e.NewElement as RoundedButton;

                originalBackground = _control.CustomBackgroundColor;

                this.PointerPressed += Control_Pressed;
                this.PointerReleased += Control_Released;
                this.PointerExited += Control_Released;

                var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
                rectangle.Width = this.Width; // 100;
                rectangle.Height = this.Height;

                rectangle.Fill = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));

                rectangle.RadiusX = _control.BorderRadius;
                rectangle.RadiusY = _control.BorderRadius;

                rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
                rectangle.StrokeThickness = _control.BorderWidth;

                this.SetNativeControl(rectangle);

            }
        }

        public static Windows.UI.Color ToMediaColor(Xamarin.Forms.Color color)
        {
            return Windows.UI.Color.FromArgb(((byte)(color.A * 255)), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
        }

        void Control_Pressed(object sender, PointerRoutedEventArgs e)
        {

            Windows.UI.Xaml.Shapes.Rectangle _rectangle = e.OriginalSource  as Windows.UI.Xaml.Shapes.Rectangle;

            var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
            rectangle.Width = this.Width;
            rectangle.Height = this.Height;
            rectangle.Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 100, 100, 100));
            rectangle.RadiusX = _control.BorderRadius;
            rectangle.RadiusY = _control.BorderRadius;
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
            rectangle.StrokeThickness = _control.BorderWidth;

            this.SetNativeControl(rectangle);

            e.Handled = false;
        }

        void Control_Released(object sender, PointerRoutedEventArgs e)
        {

            Windows.UI.Xaml.Shapes.Rectangle _rectangle = e.OriginalSource as Windows.UI.Xaml.Shapes.Rectangle;

            var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
            rectangle.Width = this.Width;
            rectangle.Height = this.Height;
            rectangle.Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(((byte)(originalBackground.A * 255)), (byte)(originalBackground.R * 255), (byte)(originalBackground.G * 255), (byte)(originalBackground.B * 255)));
            rectangle.RadiusX = _control.BorderRadius;
            rectangle.RadiusY = _control.BorderRadius;
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
            rectangle.StrokeThickness = _control.BorderWidth;

            rectangle.Fill = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));

            this.SetNativeControl(rectangle);
            e.Handled = false;
        }

    }
}
</code>```

Title: Custom renderer for button

Body:
Here is the solution for UWP for anyone interested!

[assembly: ExportRenderer(typeof(RoundedButton), typeof(RoundedButtonRenderer))]
namespace Platformspecific.Buttons
{
    public class RoundedButtonRenderer : ViewRenderer<RoundedButton, Windows.UI.Xaml.Shapes.Rectangle>
    {
        Xamarin.Forms.Color originalBackground;
        private RoundedButton _control;

        protected override void OnElementChanged(ElementChangedEventArgs<RoundedButton> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                _control = e.NewElement as RoundedButton;

                originalBackground = _control.CustomBackgroundColor;

                this.PointerPressed += Control_Pressed;
                this.PointerReleased += Control_Released;
                this.PointerExited += Control_Released;

                var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
                rectangle.Width = this.Width; // 100;
                rectangle.Height = this.Height;

                rectangle.Fill = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));

                rectangle.RadiusX = _control.BorderRadius;
                rectangle.RadiusY = _control.BorderRadius;

                rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
                rectangle.StrokeThickness = _control.BorderWidth;

                this.SetNativeControl(rectangle);

            }
        }

        public static Windows.UI.Color ToMediaColor(Xamarin.Forms.Color color)
        {
            return Windows.UI.Color.FromArgb(((byte)(color.A * 255)), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
        }

        void Control_Pressed(object sender, PointerRoutedEventArgs e)
        {

            Windows.UI.Xaml.Shapes.Rectangle _rectangle = e.OriginalSource  as Windows.UI.Xaml.Shapes.Rectangle;

            var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
            rectangle.Width = this.Width;
            rectangle.Height = this.Height;
            rectangle.Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 100, 100, 100));
            rectangle.RadiusX = _control.BorderRadius;
            rectangle.RadiusY = _control.BorderRadius;
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
            rectangle.StrokeThickness = _control.BorderWidth;

            this.SetNativeControl(rectangle);

            e.Handled = false;
        }

        void Control_Released(object sender, PointerRoutedEventArgs e)
        {

            Windows.UI.Xaml.Shapes.Rectangle _rectangle = e.OriginalSource as Windows.UI.Xaml.Shapes.Rectangle;

            var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
            rectangle.Width = this.Width;
            rectangle.Height = this.Height;
            rectangle.Fill = new SolidColorBrush(Windows.UI.Color.FromArgb(((byte)(originalBackground.A * 255)), (byte)(originalBackground.R * 255), (byte)(originalBackground.G * 255), (byte)(originalBackground.B * 255)));
            rectangle.RadiusX = _control.BorderRadius;
            rectangle.RadiusY = _control.BorderRadius;
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.OutlineColor));
            rectangle.StrokeThickness = _control.BorderWidth;

            rectangle.Fill = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));
            rectangle.Stroke = new SolidColorBrush(ToMediaColor(_control.CustomBackgroundColor));

            this.SetNativeControl(rectangle);
            e.Handled = false;
        }

    }
}


问:
MVC: Keep alive or make the initial load super fast
The goal is that I want my overall website response time to be instantaneous.

The problem is that I do no have IIS access, my website is hosted using external service and I have no control to the IIS panel.

My current approach now is having a scheduled code that keeps my website alive. The problem with this only approach is the hosting service has an algorithm to shutdown all their hosted website like every some hours.

This is why I need to implement another approach which to warm up / pre-load the website each time it runs.

How to do this when there is no access to the IIS panel?

答:
The solution requires no 3rd party sites; robots; or apps, you merely write a very simple app yourself that periodically performs a trivial web function, perhaps a REST GET.  By performing this function say every few minutes not only do you guarentee that the IIS pool won't timeout and be cold for a client, but it also has the nice effect of ensuring your website is up and running in a warm condition (JIT'd; and running) ready for a real request for your non-heartbeat website requests.

e.g.

In your website expose a REST API, say www.misspiggy.com/api/hiyaaaa that does nothing other than to return HTTP 200 OK.

By implemententing this in your ASP.NET app, any request to the above URL will cause your stopped or cold ASP.NET website to be JIT'd during:

first deployment (and even then only during a request is made to it)

after the IIS AppPool has timed out and needs to restart on demand

The client code that makes the REST request can be anything:

a console app

a Windows service

WinForms/WPF app

The console app can be triggered to fire via Windows Task Scheduler say every 5 minutes thus saving you the hastle of building in a scheduler.

My current approach now is having a scheduled code that keeps my website alive. The problem with this only approach is the hosting service has an algorithm to shutdown all their hosted website like every some hours

I suggest you set your ping period to be a matter of minutes rather than  hours.

No admin access to server required

The problem is that I do no have IIS access, my website is hosted using external service and I have no control to the IIS panel

It should be pointed out that this solution does not require you to install anything new on the server nor make any changes on the server.

Azure

It is interesting to note that Azure Application Insights has Availability Tests that though designed for testing web site availability, can be used for this exact same purpose of keeping your website alive and warm ready to go for web clients.  In fact this is what I do for my web apps.

Doing so keeps response times and latency as low as possible.


问:
How to randomly select letters in Java?
I am learning java, and my assignment now is to simulate a chess notation.

I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose random letters from A to H, I have seen random all 26 letter generators but could not work my way to understand how to generate only A to H.

My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way?

The idea is to create the class and later try and randomly generate chess notation.  At this stage, the notations do not have to make sense.

Here is what I used for int random

```<code>import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) {
    return A + rnd.nextInt(B - A + 1);
</code>```

Also, how can I make the random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more than enough.

答:
You can create a utility class for this with static method:

```<code>public final class RandomUtils {
    private static Random random = new Random();

    public static char generateRandomChar() {
        char[] chars = "ABCDEFGH".toCharArray();
        return chars[random.nextInt(chars.length)];
    }
</code>```

Title: How to randomly select letters in Java?

Body:
I am learning java, and my assignment now is to simulate a chess notation.

I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose random letters from A to H, I have seen random all 26 letter generators but could not work my way to understand how to generate only A to H.

My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way?

The idea is to create the class and later try and randomly generate chess notation.  At this stage, the notations do not have to make sense.

Here is what I used for int random

import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) {
    return A + rnd.nextInt(B - A + 1);

Also, how can I make the random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more than enough.

Body:
You can create a utility class for this with static method:

public final class RandomUtils {
    private static Random random = new Random();

    public static char generateRandomChar() {
        char[] chars = "ABCDEFGH".toCharArray();
        return chars[random.nextInt(chars.length)];
    }

ContentLicense: CC BY-SA 4.0


问:
How to check precondition to Burnikel and Ziegler division?
Burnikel and Ziegler's "RecursiveDivision" algorithm for dividing big numbers has two preconditions, one of which is "the Quotient Q must fit into n digits."  How do you know if the precondition holds without first doing the division?</p>

答:
As far as I know, Burnikel-Ziegler has a different precondition. What counts is the number of limbs (in my case, a limb is a 32 bit unsigned integer). If you divide n limbs by m limbs, the result is at most n-m+1 limbs (I assume the same calculation is true for the numbers of digits). So that could give you a hint.

But in my BigInteger code, the precondition is:

```<code>function ShouldUseBurnikelZiegler(LSize, RSize: Integer): Boolean;
begin
  // http://mail.openjdk.java.net/pipermail/core-libs-dev/2013-November/023493.html
  Result := (RSize >= BigInteger.BurnikelZieglerThreshold) and
            ((LSize - RSize) >= BigInteger.BurnikelZieglerOffsetThreshold);
end;
</code>```

LSize is the size of the left operand (dividend) and RSize the size of the right operand (divisor) in limbs. The thresholds for my code are:

```<code>const
  BurnikelZieglerThreshold       =   91;
  BurnikelZieglerOffsetThreshold =    5;
</code>```

You should (experimentally) find the thresholds for your own code.

In my code, I already gave the link where I got that.

I am aware of the fact that not everyone is familiar with Pascal (or Object-Pascal), but I think the above piece of code is readable enough to get the idea.

Body:
As far as I know, Burnikel-Ziegler has a different precondition. What counts is the number of limbs (in my case, a limb is a 32 bit unsigned integer). If you divide n limbs by m limbs, the result is at most n-m+1 limbs (I assume the same calculation is true for the numbers of digits). So that could give you a hint.

But in my BigInteger code, the precondition is:

function ShouldUseBurnikelZiegler(LSize, RSize: Integer): Boolean;
begin
  // http://mail.openjdk.java.net/pipermail/core-libs-dev/2013-November/023493.html
  Result := (RSize >= BigInteger.BurnikelZieglerThreshold) and
            ((LSize - RSize) >= BigInteger.BurnikelZieglerOffsetThreshold);
end;

LSize is the size of the left operand (dividend) and RSize the size of the right operand (divisor) in limbs. The thresholds for my code are:

const
  BurnikelZieglerThreshold       =   91;
  BurnikelZieglerOffsetThreshold =    5;

You should (experimentally) find the thresholds for your own code.

In my code, I already gave the link where I got that.

I am aware of the fact that not everyone is familiar with Pascal (or Object-Pascal), but I think the above piece of code is readable enough to get the idea.


问:
How would I call only one variable from a function that contains multiple variables?
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

```<code>import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()
</code>```

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

答:
Store the return value in a variable.</p>

```<code>import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  return selectedWord

def guessWord(selectedWord):
  selectedWord = wordSelection()
  print selectedWord
</code>```

Body:
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

Body:
Store the return value in a variable.

import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  return selectedWord

def guessWord(selectedWord):
  selectedWord = wordSelection()
  print selectedWord


问:
How to delete a file while the application is running
I have developed a C# application, in the application the users choose a photo for each record. However the user should also be able to change the pre-selected photo with a newer one. When the user changes the photo the application first deletes the old photo from the application directory then copies the new photo, but when it does that the application gives an exception because the file is used by the application so it cannot be deleted while the application is running. Does any one have a clue how to sort this out? I appreciate your help

This is the exception

The process cannot access the file
  'D:\My
  Projects\Hawkar'sProject\Software\Application\bin\Debug\Photos\John
  Smith.png' because it is being used by
  another process.

```<code> //defining a string where contains the file source path
            string fileSource = Open.FileName;

            //defining a string where it contains the file name
            string fileName =  personNameTextBox.Text + ".png" ;

            //defining a string which specifies the directory of the destination file
            string fileDest = dir + @"\Photos\" + fileName;

            if (File.Exists(fileDest))
            {

               File.Delete(fileDest);
               //this is a picturebox for showing the images
               pbxPersonal.Image = Image.FromFile(dir + @"\Photos\" + "No Image.gif");
               File.Copy(fileSource, fileDest);
            }
            else
            {
                File.Copy(fileSource, fileDest);

            }
            imageIDTextBox.Text = fileDest;
</code>```

答: Thanks a lot for your help and sorry for the mistake in the code I just saw it, my original code is just like as you have written but I don't know maybe when I posted accidentally I've put like this. when the application runs there is a picturebox which the image of each record is shown, that is why the application is giving an exception when I want to change the picture because it has been used once by the picturebox , however I've also tried to load another picture to the picture box before deleting the original one but still the same. I've modified the above could if you want to examine it</p>

Body:
I have developed a C# application, in the application the users choose a photo for each record. However the user should also be able to change the pre-selected photo with a newer one. When the user changes the photo the application first deletes the old photo from the application directory then copies the new photo, but when it does that the application gives an exception because the file is used by the application so it cannot be deleted while the application is running. Does any one have a clue how to sort this out? I appreciate your help

This is the exception

The process cannot access the file
  'D:\My
  Projects\Hawkar'sProject\Software\Application\bin\Debug\Photos\John
  Smith.png' because it is being used by
  another process.

 //defining a string where contains the file source path
            string fileSource = Open.FileName;

            //defining a string where it contains the file name
            string fileName =  personNameTextBox.Text + ".png" ;

            //defining a string which specifies the directory of the destination file
            string fileDest = dir + @"\Photos\" + fileName;

            if (File.Exists(fileDest))
            {

               File.Delete(fileDest);
               //this is a picturebox for showing the images
               pbxPersonal.Image = Image.FromFile(dir + @"\Photos\" + "No Image.gif");
               File.Copy(fileSource, fileDest);
            }
            else
            {
                File.Copy(fileSource, fileDest);

            }
            imageIDTextBox.Text = fileDest;


问:
assert, only once, if variables by vars_prompt are empty
I'm asking the user for input and basically I want to check that the value of the variable (asked to the user by vars_prompt) is not empty.

Aborting the playbook when the variable is "" is not a problem and easily done.
However I'm annoyed that this step is ran on a ton of machines while I just want to check it once (I don't see the need to go to a remote machine) and when it's not set I just want the playbook to stop as we know when it's empty the first time it still is the 100s of times afterwards.

Is there a clean way of doing this? I've been experimenting with the assert module but no luck.

Thanks in advance!

答:
run_once is your friend:

```<code>---
- hosts: mygroup
  gather_facts: no
  vars_prompt:
    - name: myvar
      prompt: enter myvar
      default: bad_value
  tasks:
    # assert before gathering facts
    - assert:
        that: myvar != 'bad_value'
      run_once: yes
    # gather facts manually with setup
    - setup:
    - debug:
        msg: do the job
</code>```

Also you can disable automatic facts gathering to avoid connections to all your hosts before assertion is done, and collect them manually with setup.

Body:
run_once is your friend:

---
- hosts: mygroup
  gather_facts: no
  vars_prompt:
    - name: myvar
      prompt: enter myvar
      default: bad_value
  tasks:
    # assert before gathering facts
    - assert:
        that: myvar != 'bad_value'
      run_once: yes
    # gather facts manually with setup
    - setup:
    - debug:
        msg: do the job

Also you can disable automatic facts gathering to avoid connections to all your hosts before assertion is done, and collect them manually with setup.


问:
Python, want logging with log rotation and compression
Can anyone suggest a way in python to do logging with:

log rotation every day

compression of logs when they're rotated

optional - delete oldest log file to preserve X MB of free space

optional - sftp log files to server

Thanks for any responses,
Fred

答:
I think that the best option will be to use current implementation of TimedRotatingFileHandler and after renaming log file to the rotated version just compress it:

```<code>import zipfile
import os
from logging.handlers import TimedRotatingFileHandler

class TimedCompressedRotatingFileHandler(TimedRotatingFileHandler):
    """
    Extended version of TimedRotatingFileHandler that compress logs on rollover.
    """
    def find_last_rotated_file(self):
        dir_name, base_name = os.path.split(self.baseFilename)
        file_names = os.listdir(dir_name)
        result = []
        prefix = '{}.20'.format(base_name)  # we want to find a rotated file with eg filename.2017-12-12... name
        for file_name in file_names:
            if file_name.startswith(prefix) and not file_name.endswith('.zip'):
                result.append(file_name)
        result.sort()
        return result[0]

    def doRollover(self):
        super(TimedCompressedRotatingFileHandler, self).doRollover()

        dfn = self.find_last_rotated_file()
        dfn_zipped = '{}.zip'.format(dfn)
        if os.path.exists(dfn_zipped):
            os.remove(dfn_zipped)
        with zipfile.ZipFile(dfn_zipped, 'w') as f:
            f.write(dfn, dfn_zipped, zipfile.ZIP_DEFLATED)
        os.remove(dfn)
</code>```

Body:
I think that the best option will be to use current implementation of TimedRotatingFileHandler and after renaming log file to the rotated version just compress it:

import zipfile
import os
from logging.handlers import TimedRotatingFileHandler

class TimedCompressedRotatingFileHandler(TimedRotatingFileHandler):
    """
    Extended version of TimedRotatingFileHandler that compress logs on rollover.
    """
    def find_last_rotated_file(self):
        dir_name, base_name = os.path.split(self.baseFilename)
        file_names = os.listdir(dir_name)
        result = []
        prefix = '{}.20'.format(base_name)  # we want to find a rotated file with eg filename.2017-12-12... name
        for file_name in file_names:
            if file_name.startswith(prefix) and not file_name.endswith('.zip'):
                result.append(file_name)
        result.sort()
        return result[0]

    def doRollover(self):
        super(TimedCompressedRotatingFileHandler, self).doRollover()

        dfn = self.find_last_rotated_file()
        dfn_zipped = '{}.zip'.format(dfn)
        if os.path.exists(dfn_zipped):
            os.remove(dfn_zipped)
        with zipfile.ZipFile(dfn_zipped, 'w') as f:
            f.write(dfn, dfn_zipped, zipfile.ZIP_DEFLATED)
        os.remove(dfn)


问:
Variable as argument name
Is it possible to use the value of a variable as the name of an argument, something like this (but not exactly this, as it doesn't work):

```<code>$processData = Split-Path $processData -($variable.split)
</code>```

$variable is actually some XML, and the split property can either be 'parent' or 'leaf'. I can use this approach, and it works fine:

```<code>switch ($variable.split) {
    parent {
        $processData = Split-Path $processData -Parent
    }
    leaf {
        $processData = Split-Path $processData -Leaf
    }
}
</code>```

But using the variable directly would be more elegant.

答:
Splatting should do what you want:

```<code>$params = @{
    Path = $processData
    $variable.split = $true
}
$processData = Split-Path @params
</code>```

Not really much less code than a switch statement, though:

```<code>$processData = switch ($variable.split) {
    parent { Split-Path $processData -Parent }
    leaf   { Split-Path $processData -Leaf }
}
</code>```

Title: Variable as argument name

Body:
Is it possible to use the value of a variable as the name of an argument, something like this (but not exactly this, as it doesn't work):

$processData = Split-Path $processData -($variable.split)

$variable is actually some XML, and the split property can either be 'parent' or 'leaf'. I can use this approach, and it works fine:

switch ($variable.split) {
    parent {
        $processData = Split-Path $processData -Parent
    }
    leaf {
        $processData = Split-Path $processData -Leaf
    }
}

But using the variable directly would be more elegant.

Body:
Splatting should do what you want:

$params = @{
    Path = $processData
    $variable.split = $true
}
$processData = Split-Path @params

Not really much less code than a switch statement, though:

$processData = switch ($variable.split) {
    parent { Split-Path $processData -Parent }
    leaf   { Split-Path $processData -Leaf }
}


问:
Comparing two NSDates and ignoring the time component
What is the most efficient/recommended way of comparing two NSDates?  I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day.  This seems long winded and I feel like I am missing something obvious.

The code I am trying to fix is:

```<code>if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}
</code>```

where key and todaysDate are NSDate objects and todaysDate is creating using:

```<code>NSDate *todaysDate = [[NSDate alloc] init];
</code>```

Regards

Dave

答:
With Swift 3, according to your needs, you can choose one of the two following patterns in order to solve your problem.

#1. Using compare(_:to:toGranularity:) method

Calendar has a method called compare(_:to:toGranularity:). compare(_:to:toGranularity:) has the following declaration:

```<code>func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult
</code>```

Compares the given dates down to the given component, reporting them orderedSame if they are the same in the given component and all larger components, otherwise either orderedAscending or orderedDescending.

The Playground code below shows hot to use it:

```<code>import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let comparisonResult = calendar.compare(date1, to: date2, toGranularity: .day)
    switch comparisonResult {
    case ComparisonResult.orderedSame:
        print("Same day")
    default:
        print("Not the same day")
    }
    // Prints: "Not the same day"
}

/* Compare date1 and date3 */
do {
    let comparisonResult = calendar.compare(date1, to: date3, toGranularity: .day)
    if case ComparisonResult.orderedSame = comparisonResult {
        print("Same day")
    } else {
        print("Not the same day")
    }
    // Prints: "Same day"
}
</code>```

#2. Using dateComponents(_:from:to:)

Calendar has a method called dateComponents(_:from:to:). dateComponents(_:from:to:) has the following declaration:

```<code>func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
</code>```

Returns the difference between two dates.

The Playground code below shows hot to use it:

```<code>import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date2)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 is before date1
}

/* Compare date1 and date3 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date3)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 equals date1
}
</code>```

Body:
What is the most efficient/recommended way of comparing two NSDates?  I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day.  This seems long winded and I feel like I am missing something obvious.

The code I am trying to fix is:

if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}

where key and todaysDate are NSDate objects and todaysDate is creating using:

NSDate *todaysDate = [[NSDate alloc] init];

Regards

Dave

Body:
With Swift 3, according to your needs, you can choose one of the two following patterns in order to solve your problem.

#1. Using compare(_:to:toGranularity:) method

Calendar has a method called compare(_:to:toGranularity:). compare(_:to:toGranularity:) has the following declaration:

func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult

Compares the given dates down to the given component, reporting them orderedSame if they are the same in the given component and all larger components, otherwise either orderedAscending or orderedDescending.

The Playground code below shows hot to use it:

import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let comparisonResult = calendar.compare(date1, to: date2, toGranularity: .day)
    switch comparisonResult {
    case ComparisonResult.orderedSame:
        print("Same day")
    default:
        print("Not the same day")
    }
    // Prints: "Not the same day"
}

/* Compare date1 and date3 */
do {
    let comparisonResult = calendar.compare(date1, to: date3, toGranularity: .day)
    if case ComparisonResult.orderedSame = comparisonResult {
        print("Same day")
    } else {
        print("Not the same day")
    }
    // Prints: "Same day"
}

#2. Using dateComponents(_:from:to:)

Calendar has a method called dateComponents(_:from:to:). dateComponents(_:from:to:) has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents

Returns the difference between two dates.

The Playground code below shows hot to use it:

import Foundation

let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"

/* Compare date1 and date2 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date2)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 is before date1
}

/* Compare date1 and date3 */
do {
    let dateComponents = calendar.dateComponents([.day], from: date1, to: date3)
    switch dateComponents.day {
    case let value? where value < 0:
        print("date2 is before date1")
    case let value? where value > 0:
        print("date2 is after date1")
    case let value? where value == 0:
        print("date2 equals date1")
    default:
        print("Could not compare dates")
    }
    // Prints: date2 equals date1
}


问:
Fetch last three orders from a table
Consider a table with the following columns:

Customer Email ID

Payment Method (COD/ Netbanking/ CreditCard/ DebitCard)

Order ID

Order Creation Date

Order Status(Success/ Failed/ Cancelled)

How do I fetch the last three successful orders past 3 months for each customer from these table in SQL along with the relevant details?

答:
I Hope this helps </p>

```<code>SELECT *
FROM TABLENAME
WHERE OrderStatus='Success'
ORDER BY OrderCreationDate DESC
LIMIT 3;
</code>```

Title: Fetch last three orders from a table

Body:
I Hope this helps

SELECT *
FROM TABLENAME
WHERE OrderStatus='Success'
ORDER BY OrderCreationDate DESC
LIMIT 3;


问:
Dynamically styling pseudo-elements using jQuery or Javascript
I need to change the margin-top value of p::before dynamically on each image click.
Neither of these questions 1 / 2 / 3 / 4 nor this tutorial worked for me since I am changing the margin-top value not content or colors.

I can't use attr() because it's not supported for non-string values according to this.
Creating stylesheet or adding scripting the the header isn't a good idea since I can't reach and modify it again so it's creating tens of style tags and rules and it's messing up with my styling.

How can I achieve this?

Thanks in advance

```<code>p::after {
    top: auto;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-bottom-color: #f9e8a2;
    border-width: 15px;
    left: 50%;
    margin: 28px 0 0 -15px;
}
</code>```

答:
May I suggest doing like this, where you dynamically create a style element (with a unique id so you can access it over and over) and just update a rule repeatedly

Usage

```<code>loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');
</code>```

Script

```<code>function loadStyle(css) {
  var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
  style.id = 'lastinbody';
  style.type = 'text/css';
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  document.querySelector('body').appendChild(style);
}
</code>```

At this post of mine is a few more versions (which might be consider as a possible duplicate)

Body:
I need to change the margin-top value of p::before dynamically on each image click.
Neither of these questions 1 / 2 / 3 / 4 nor this tutorial worked for me since I am changing the margin-top value not content or colors.

I can't use attr() because it's not supported for non-string values according to this.
Creating stylesheet or adding scripting the the header isn't a good idea since I can't reach and modify it again so it's creating tens of style tags and rules and it's messing up with my styling.

How can I achieve this?

Thanks in advance

p::after {
    top: auto;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-bottom-color: #f9e8a2;
    border-width: 15px;
    left: 50%;
    margin: 28px 0 0 -15px;
}

Body:
May I suggest doing like this, where you dynamically create a style element (with a unique id so you can access it over and over) and just update a rule repeatedly

Usage

loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');

Script

function loadStyle(css) {
  var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
  style.id = 'lastinbody';
  style.type = 'text/css';
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  document.querySelector('body').appendChild(style);
}

At this post of mine is a few more versions (which might be consider as a possible duplicate)