问:
Multiplying big numbers in C++ - code with mistakes? How to improve it?
We got an assignment to write a function multiplying big numbers, which prints the result on screen.

Here is my code so far:

```<code>void mnozenie(string a, string b)
{
    if(a=="0"||b=="0")
        cout<<0;
  else
  {

    bool minus=false;

    if((a[0]=='-'&&b[0]!='-')||(b[0]=='-'&&a[0]!='-'))
        minus=true;

    if(a[0]=='-')
        a.erase(a.begin());

    if(b[0]=='-')
        b.erase(b.begin());

    if(a.size()<b.size())
        swap(a,b);

    vector<int> C;
    for(int i=0; i<(int)a.size()+(int)b.size(); i++)
        C.push_back(0);

    for(int i=(int)b.size()-1; i>=0; i--)
    {
        for(int j=(int)a.size()-1; j>=0; j--)
        {
            C[i+j+1]+=((a[j]-'0')*(b[i]-'0'));
            int k=i+j+1;
            while(C[k]>9&&k>0)
            {
               C[k-1]+=C[k]/10;
               C[k]=C[k]%10;
               k--;
            }

        }

    }

    while(C[0]==0)
        C.erase(C.begin());

    if(minus)
        cout<<"-";

    for(int i=0; i<(int)C.size(); i++)
        cout<<C[i];

    cout<<endl;
   }

}
</code>```

I haven't found a case when it's incorrect, but when I try to submit it I get ANSWER mistake. So probably there is such a case.

答:
Not sure it's the only problem but is a problem...

When you write

```<code>  if ( a[0] = '-')
     a.erase(a.begin());

  if ( b[0] = '-')
     b.erase(b.begin());
</code>```

you, in the tests, assign '-' to a[0] and b[0].

I presume your intention was to test if a[0] is '-' (and the same with b[0]

So I suggest to modify in

```<code>  // .......vv
  if ( a[0] == '-')
     a.erase(a.begin());

  // .......vv
  if ( b[0] == '-')
     b.erase(b.begin());
</code>```

Body:
We got an assignment to write a function multiplying big numbers, which prints the result on screen.

Here is my code so far:

void mnozenie(string a, string b)
{
    if(a=="0"||b=="0")
        cout<<0;
  else
  {

    bool minus=false;

    if((a[0]=='-'&&b[0]!='-')||(b[0]=='-'&&a[0]!='-'))
        minus=true;

    if(a[0]=='-')
        a.erase(a.begin());

    if(b[0]=='-')
        b.erase(b.begin());

    if(a.size()<b.size())
        swap(a,b);

    vector<int> C;
    for(int i=0; i<(int)a.size()+(int)b.size(); i++)
        C.push_back(0);

    for(int i=(int)b.size()-1; i>=0; i--)
    {
        for(int j=(int)a.size()-1; j>=0; j--)
        {
            C[i+j+1]+=((a[j]-'0')*(b[i]-'0'));
            int k=i+j+1;
            while(C[k]>9&&k>0)
            {
               C[k-1]+=C[k]/10;
               C[k]=C[k]%10;
               k--;
            }

        }

    }

    while(C[0]==0)
        C.erase(C.begin());

    if(minus)
        cout<<"-";

    for(int i=0; i<(int)C.size(); i++)
        cout<<C[i];

    cout<<endl;
   }

}

I haven't found a case when it's incorrect, but when I try to submit it I get ANSWER mistake. So probably there is such a case.

Body:
Not sure it's the only problem but is a problem...

When you write

  if ( a[0] = '-')
     a.erase(a.begin());

  if ( b[0] = '-')
     b.erase(b.begin());

you, in the tests, assign '-' to a[0] and b[0].

I presume your intention was to test if a[0] is '-' (and the same with b[0]

So I suggest to modify in

  // .......vv
  if ( a[0] == '-')
     a.erase(a.begin());

  // .......vv
  if ( b[0] == '-')
     b.erase(b.begin());


来源: stackexchange

问:
Swift - Cannot convert value of type 'UnsafePointer<Any>' to expected argument type 'UnsafePointer<_>'
I am trying to use CommonCrypto (with the help of https://github.com/sergejp/CommonCrypto) for the first time with swift. Here is my code:

```<code>UnsafeRawPointer(ivData!.withUnsafeBytes
{(pointer) -> UnsafePointer<Any> in
    let ivBuffer = pointer
})
</code>```

The error is:

Cannot convert value of type 'UnsafePointer' to expected argument
  type 'UnsafePointer<_>'

What does the <_> signify? What do I need to do? Thanks.

答:
It's pointer that it is complaining about.  You need to cast it.  Here's an example usage, part of creating an MD5 hash:

```<code>    var rawBytes = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
    let _ = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
        CC_MD5(bytes, CC_LONG(data.count), &rawBytes)
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use CommonCrypto (with the help of https://github.com/sergejp/CommonCrypto) for the first time with swift. Here is my code:

UnsafeRawPointer(ivData!.withUnsafeBytes
{(pointer) -> UnsafePointer<Any> in
    let ivBuffer = pointer
})

The error is:

Cannot convert value of type 'UnsafePointer' to expected argument
  type 'UnsafePointer<_>'

What does the <_> signify? What do I need to do? Thanks.

Body:
It's pointer that it is complaining about.  You need to cast it.  Here's an example usage, part of creating an MD5 hash:

    var rawBytes = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
    let _ = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
        CC_MD5(bytes, CC_LONG(data.count), &rawBytes)
    }


问:
linq data context abstraction
I'm finding myself writing this line for every query:

```<code>using ( MyDataModel thisDataContext = new MyDataModel() )
{
  linq query
}
</code>```

Is there a better way to declare a data context?

Thanks.

答:
you can create a DataService class that represent your DataContext
e.g.:

```<code> public  class BaseDataService:IDisposable
    {
       protected MyDataModel thisDataContext = null;
       public BaseDataService(string connection)
       {
           this.thisDataContext = new MyDataModel (connection);
       }

       public void Dispose()
       {
           this.thisDataContext.Connection.Close();
           this.thisDataContext.Dispose();
       }

    }
</code>```

then create methods that satisfy your needs
e.g.:

```<code>public class YourEntityDataService:BaseDataService
    {

        public YourEntityDataService(string connection):base(connection)
        {

        }

        public YourEntity GetYourEntity()
        {
//LINQ CODE
        }

        public void SaveYourEntity (YourEntity entityToSave)
        {
//LINQ CODE
        }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: linq data context abstraction

Body:
I'm finding myself writing this line for every query:

using ( MyDataModel thisDataContext = new MyDataModel() )
{
  linq query
}

Is there a better way to declare a data context?

Thanks.

Body:
you can create a DataService class that represent your DataContext
e.g.:

 public  class BaseDataService:IDisposable
    {
       protected MyDataModel thisDataContext = null;
       public BaseDataService(string connection)
       {
           this.thisDataContext = new MyDataModel (connection);
       }

       public void Dispose()
       {
           this.thisDataContext.Connection.Close();
           this.thisDataContext.Dispose();
       }

    }

then create methods that satisfy your needs
e.g.:

public class YourEntityDataService:BaseDataService
    {

        public YourEntityDataService(string connection):base(connection)
        {

        }

        public YourEntity GetYourEntity()
        {
//LINQ CODE
        }

        public void SaveYourEntity (YourEntity entityToSave)
        {
//LINQ CODE
        }
}


问:
I only want to remove quotes from the first line
I am trying to only remove the quotes from the first line of my report.  The rest of the report, quotes are fine.  I tried this, but it deleted everything after the first line:

```<code>(gc daily_report_yyyymmdd.csv -First 1) |
    % {$_ -replace '"', ""} |
    Out-File daily_report_yyyymmdd.csv -Fo -En Ascii
</code>```

Header

```<code>ORDER_ID,"PRIORITY_STATUS","PRODUCT_CLASS","PLAN_NAME","CONTRACT_ID","GROUP_NAME","CREATION_DATE","TECH_RESPONSE_DATE","RPH_RESPONSE_DATE","CLOSE_DATE","MEMBER_ID","FIRST_NAME","LAST_NAME","DRUGNAME","PHYSICIAN_FIRST_NAME","PHYSICIAN_LAST_NAME","NPI","RPH First Name","RPH Last Name","CSR First Name","CSR Last Name","QA First Name","QA Last Name","OutBound Call Notes","RFI Sent","COV_DETERM_TYPE","ORIGIN_OF_REQUEST","FORMULARYSTATUS","BENEFIT","ORDER_STATUS","RATIONALEBRIEFDESC","EARLY_CLOSE_CODE","TAT from Order Create (Hours)","TAT from Fax Receipt (Hours)"
</code>```

First Line

```<code>2727770,"Standard","TESTMAI","TESTMAI","PIZZA ","DOUGH","2017-11-29 18:11:18.816000","2017-12-01 08:53:30.000000","2017-11-07 09:15:32.000000","2017-12-01 08:53:30.665000","123456789","TEST","USER","Bystolic 10 mg tablet","TEST","PEOPLE","1234657984","TESTER","TEST","TESTER","TEST","TESTER","TEST","","N","","Provider Fax","On Formulary","Pharmacy Benefit","Early Close","The medication requested is a non-preferred medication.  The member must try/fail at least one preferred agent for a period of 30 days or more before approval of a non-preferred agent. The preferred a","ELCL","38","38"
</code>```

答:
I wound up converting the DOS to UNIX in PowerShell and it took care of my CR issue:</p>

```<code>$csvdata = [io.file]::ReadAllText('in.csv') | % {$_ -replace "`r",""}
[io.file]::WriteAllLines('out.csv', $csvdata)
</code>```

Body:
I am trying to only remove the quotes from the first line of my report.  The rest of the report, quotes are fine.  I tried this, but it deleted everything after the first line:

(gc daily_report_yyyymmdd.csv -First 1) |
    % {$_ -replace '"', ""} |
    Out-File daily_report_yyyymmdd.csv -Fo -En Ascii

Header

ORDER_ID,"PRIORITY_STATUS","PRODUCT_CLASS","PLAN_NAME","CONTRACT_ID","GROUP_NAME","CREATION_DATE","TECH_RESPONSE_DATE","RPH_RESPONSE_DATE","CLOSE_DATE","MEMBER_ID","FIRST_NAME","LAST_NAME","DRUGNAME","PHYSICIAN_FIRST_NAME","PHYSICIAN_LAST_NAME","NPI","RPH First Name","RPH Last Name","CSR First Name","CSR Last Name","QA First Name","QA Last Name","OutBound Call Notes","RFI Sent","COV_DETERM_TYPE","ORIGIN_OF_REQUEST","FORMULARYSTATUS","BENEFIT","ORDER_STATUS","RATIONALEBRIEFDESC","EARLY_CLOSE_CODE","TAT from Order Create (Hours)","TAT from Fax Receipt (Hours)"

First Line

2727770,"Standard","TESTMAI","TESTMAI","PIZZA ","DOUGH","2017-11-29 18:11:18.816000","2017-12-01 08:53:30.000000","2017-11-07 09:15:32.000000","2017-12-01 08:53:30.665000","123456789","TEST","USER","Bystolic 10 mg tablet","TEST","PEOPLE","1234657984","TESTER","TEST","TESTER","TEST","TESTER","TEST","","N","","Provider Fax","On Formulary","Pharmacy Benefit","Early Close","The medication requested is a non-preferred medication.  The member must try/fail at least one preferred agent for a period of 30 days or more before approval of a non-preferred agent. The preferred a","ELCL","38","38"

Body:
I wound up converting the DOS to UNIX in PowerShell and it took care of my CR issue:

$csvdata = [io.file]::ReadAllText('in.csv') | % {$_ -replace "`r",""}
[io.file]::WriteAllLines('out.csv', $csvdata)


问:
Select first empty cell in range
So my very basic VBA skills limit my programming codes. I want to search within a Range("A14:A23") the first empty cell in order to fill in a value. I have to do this within various ranges in A, so I can't just use the lastcell in column code. Can anyone help me?</p>

答:
In relation to Scott Craner's comment, you can use .Select (which in most cases is advised against).

Please see How to avoid .Select

```<code>Sub FindEmptyCell()

   ActiveSheet.Range("A1:A10").Find("").Select

End Sub
</code>```

This will select the first empty cell

Title: Select first empty cell in range

Body:
In relation to Scott Craner's comment, you can use .Select (which in most cases is advised against).

Please see How to avoid .Select

Sub FindEmptyCell()

   ActiveSheet.Range("A1:A10").Find("").Select

End Sub

This will select the first empty cell


问:
Drag and Drop with Protractor in AngularJS
I appreciate there's quite a bit of stuff already been said about automating drag and drop as part of E2E testing. However after many, many hours of fiddling around, I cannot get any of the methods described to work...that is using Functions, coordinates etc etc. Oddly enough, console.log maintains the tests have passed, but the screenshots clearly show nothing has happened.
Screenshots shows a portion of the application

The user selects a paper and drags onto the image. As the drag 'starts' the grey overlay on the image clears and the paper is rendered on the room.

The code snippet shows one of the more simple ideas I've tried and I would be very pleased to receive any help going!

```<code>const JS_HTML5_DND = 'function e(e,t,n,i){var r=a.createEvent("DragEvent");r.initMouseEvent(t,!0,!0,o,0,0,0,c,g,!1,!1,!1,!1,0,null),Object.defineProperty(r,"dataTransfer",{get:function(){return d}}),e.dispatchEvent(r),o.setTimeout(i,n)}var t=arguments[0],n=arguments[1],i=arguments[2]||0,r=arguments[3]||0;if(!t.draggable)throw new Error("Source element is not draggable.");var a=t.ownerDocument,o=a.defaultView,l=t.getBoundingClientRect(),u=n?n.getBoundingClientRect():l,c=l.left+(l.width>>1),g=l.top+(l.height>>1),s=u.left+(u.width>>1)+i,f=u.top+(u.height>>1)+r,d=Object.create(Object.prototype,{_items:{value:{}},effectAllowed:{value:"all",writable:!0},dropEffect:{value:"move",writable:!0},files:{get:function(){return this._items.Files}},types:{get:function(){return Object.keys(this._items)}},setData:{value:function(e,t){this._items[e]=t}},getData:{value:function(e){return this._items[e]}},clearData:{value:function(e){delete this._items[e]}},setDragImage:{value:function(e){}}});if(n=a.elementFromPoint(s,f),!n)throw new Error("The target element is not interactable and need to be scrolled into the view.");u=n.getBoundingClientRect(),e(t,"dragstart",101,function(){var i=n.getBoundingClientRect();c=i.left+s-u.left,g=i.top+f-u.top,e(n,"dragenter",1,function(){e(n,"dragover",101,function(){n=a.elementFromPoint(c,g),e(n,"drop",1,function(){e(t,"dragend",1,callback)})})})})';

describe('Drag and Drop Test', function() {
it('should drag', function () {

    var e1 = element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img'));
    var e2 = element(by.css('.db-project-designer'));

    element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img')).click();
    //element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[1]/div/div/digitalbridge-project/div/digitalbridge-project-designer/canvas')).click();

    browser.driver.actions().dragAndDrop(e1.getWebElement(),e2.getWebElement()).perform();

    browser.sleep(2000);
});
});
</code>```

The constant is showing an error 'const' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz). (W104) - I do have ES6 installed in Node_Modules.

I inserted the click line to see if pre-selecting the item made any difference...it didn't!

Thank you

David

答:
```<code>module.exports = function simulateDragAndDrop(sourceNode, destinationNode) {
    const EVENT_TYPES = {
        DRAG_END: 'dragend',
        DRAG_START: 'dragstart',
        DROP: 'drop'
    };

    function createCustomEvent(type) {
        const event = new CustomEvent('CustomEvent');
        event.initCustomEvent(type, true, true, null);
        event.dataTransfer = {
            data: {
            },
            setData: function(type, val) {
                this.data[type] = val;
            },
            getData: function(type) {
                return this.data[type];
            }
        };
        return event;
    }

    function dispatchEvent(node, type, event) {
        if (node.dispatchEvent) {
            return node.dispatchEvent(event);
        }
        if (node.fireEvent) {
            return node.fireEvent('on' + type, event);
        }
    }

    const event = createCustomEvent(EVENT_TYPES.DRAG_START);
    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event);

    const dropEvent = createCustomEvent(EVENT_TYPES.DROP);
    dropEvent.dataTransfer = event.dataTransfer;
    dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent);

    const dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END);
    dragEndEvent.dataTransfer = event.dataTransfer;
    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent);
}
</code>```

You can call it from you code like this

```<code>browser.executeScript(dragAndDrop, element, targetArea);
</code>```

Body:
I appreciate there's quite a bit of stuff already been said about automating drag and drop as part of E2E testing. However after many, many hours of fiddling around, I cannot get any of the methods described to work...that is using Functions, coordinates etc etc. Oddly enough, console.log maintains the tests have passed, but the screenshots clearly show nothing has happened.
Screenshots shows a portion of the application

The user selects a paper and drags onto the image. As the drag 'starts' the grey overlay on the image clears and the paper is rendered on the room.

The code snippet shows one of the more simple ideas I've tried and I would be very pleased to receive any help going!

const JS_HTML5_DND = 'function e(e,t,n,i){var r=a.createEvent("DragEvent");r.initMouseEvent(t,!0,!0,o,0,0,0,c,g,!1,!1,!1,!1,0,null),Object.defineProperty(r,"dataTransfer",{get:function(){return d}}),e.dispatchEvent(r),o.setTimeout(i,n)}var t=arguments[0],n=arguments[1],i=arguments[2]||0,r=arguments[3]||0;if(!t.draggable)throw new Error("Source element is not draggable.");var a=t.ownerDocument,o=a.defaultView,l=t.getBoundingClientRect(),u=n?n.getBoundingClientRect():l,c=l.left+(l.width>>1),g=l.top+(l.height>>1),s=u.left+(u.width>>1)+i,f=u.top+(u.height>>1)+r,d=Object.create(Object.prototype,{_items:{value:{}},effectAllowed:{value:"all",writable:!0},dropEffect:{value:"move",writable:!0},files:{get:function(){return this._items.Files}},types:{get:function(){return Object.keys(this._items)}},setData:{value:function(e,t){this._items[e]=t}},getData:{value:function(e){return this._items[e]}},clearData:{value:function(e){delete this._items[e]}},setDragImage:{value:function(e){}}});if(n=a.elementFromPoint(s,f),!n)throw new Error("The target element is not interactable and need to be scrolled into the view.");u=n.getBoundingClientRect(),e(t,"dragstart",101,function(){var i=n.getBoundingClientRect();c=i.left+s-u.left,g=i.top+f-u.top,e(n,"dragenter",1,function(){e(n,"dragover",101,function(){n=a.elementFromPoint(c,g),e(n,"drop",1,function(){e(t,"dragend",1,callback)})})})})';

describe('Drag and Drop Test', function() {
it('should drag', function () {

    var e1 = element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img'));
    var e2 = element(by.css('.db-project-designer'));

    element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img')).click();
    //element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[1]/div/div/digitalbridge-project/div/digitalbridge-project-designer/canvas')).click();

    browser.driver.actions().dragAndDrop(e1.getWebElement(),e2.getWebElement()).perform();

    browser.sleep(2000);
});
});

The constant is showing an error 'const' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz). (W104) - I do have ES6 installed in Node_Modules.

I inserted the click line to see if pre-selecting the item made any difference...it didn't!

Thank you

David

Body:
module.exports = function simulateDragAndDrop(sourceNode, destinationNode) {
    const EVENT_TYPES = {
        DRAG_END: 'dragend',
        DRAG_START: 'dragstart',
        DROP: 'drop'
    };

    function createCustomEvent(type) {
        const event = new CustomEvent('CustomEvent');
        event.initCustomEvent(type, true, true, null);
        event.dataTransfer = {
            data: {
            },
            setData: function(type, val) {
                this.data[type] = val;
            },
            getData: function(type) {
                return this.data[type];
            }
        };
        return event;
    }

    function dispatchEvent(node, type, event) {
        if (node.dispatchEvent) {
            return node.dispatchEvent(event);
        }
        if (node.fireEvent) {
            return node.fireEvent('on' + type, event);
        }
    }

    const event = createCustomEvent(EVENT_TYPES.DRAG_START);
    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event);

    const dropEvent = createCustomEvent(EVENT_TYPES.DROP);
    dropEvent.dataTransfer = event.dataTransfer;
    dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent);

    const dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END);
    dragEndEvent.dataTransfer = event.dataTransfer;
    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent);
}

You can call it from you code like this

browser.executeScript(dragAndDrop, element, targetArea);


问:
Fastest way to count folder files in .NET 4.0
I need to count the number of files in a folder in .NET 4:
The count will return number of all files except the .db file in the folder.

Option 1:

```<code> IEnumerable<string> enumerables = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
 int iNumFiles = 0;
 foreach (string f in enumerables)
 {
    if (!f.EndsWith(".db"))
       iNumFiles++;
 }

 //iNumFiles is the count
</code>```

Option 2:

```<code>int iNumFiles = 0;
IEnumerable<string> enumerables1 = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
IEnumerable<string> enumerables2 = Directory.EnumerateFiles(strPath, "*.db", SearchOption.TopDirectoryOnly);

iNumFiles = enumerables1.Count() - enumerables2.Count();

//iNumFiles is the count
</code>```

Is there any other simpler but better methods (using RegEx or something else) that I should use?

EDIT:
Should I keep the .db file or how useful it is? All I know it is the database (cache) of folder contents.

This is messing up my file count.

Thanks for reading.

答:
Turn the . results into a queryable object.  then query out the *.db items.

var queryObject = My.Computer.FileSystem.getFiles(foldername,       FileIO.SearchOption.SearchTopLevelOnly, "*.*").AsQueryable();

var filesIcareAbout = queryObject.where(f => right(f,3) != ".db");

I took some syntax shorcuts.  This may not be exactly right syntactically.

Body:
I need to count the number of files in a folder in .NET 4:
The count will return number of all files except the .db file in the folder.

Option 1:

 IEnumerable<string> enumerables = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
 int iNumFiles = 0;
 foreach (string f in enumerables)
 {
    if (!f.EndsWith(".db"))
       iNumFiles++;
 }

 //iNumFiles is the count

Option 2:

int iNumFiles = 0;
IEnumerable<string> enumerables1 = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
IEnumerable<string> enumerables2 = Directory.EnumerateFiles(strPath, "*.db", SearchOption.TopDirectoryOnly);

iNumFiles = enumerables1.Count() - enumerables2.Count();

//iNumFiles is the count

Is there any other simpler but better methods (using RegEx or something else) that I should use?

EDIT:
Should I keep the .db file or how useful it is? All I know it is the database (cache) of folder contents.

This is messing up my file count.

Thanks for reading.


问:
Dynamic Grouping in stored procedure determined by SSRS
I have an SP, who's Count(ColX) changes depending on which column I am grouping by. I have 4 tables in a report in SSRS (VS 2013) that all use the this SP select, but each table will have a different count due to each table grouping by a different column in this SP.

Is it possible to keep one SP and group in this SP differently for each table this SP is called in in SSRS?

E.g. Table A will group by ColX first, Table B will group by ColY first, etc.

答:
If you mean that you have a single fixed stored procedure and you want to take the output from that and use it in four different tables in your report design, each grouping the data differently, then yes.

SSRS does not care where the data came from, the results of the stored procedure are passed to SSRS. Each table then determines how it will display that data.

Think of the tables in your report as SQL views. You can have a single database table and write many views over it, each giving you different output.

If this is not what you mean then my apologies, you've just wasted 30 seconds of your life reading this!


问:
PickerView to return certain text string based on picker selection
What I would like to do is have a certain text string to appear depending on what is selected from the Picker. For instance, the choices Blue, Green, and Yellow are available for selection in the picker. When you choose Blue some text (ex. I LOVE the ocean!) is output to a label.

I've got everything working, except I can't change the output from anything other than what was selected in the picker.

Example of the code in question,

```<code>let colors = ["Blue", "Green", "Yellow"]

func numberOfComponents(in pickerView: UIPickerView) -> Int
{
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    return colors[row]

}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return colors.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = colors[row]
}    //but I want this to return a text string when Blue is 'picked', another different string when Green is 'picked', and a third sting when Yellow is 'picked'
</code>```

I have it set so the data appears on a label once a selection in the pickerView has been made, but like I said, I can only get the data from the pickerView itself to appear. I would like to have some other data (that you don't see) appear based on your selection in the picker.

答:
The code you put in didSelectRow is setting the color name. If you want the selected row number, then set the label to the selected row.

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = "\(row + 1)"
}
</code>```

Body:
What I would like to do is have a certain text string to appear depending on what is selected from the Picker. For instance, the choices Blue, Green, and Yellow are available for selection in the picker. When you choose Blue some text (ex. I LOVE the ocean!) is output to a label.

I've got everything working, except I can't change the output from anything other than what was selected in the picker.

Example of the code in question,

let colors = ["Blue", "Green", "Yellow"]

func numberOfComponents(in pickerView: UIPickerView) -> Int
{
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    return colors[row]

}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return colors.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = colors[row]
}    //but I want this to return a text string when Blue is 'picked', another different string when Green is 'picked', and a third sting when Yellow is 'picked'

I have it set so the data appears on a label once a selection in the pickerView has been made, but like I said, I can only get the data from the pickerView itself to appear. I would like to have some other data (that you don't see) appear based on your selection in the picker.

Body:
The code you put in didSelectRow is setting the color name. If you want the selected row number, then set the label to the selected row.

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = "\(row + 1)"
}


问:
Condensing data frame with same names and different values
I have a data frame that I am trying to condense. There are multiple value os X with the same names but with different Y values associated with them:

```<code>  X Y
1 a 1
2 b 3
3 a 2
4 c 4
5 b 7
</code>```

I want to condense the data frame so there are no duplicate names in X, like below:

```<code>  X Y
1 a 3
2 b 10
3 c 4
</code>```

答:
Using tidyverse:</p>

```<code>library(tidyverse)
df <- df %>%
group_by(x) %>%
summarise(y = sum(y))
</code>```

Body:
I have a data frame that I am trying to condense. There are multiple value os X with the same names but with different Y values associated with them:

  X Y
1 a 1
2 b 3
3 a 2
4 c 4
5 b 7

I want to condense the data frame so there are no duplicate names in X, like below:

  X Y
1 a 3
2 b 10
3 c 4

Body:
Using tidyverse:

library(tidyverse)
df <- df %>%
group_by(x) %>%
summarise(y = sum(y))


问:
SQL procedure to show how many hours has worker worked
```<code>+-----------+-------------------------------+-------+
| Worker ID | Time(MM/DD/YYYY Hour:Min:Sec) | InOut |
+-----------+-------------------------------+-------+
|        1  |  12/04/2017 10:00:00          | In    |
|        2  |  12/04/2017 10:00:00          | In    |
|        2  |  12/04/2017 18:40:02          | Out   |
|        3  |  12/04/2017 10:00:00          | In    |
|        1  |  12/04/2017 12:01:00          | Out   |
|        3  |  12/04/2017 19:40:05          | Out   |
+-----------+-------------------------------+-------+
</code>```

Hi! I have problem with my project and I thought some of you would help me. I have table like that. It is simple table that indicates worker getting in and out of company. I need to do procedure which would take ID and number of day as In parameters and it would show how many hours and minutes that worker has worked that day. Thanks for help.

答:
Yeah, I had to do a number of queries like this at my old job.  Here's the approach I used, and it worked out pretty well:

For each "Out" record, get the MAX(TIME) on "In" records with a time earlier than the OUT record

Does that make sense?  You're basically joining the table against itself, looking for the record that represents the "clock in" time for any particular "clock out" time.

So here's the backbone:

```<code>select
*
, (
        SELECT MAX(tim) from @tempTable subQ
        where subQ.id = main.id
        and subQ.tim <= main.tim
        and subQ.InOut = 'In'
  ) as correspondingInTime
from @tempTable main
where InOut = 'Out'
</code>```

... from here, you can get the data you need.  Either by manipulating the query above, or using it as a subquery itself (which is my favored way of doing it) - something like:

```<code>select id as workerID, sum(DATEDIFF(s, correspondingInTime, tim)) as totalSecondsWorked
from
(
    select
    *
    , (
            SELECT MAX(tim) from @tempTable subQ
            where subQ.id = main.id
            and subQ.tim <= main.tim
            and subQ.InOut = 'In'
      ) correspondingInTime
    from @tempTable main
    where InOut = 'Out'
) mainQuery
group by id
</code>```

EDIT: Remove the 'as' before correspondingInTime, because oracle doesn't allow 'as' in table aliasing.

Body:
+-----------+-------------------------------+-------+
| Worker ID | Time(MM/DD/YYYY Hour:Min:Sec) | InOut |
+-----------+-------------------------------+-------+
|        1  |  12/04/2017 10:00:00          | In    |
|        2  |  12/04/2017 10:00:00          | In    |
|        2  |  12/04/2017 18:40:02          | Out   |
|        3  |  12/04/2017 10:00:00          | In    |
|        1  |  12/04/2017 12:01:00          | Out   |
|        3  |  12/04/2017 19:40:05          | Out   |
+-----------+-------------------------------+-------+

Hi! I have problem with my project and I thought some of you would help me. I have table like that. It is simple table that indicates worker getting in and out of company. I need to do procedure which would take ID and number of day as In parameters and it would show how many hours and minutes that worker has worked that day. Thanks for help.

Body:
Yeah, I had to do a number of queries like this at my old job.  Here's the approach I used, and it worked out pretty well:

For each "Out" record, get the MAX(TIME) on "In" records with a time earlier than the OUT record

Does that make sense?  You're basically joining the table against itself, looking for the record that represents the "clock in" time for any particular "clock out" time.

So here's the backbone:

select
*
, (
        SELECT MAX(tim) from @tempTable subQ
        where subQ.id = main.id
        and subQ.tim <= main.tim
        and subQ.InOut = 'In'
  ) as correspondingInTime
from @tempTable main
where InOut = 'Out'

... from here, you can get the data you need.  Either by manipulating the query above, or using it as a subquery itself (which is my favored way of doing it) - something like:

select id as workerID, sum(DATEDIFF(s, correspondingInTime, tim)) as totalSecondsWorked
from
(
    select
    *
    , (
            SELECT MAX(tim) from @tempTable subQ
            where subQ.id = main.id
            and subQ.tim <= main.tim
            and subQ.InOut = 'In'
      ) correspondingInTime
    from @tempTable main
    where InOut = 'Out'
) mainQuery
group by id

EDIT: Remove the 'as' before correspondingInTime, because oracle doesn't allow 'as' in table aliasing.


问:
Return Boolean if Rails Object Contains Specific Value in a Specific Column

I'm trying to write a rails/activerecord query that returns true if a rails object contains a specific value.  I have a join table called 'Events' between 'Users' and 'Bicycles' and the Events table has a column called 'event_type'.  I'm trying to find out if a specific Bicycle's last created event contains the event_type 'stolen'.  I want to return only true or false, not the rails object itself.

I have been able to return the last event object with no problem using:

Bicycle.find(:id).events.last

And I can return true or false if there is any event registered to that bicycle that contains event_type 'stolen' by using:

Bicycle.find(:id).events.where("event_type='stolen'").count.positive?

How can I return true only if the last event on the object contains event_type 'stolen'?

Thanks!

答:
You're going to laugh at how obvious the answer is...

```<code>Bicycle.find(id).events.last.event_type == "stolen"
</code>```

One minor edge case to account for, however, is: What if there are no events for that bicycle?

In that case, Bicycle.find(id).events will return an empty collection, so Bicycle.find(id).events.last == nil. This means the above code would raise an exception: NoMethodError: Undefined method event_type for nil:NilClass.

However, a simple workaround would be to use the safe navigation operator:

```<code>Bicycle.find(id).events.last&.event_type == "stolen"
</code>```

Body:
You're going to laugh at how obvious the answer is...

Bicycle.find(id).events.last.event_type == "stolen"

One minor edge case to account for, however, is: What if there are no events for that bicycle?

In that case, Bicycle.find(id).events will return an empty collection, so Bicycle.find(id).events.last == nil. This means the above code would raise an exception: NoMethodError: Undefined method event_type for nil:NilClass.

However, a simple workaround would be to use the safe navigation operator:

Bicycle.find(id).events.last&.event_type == "stolen"


问:
Converting 3 column parent/child list into dictionary
I have a large csv file that has 3 columns:

```<code>Parent  Child   Qty
31282   42126A  0.00272
31282   50553   0.107
31282   61119   1
31283   42126A  0.00272
31283   50277   0.107
31283   61119   1
</code>```

A Child can be a parent of other Children.

There could be a scenario of two identical children having different parents and therefore different quantities:

```<code>31254   31282   0.535
31255   31282   2.8448
</code>```

I want to convert that into a dictionary, that includes the quantities.

So far I can make the dict with the following code:

```<code>has_parent = set()
all_items = {}
quan = []

for parent, child, qty in data:
    if parent not in all_items:
        all_items[parent] = {}
    if child not in all_items:
        all_items[child] = {}

    quan.append({'parent': parent,'child': child, 'qty': qty})

    all_items[parent][child] = all_items[child]
    has_parent.add(child)

result = {}
for key, value in all_items.items():
    if key not in has_parent:
        result[key] = value
</code>```

The result dict looks like this:

```<code> '31597': {'31598': {'42126A': {},
                     '50005A': {},
                     '50365': {},
                     '50393': {},
                     '53120': {},
                     '61554': {}}},
 '31599': {'31600': {'50398': {}}},
 '31601': {'31602': {'50399': {}}},
 '31603': {'31600': {'50398': {}}},
 '31604': {'31602': {'50399': {}}},
 '31605': {'31606': {'50403': {}}},
 '31607': {'31606': {'50403': {}}},
 '31609': {'31608': {'51037': {}, '52095': {}, '64041': {}}},
 '31612': {'31610': {'40098': {}, '60544': {}, '61501A': {}}},
</code>```

My issue is how can I insert the QTY into the proper key.

I can find a key's parents and then look at the original file and see the quantity, but how can I insert that quantity at a depth of maybe 3 or 4 or more?

This is the output of a Child Key and its many parents.

```<code>60542
['31280', '31281', '31280', '31281']
----------
61554
['31596', '31598', '31280', '31281', '31280', '31281']
</code>```

答:
You're going to want an auxiliary data structure to keep track of the root-node that corresponds to the leaf you want to modify. A simple choice would be an adjacency list. This way you can know which node to start your search from.

Alternatively (and with greater simplicity), you could implement BFS/DFS, but the lack of structure in your data would ensure poor time-complexity.

Body:
I have a large csv file that has 3 columns:

Parent  Child   Qty
31282   42126A  0.00272
31282   50553   0.107
31282   61119   1
31283   42126A  0.00272
31283   50277   0.107
31283   61119   1

A Child can be a parent of other Children.

There could be a scenario of two identical children having different parents and therefore different quantities:

31254   31282   0.535
31255   31282   2.8448

I want to convert that into a dictionary, that includes the quantities.

So far I can make the dict with the following code:

has_parent = set()
all_items = {}
quan = []

for parent, child, qty in data:
    if parent not in all_items:
        all_items[parent] = {}
    if child not in all_items:
        all_items[child] = {}

    quan.append({'parent': parent,'child': child, 'qty': qty})

    all_items[parent][child] = all_items[child]
    has_parent.add(child)

result = {}
for key, value in all_items.items():
    if key not in has_parent:
        result[key] = value

The result dict looks like this:

 '31597': {'31598': {'42126A': {},
                     '50005A': {},
                     '50365': {},
                     '50393': {},
                     '53120': {},
                     '61554': {}}},
 '31599': {'31600': {'50398': {}}},
 '31601': {'31602': {'50399': {}}},
 '31603': {'31600': {'50398': {}}},
 '31604': {'31602': {'50399': {}}},
 '31605': {'31606': {'50403': {}}},
 '31607': {'31606': {'50403': {}}},
 '31609': {'31608': {'51037': {}, '52095': {}, '64041': {}}},
 '31612': {'31610': {'40098': {}, '60544': {}, '61501A': {}}},

My issue is how can I insert the QTY into the proper key.

I can find a key's parents and then look at the original file and see the quantity, but how can I insert that quantity at a depth of maybe 3 or 4 or more?

This is the output of a Child Key and its many parents.

60542
['31280', '31281', '31280', '31281']
----------
61554
['31596', '31598', '31280', '31281', '31280', '31281']


问:
phantom database in Vista
I have a C++/MFC based application that accesses a Microsoft Access database in the folder c:\Program Files\xxx\yyy.

In literally hundreds of other computers running XP, Vista, and 7; the application works just fine.  But on one Vista machine, the apps reads the data from the database and it is completely different then what is actually in the database if I access it via Microsoft Access.  I delete the database from that folder and the application can still access this "phantom" database.

Does anyone have any recommendations?

Thanks

答: The %ProgramFiles% folder is virtualized, see http://support.microsoft.com/kb/927387.

Title: phantom database in Vista


问:
Laravel DataTables handle 401 Unauthorized error
I inherited a Laravel application that is using Yajra DataTables to display grid content in a page.

If Laravel's session expires, the DataTable will throw the following alert:

DataTables warning: table id=dataTableBuilder - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Viewing the Network tab in Chrome shows me that the AJAX response for the DataTable was a 401 Unauthorized. This is all expected behavior, but instead of displaying an arbitrary error to the user, I'd like to send the user to the login page with a message that says "your session timed out, please log in again." or something.

I can't figure out how to do that.

Traditional DataTables integrations allow me to pass an error handler to the AJAX response (i.e. {ajax: { error: function () {...} }}), but there doesn't seem to be a way to do that with Laravel DataTables.

Laravel DataTables has an html() method that I can override like so:

```<code>public function html() {
    return $this->builder()
           ->ajax([
             error => ''
           ]);
}
</code>```

But the ajax method on the builder doesn't allow me to pass a JavaScript handler to the error property.

Is there anyway to accomplish the force login when sessions time out?

答:
Given the comment chain above, my suggestion would be to put a unique string in the error response, like:

```<code>code: 401
</code>```

Then, use the global $.ajaxError to catch errors and do something different based on the response text:

```<code>$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    if (typeof settings === "string" && settings.indexOf('401') > -1) {
        //you can probably do something here
    }
});
</code>```

You could probably even do this in a more efficient way as the 401 response type should be observable in one of the 4 properties (can't remember which)

Body:
I inherited a Laravel application that is using Yajra DataTables to display grid content in a page.

If Laravel's session expires, the DataTable will throw the following alert:

DataTables warning: table id=dataTableBuilder - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Viewing the Network tab in Chrome shows me that the AJAX response for the DataTable was a 401 Unauthorized. This is all expected behavior, but instead of displaying an arbitrary error to the user, I'd like to send the user to the login page with a message that says "your session timed out, please log in again." or something.

I can't figure out how to do that.

Traditional DataTables integrations allow me to pass an error handler to the AJAX response (i.e. {ajax: { error: function () {...} }}), but there doesn't seem to be a way to do that with Laravel DataTables.

Laravel DataTables has an html() method that I can override like so:

public function html() {
    return $this->builder()
           ->ajax([
             error => ''
           ]);
}

But the ajax method on the builder doesn't allow me to pass a JavaScript handler to the error property.

Is there anyway to accomplish the force login when sessions time out?

Body:
Given the comment chain above, my suggestion would be to put a unique string in the error response, like:

code: 401

Then, use the global $.ajaxError to catch errors and do something different based on the response text:

$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    if (typeof settings === "string" && settings.indexOf('401') > -1) {
        //you can probably do something here
    }
});

You could probably even do this in a more efficient way as the 401 response type should be observable in one of the 4 properties (can't remember which)


问:
Java - HashMap cannot use new object as search key
What I am trying to do here is to fill a HashMap with objects Obj using the key Key and when I finish I want to have access to those values according to any any of the possible keys. I have written the following code and what happened is that although the first show really shows the values I want, the second one raises a NullPointerException.

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

public class My{
public static void main(String[] args){
    Map<Key,Obj> myMap = new HashMap<Key,Obj>();

    Obj ob1 = new Obj("Nick",19);
    Obj ob2 = new Obj("George",17);

    Key key1 = new Key(1,2);
    Key key2 = new Key(2,1);

    myMap.put(key1,ob1);
    myMap.put(key2,ob2);

    myMap.get(key1).show();
    myMap.get(new Key(1,2)).show();

}
</code>```

I can tell that somehow Java cannot tell that new Key(1,2) is equal with key1, but I cannot think of how can I overcome this issue.

```<code>public class Obj{

    private String name;
    private int age;

    Obj(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void show(){
         System.out.println(name + " " + age);
    }
}
</code>```

These are the classes I use

```<code>import java.* ;

public class Key{

    public int x,y;

    Key(int x, int y){
        this.x = x;
        this.y = y;
    }

    public boolean equals(Key d){
        if ((this.x == d.x)&&(this.y == d.y)){
            return true;
        }
        else{
            return false;
        }
    }
}
</code>```

答:
You have two problems in your implementation of Key. First, the equals' method signature is wrong - it should be public boolean equals(Object). This error would have been easily noticeable if you had used the @Override annotation. Second, you should also override the hashCode() method:

```<code>@Override
public boolean equals(Object o) {
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    Key key = (Key) o;
    return x == key.x && y == key.y;
}

@Override
public int hashCode() {
    return Objects.hash(x, y);
}
</code>```

Body:
What I am trying to do here is to fill a HashMap with objects Obj using the key Key and when I finish I want to have access to those values according to any any of the possible keys. I have written the following code and what happened is that although the first show really shows the values I want, the second one raises a NullPointerException.

import java.util.*;

public class My{
public static void main(String[] args){
    Map<Key,Obj> myMap = new HashMap<Key,Obj>();

    Obj ob1 = new Obj("Nick",19);
    Obj ob2 = new Obj("George",17);

    Key key1 = new Key(1,2);
    Key key2 = new Key(2,1);

    myMap.put(key1,ob1);
    myMap.put(key2,ob2);

    myMap.get(key1).show();
    myMap.get(new Key(1,2)).show();

}

I can tell that somehow Java cannot tell that new Key(1,2) is equal with key1, but I cannot think of how can I overcome this issue.

public class Obj{

    private String name;
    private int age;

    Obj(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void show(){
         System.out.println(name + " " + age);
    }
}

These are the classes I use

import java.* ;

public class Key{

    public int x,y;

    Key(int x, int y){
        this.x = x;
        this.y = y;
    }

    public boolean equals(Key d){
        if ((this.x == d.x)&&(this.y == d.y)){
            return true;
        }
        else{
            return false;
        }
    }
}

Body:
You have two problems in your implementation of Key. First, the equals' method signature is wrong - it should be public boolean equals(Object). This error would have been easily noticeable if you had used the @Override annotation. Second, you should also override the hashCode() method:

@Override
public boolean equals(Object o) {
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    Key key = (Key) o;
    return x == key.x && y == key.y;
}

@Override
public int hashCode() {
    return Objects.hash(x, y);
}


问:
RxJava Observable timeout before first element
I have device that send me ping, and I use observable for this. But before first ping we start connection and it takes some time. Therefore I want first ping have 10 sec timeout. I make it this way:

```<code>public Observable<Ping> getPing() {
    ConnectableObservable<Ping> observable = device.connectToDevice().publish();

    Observable<Ping> firstWithTimeout = observable.take(1).timeout(10, TimeUnit.SECONDS);
    Observable<Ping> fromSecondWithoutTimeout = observable.skip(1);

    Observable<Ping> mergedObservable = firstWithTimeout.mergeWith(fromSecondWithoutTimeout)
            .doOnDispose(() -> disconnect(bluetoothDevice))
            .doOnError(error -> disconnect(bluetoothDevice));

    observable.connect();
    return mergedObservable;
}
</code>```

For test I use

```<code>Subject<Ping> observable = PublishSubject.create();
when(device.connect()).thenReturn(observable);
TestObserver<Ping> testSubscriber = TestObserver.create();
getPing.subscribe(testSubscriber);
observable.onNext(new Ping());

testSubscriber.assertValueCount(1);
</code>```

This test will fail, because TimeoutException, in spite I send ping instantly.

答:
Please have a look at this setup:

JUnit5 / RxJava2

I think you error a incorrect configuration of the mock

when(device.connect()).thenReturn(observable);

Please have a look at my implementation. There is no need to use publish / connect when you are createing a new observable with every method-invocation. Use autoConnect in device for method-impl connectToDevice()

```<code>  Device device;

  @BeforeEach
  void setUp() {
    device = mock(Device.class);
  }

  @Test
  void name() throws Exception {
    Subject<Ping> observable = PublishSubject.create();

    when(device.connectToDevice()).thenReturn(observable);

    TestObserver<Ping> test = getPing(Schedulers.computation()).test();
    observable.onNext(new Ping());

    test.assertValueCount(1);
  }

  @Test
  void name2() throws Exception {
    Subject<Ping> observable = PublishSubject.create();

    when(device.connectToDevice()).thenReturn(observable);

    TestScheduler testScheduler = new TestScheduler();
    TestObserver<Ping> test = getPing(testScheduler).test();

    testScheduler.advanceTimeBy(20, TimeUnit.SECONDS);

    observable.onNext(new Ping());

    test.assertError(TimeoutException.class);
  }

  private Observable<Ping> getPing(Scheduler scheduler) {

    return device
        .connectToDevice()
        .take(1)
        .timeout(10, TimeUnit.SECONDS, scheduler)
        .doOnDispose(() -> disconnect())
        .doOnError(error -> disconnect());
  }

  private void disconnect() {}

  interface Device {
    Observable<Ping> connectToDevice();
  }

  class Ping {}
</code>```

Body:
I have device that send me ping, and I use observable for this. But before first ping we start connection and it takes some time. Therefore I want first ping have 10 sec timeout. I make it this way:

public Observable<Ping> getPing() {
    ConnectableObservable<Ping> observable = device.connectToDevice().publish();

    Observable<Ping> firstWithTimeout = observable.take(1).timeout(10, TimeUnit.SECONDS);
    Observable<Ping> fromSecondWithoutTimeout = observable.skip(1);

    Observable<Ping> mergedObservable = firstWithTimeout.mergeWith(fromSecondWithoutTimeout)
            .doOnDispose(() -> disconnect(bluetoothDevice))
            .doOnError(error -> disconnect(bluetoothDevice));

    observable.connect();
    return mergedObservable;
}

For test I use

Subject<Ping> observable = PublishSubject.create();
when(device.connect()).thenReturn(observable);
TestObserver<Ping> testSubscriber = TestObserver.create();
getPing.subscribe(testSubscriber);
observable.onNext(new Ping());

testSubscriber.assertValueCount(1);

This test will fail, because TimeoutException, in spite I send ping instantly.

Body:
Please have a look at this setup:

JUnit5 / RxJava2

I think you error a incorrect configuration of the mock

when(device.connect()).thenReturn(observable);

Please have a look at my implementation. There is no need to use publish / connect when you are createing a new observable with every method-invocation. Use autoConnect in device for method-impl connectToDevice()

  Device device;

  @BeforeEach
  void setUp() {
    device = mock(Device.class);
  }

  @Test
  void name() throws Exception {
    Subject<Ping> observable = PublishSubject.create();

    when(device.connectToDevice()).thenReturn(observable);

    TestObserver<Ping> test = getPing(Schedulers.computation()).test();
    observable.onNext(new Ping());

    test.assertValueCount(1);
  }

  @Test
  void name2() throws Exception {
    Subject<Ping> observable = PublishSubject.create();

    when(device.connectToDevice()).thenReturn(observable);

    TestScheduler testScheduler = new TestScheduler();
    TestObserver<Ping> test = getPing(testScheduler).test();

    testScheduler.advanceTimeBy(20, TimeUnit.SECONDS);

    observable.onNext(new Ping());

    test.assertError(TimeoutException.class);
  }

  private Observable<Ping> getPing(Scheduler scheduler) {

    return device
        .connectToDevice()
        .take(1)
        .timeout(10, TimeUnit.SECONDS, scheduler)
        .doOnDispose(() -> disconnect())
        .doOnError(error -> disconnect());
  }

  private void disconnect() {}

  interface Device {
    Observable<Ping> connectToDevice();
  }

  class Ping {}


问:
EF4 Linq Oracle11g making queries none case-sensitive
We are moving to EF4 & Linq as our db interface to a Oracle 11g db. The database is setup as case sensitive, but we need to search as case insensitive. In oracle using "UPPER" in the query is potentially very expensive. I have looked at the following options with the indicated results:

```<code>ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE))

generates SQL Where clause:

WHERE TABLE.FIELD = VARIABLE
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE.ToUpper()))

generates SQL Where clause:

WHERE TABLE.FIELD = (UPPER(VARIABLE))
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.ToUpper().Equals(VARIABLE.ToUpper()));

generates SQL Where clause:

WHERE (UPPER(TABLE.FIELD)) = (UPPER(VARIABLE))
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE, StringComparison.CurrentCultureIgnoreCase))

generates SQL Where clause:

WHERE TABLE.FIELD = VARIABLE
-----------------------
</code>```

The results kinda speak for themselves, except that the last example could actually miss records.

Does anyone have any other thoughts on techniques?

Thanks, Sammer

答: You need to either change the column collation in DB metadata or specify it in the query. The only way to specify it in a query in EF is to use ESQL or Query Builder methods. A better idea is to change the collation on the DB column itself.</p>

Body:
We are moving to EF4 & Linq as our db interface to a Oracle 11g db. The database is setup as case sensitive, but we need to search as case insensitive. In oracle using "UPPER" in the query is potentially very expensive. I have looked at the following options with the indicated results:

ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE))

generates SQL Where clause:

WHERE TABLE.FIELD = VARIABLE
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE.ToUpper()))

generates SQL Where clause:

WHERE TABLE.FIELD = (UPPER(VARIABLE))
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.ToUpper().Equals(VARIABLE.ToUpper()));

generates SQL Where clause:

WHERE (UPPER(TABLE.FIELD)) = (UPPER(VARIABLE))
---------------------
ChangeEntities.TABLE.Where(x => x.FIELD.Equals(VARIABLE, StringComparison.CurrentCultureIgnoreCase))

generates SQL Where clause:

WHERE TABLE.FIELD = VARIABLE
-----------------------

The results kinda speak for themselves, except that the last example could actually miss records.

Does anyone have any other thoughts on techniques?

Thanks, Sammer


问:
How to stop directory browsing of a web site but also allow default document
When you attempt to visit a directory on a web server you get a 403 message, whereas its generally more desirable to get a 404 message so you're not giving a hacker a clue that a folder exists.

I thought I had found the ultimate solution to this problem - by adding this to web.config system.webServer:

```<code><handlers>
  <add name="StopDirectoryBrowsing" path="*." resourceType="Directory" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" />
</handlers>
</code>```

This correctly raises a 404 when you attempt to visit a directory.

However sadly it kills default document mechanism at the top level.

Can anyone suggest a variant of the above that allows default document to work but still protects sub directories.

答:
this doesn't actually change the status codes returned but you can redirect as you like using <customErrors>:

```<code><customErrors mode="RemoteOnly" defaultRedirect="~/redirect/error-status.aspx">
    <error statusCode="403" redirect="~/redirect/access-denied.aspx" />
    <error statusCode="404" redirect="~/redirect/file-not-found.aspx" />
</customErrors>
</code>```

you could redirect every status code to one single page if you wanted to.

Body:
When you attempt to visit a directory on a web server you get a 403 message, whereas its generally more desirable to get a 404 message so you're not giving a hacker a clue that a folder exists.

I thought I had found the ultimate solution to this problem - by adding this to web.config system.webServer:

<handlers>
  <add name="StopDirectoryBrowsing" path="*." resourceType="Directory" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" />
</handlers>

This correctly raises a 404 when you attempt to visit a directory.

However sadly it kills default document mechanism at the top level.

Can anyone suggest a variant of the above that allows default document to work but still protects sub directories.

Body:
this doesn't actually change the status codes returned but you can redirect as you like using <customErrors>:

<customErrors mode="RemoteOnly" defaultRedirect="~/redirect/error-status.aspx">
    <error statusCode="403" redirect="~/redirect/access-denied.aspx" />
    <error statusCode="404" redirect="~/redirect/file-not-found.aspx" />
</customErrors>

you could redirect every status code to one single page if you wanted to.


问:
Linear and Unique types with mkPair
I've been reading through this article here http://edsko.net/2017/01/08/linearity-in-haskell/ and the author mentions that one can construct a non-unique array with unique elements but that you can't extract them.

I.e.

```<code>mkPair :: 1:a -> 1:b -> ω:(1:a, 1:b) -- correct but useless
mkPair x y = (x, y)
</code>```

but couldn't you read the elements once in the calling function? Maybe I'm missing something.

Also, although legal, this same function is illegal when looking at it from a linearity perspective. But I thought these were just 2 sides of the same coin, so the function would not change legality depending upon perspective.

答:
I'm not sure what the author of the blog post means when he says that this is correct but useless. In Clean, a language which has actually implemented uniqueness types, this is not allowed due to uniqueness propagation. You can read more about that in section 9.2 of the language report. There simply does not exist a type ω:(1:a, 1:b) (which is (*a,*b) in Clean syntax), because due to uniqueness propagation this actually is 1:(1:a, 1:b) or *(*a,*b).

This may be what the author is trying to express, but I find the post hard to read due to the lack of a theoretical framework.

Title: Linear and Unique types with mkPair

Body:
I've been reading through this article here http://edsko.net/2017/01/08/linearity-in-haskell/ and the author mentions that one can construct a non-unique array with unique elements but that you can't extract them.

I.e.

mkPair :: 1:a -> 1:b -> ω:(1:a, 1:b) -- correct but useless
mkPair x y = (x, y)

but couldn't you read the elements once in the calling function? Maybe I'm missing something.

Also, although legal, this same function is illegal when looking at it from a linearity perspective. But I thought these were just 2 sides of the same coin, so the function would not change legality depending upon perspective.


问:
Finding two associated indexes where the sum of two elements equals a target value
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}
</code>```

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

答:
Basically the same as zzxyz's most recent edit but a little quicker and dirtier.</p>

```<code>#include <iostream>
#include <vector>

bool FindSolution(const std::vector<int> &list, // const reference. Less copying
                  int target)
{
    for (int i: list) // Range-based for (added in C++11)
    {
        for (int j: list)
        {
            if (i + j == target) // i and j are the numbers from the vector.
                                 // no need for indexing
            {
                return true;
            }
        }
    }
    return false;
}

int main()
{
    std::vector<int> list{1,2,3,4,5}; // Uniform initialization Added in C++11.
                                      // No need for push-backs of fixed data

    if (FindSolution(list, 8))
    {
        std::cout << "There is a solution\n";
    }
    else
    {
        std::cout << "There is no solution\n";
    }

    return 0;
}
</code>```

Body:
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

Body:
Basically the same as zzxyz's most recent edit but a little quicker and dirtier.

#include <iostream>
#include <vector>

bool FindSolution(const std::vector<int> &list, // const reference. Less copying
                  int target)
{
    for (int i: list) // Range-based for (added in C++11)
    {
        for (int j: list)
        {
            if (i + j == target) // i and j are the numbers from the vector.
                                 // no need for indexing
            {
                return true;
            }
        }
    }
    return false;
}

int main()
{
    std::vector<int> list{1,2,3,4,5}; // Uniform initialization Added in C++11.
                                      // No need for push-backs of fixed data

    if (FindSolution(list, 8))
    {
        std::cout << "There is a solution\n";
    }
    else
    {
        std::cout << "There is no solution\n";
    }

    return 0;
}


问:
Gradle project refresh failed Unable to get the CMake
enter image description here"Gradle 'projectname' project refresh failed"

This is the error message that is being displayed when i start android studio. how to rectify this? My android studio version is 3.0
Thanks in advance

Error:Unable to get the CMake version located at:
  C:\Users\Asus\AppData\Local\Android\Sdk\cmake\bin

答:
You need to install CMake from the SDK tools.

Open File > Settings.
Select Appearance & Behavior > System Settings > Android SDK.
Switch to the SDK Tools tab.
Check CMake. Apply.


问:
get the distinct elements of an ArrayType column in a spark dataframe
I have a dataframe with 3 columns named id, feat1 and feat2. feat1 and feat2 are in the form of Array of String:

```<code>Id, feat1,feat2
------------------
1, ["feat1_1","feat1_2","feat1_3"],[]

2, ["feat1_2"],["feat2_1","feat2_2"]

3,["feat1_4"],["feat2_3"]
</code>```

I want to get the list of distinct elements inside each feature column, so the output will be:

```<code>distinct_feat1,distinct_feat2
-----------------------------
["feat1_1","feat1_2","feat1_3","feat1_4"],["feat2_1","feat2_2","feat2_3]
</code>```

what is the best way to do this in Scala?

答:
The method provided by Psidom works great, here is a function that does the same given a Dataframe and a list of fields:

```<code>def array_unique_values(df, fields):
    from pyspark.sql.functions import col, collect_set, explode
    from functools import reduce
    data = reduce(lambda d, f: d.withColumn(f, explode(col(f))), fields, df)
    return data.agg(*[collect_set(f).alias(f + '_distinct') for f in fields])
</code>```

And then:

```<code>data = array_unique_values(df, my_fields)
data.take(1)
</code>```

Body:
I have a dataframe with 3 columns named id, feat1 and feat2. feat1 and feat2 are in the form of Array of String:

Id, feat1,feat2
------------------
1, ["feat1_1","feat1_2","feat1_3"],[]

2, ["feat1_2"],["feat2_1","feat2_2"]

3,["feat1_4"],["feat2_3"]

I want to get the list of distinct elements inside each feature column, so the output will be:

distinct_feat1,distinct_feat2
-----------------------------
["feat1_1","feat1_2","feat1_3","feat1_4"],["feat2_1","feat2_2","feat2_3]

what is the best way to do this in Scala?

Body:
The method provided by Psidom works great, here is a function that does the same given a Dataframe and a list of fields:

def array_unique_values(df, fields):
    from pyspark.sql.functions import col, collect_set, explode
    from functools import reduce
    data = reduce(lambda d, f: d.withColumn(f, explode(col(f))), fields, df)
    return data.agg(*[collect_set(f).alias(f + '_distinct') for f in fields])

And then:

data = array_unique_values(df, my_fields)
data.take(1)


问:
How to use foreign keys in Ruby on the Rails query?
I have three models; events, users and entries. I would like on my users page for to be able to retrieve information relating to the events associated with the event associated with the user.

```<code>def show
    @user = User.find(params[:id])
    @entry = @user.entries.paginate(page: params[:page])
  end
</code>```

It is more than happy with @user.entries.count but I would like to link up in a table something like this:

Event Name - Event Location - Course

My models are bellow:

```<code>class Event < ApplicationRecord
    has_many :entries, dependent: :destroy

class User < ApplicationRecord
    has_many :entries, dependent: :destroy

class Entry < ApplicationRecord
    belongs_to :user
    belongs_to :event
</code>```

答:
If they're related as:

```<code>class User < ApplicationRecord
  has_many :events
end

class Event < ApplicationRecord
  has_many :entries
  belongs_to :user
end

class Entry < ApplicationRecord
  belongs_to :event
end
</code>```

Then you can use joins starting from Entry, up to User and check events where the user id is the one what you need:

```<code>Entry.joins(event: :user).where(users: { id: user_id })
</code>```

Body:
I have three models; events, users and entries. I would like on my users page for to be able to retrieve information relating to the events associated with the event associated with the user.

def show
    @user = User.find(params[:id])
    @entry = @user.entries.paginate(page: params[:page])
  end

It is more than happy with @user.entries.count but I would like to link up in a table something like this:

Event Name - Event Location - Course

My models are bellow:

class Event < ApplicationRecord
    has_many :entries, dependent: :destroy

class User < ApplicationRecord
    has_many :entries, dependent: :destroy

class Entry < ApplicationRecord
    belongs_to :user
    belongs_to :event

Body:
If they're related as:

class User < ApplicationRecord
  has_many :events
end

class Event < ApplicationRecord
  has_many :entries
  belongs_to :user
end

class Entry < ApplicationRecord
  belongs_to :event
end

Then you can use joins starting from Entry, up to User and check events where the user id is the one what you need:

Entry.joins(event: :user).where(users: { id: user_id })


问:
Error running application that uses ms access database
When I try to run my application I get:

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."

Is there a better way to make the call to the Microsoft access database that runs the application so that this error will not come up.  I would like the application to run on the machine even if Access is not installed.

Visual Studio 2008 - VB.Net is what I used to write it.

What method/technology should I use to make the call to Access db?

答: For machines without Office you can use this. </p>


问:
Android Init startup - Ueventd and watchdogd
I'm a beginner and I'm trying to understand the Kernel-Android interface.

In the system/core/init/init.c, the initial part has the following code.

```<code>if (!strcmp(basename(argv[0]), "ueventd"))
        return ueventd_main(argc, argv);

if (!strcmp(basename(argv[0]), "watchdogd"))
        return watchdogd_main(argc, argv);
</code>```

This is followed by the parsing of the board specific init.rc files.

The ueventd_main parses the board specific uevent.rc files.

The watchdogd_main tries to set the timeout & then keeps writing an empty character to the /dev/watchdog in an infinite loop.

In the book 'Embedded Android' by Karim Yaghmour, it is mentioned as,

One of the first things init does is check whether it was invoked as
  ueventd. init includes an implementation of the udev hotplug events
  handler. Because this code is compiled within init’s own code, init
  checks the command-line that was used to invoke it, and if it was
  invoked through the /sbin/ueventd symbolic link to /init, then init
  immediately runs as ueventd.

My questions are

1) I believe that the arguments to this main function are received from kernel bootcmd parameters "init=". Am I right?

2) Under what scenario one would invoke an init to be run only as ueventd or watchdogd?

3) What do they mean by symbolically linked to /init?

答:
1) I believe that the arguments to this main function are received
  from kernel bootcmd parameters "init=". Am I right?

No, not bootcmd arguments.   argv[0] is the name of the executable being launched.

If you look at the Android.mk for init, you will see:

```<code># Create symlinks.
LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd
</code>```

Here you can see that two extra symbolic links are created, both pointing to init.  These will be included in the final Android boot image in /sbin/

2) Under what scenario one would invoke an init to be run only as
  ueventd or watchdogd?

In init.rc, you can see:

```<code>## Daemon processes to be run by init.
##
service ueventd /sbin/ueventd
    class core
    critical
    seclabel u:r:ueventd:s0
    shutdown critical
</code>```

This is declaring the service ueventd and specifying a path to the ueventd path.  So when the ueventd service is started, it will the the init executable but the argv[0] argument will be ueventd.

watchdogd is done the same way.

So it is the same executable called with three different names init, ueventd, or watchdogd.  Depending on which name it is called with, one of three different code paths are executed (as in the code you referenced).

This is often done when different commands are substantially the same in implementation.  On my Ubuntu system:

```<code>$ ls -l /usr/bin/unxz
lrwxrwxrwx 1 root root 2 Oct  3 11:04 /usr/bin/unxz -> xz
</code>```

You can see that unxz is linked to xz
From the man page for xz: unxz is equivalent to xz --decompress.

So here, there was only one executable, but depending on which executable name is used to launch it, the behavior is different.

3) What do they mean by symbolically linked to /init?

Answered in previous two answers.

Body:
I'm a beginner and I'm trying to understand the Kernel-Android interface.

In the system/core/init/init.c, the initial part has the following code.

if (!strcmp(basename(argv[0]), "ueventd"))
        return ueventd_main(argc, argv);

if (!strcmp(basename(argv[0]), "watchdogd"))
        return watchdogd_main(argc, argv);

This is followed by the parsing of the board specific init.rc files.

The ueventd_main parses the board specific uevent.rc files.

The watchdogd_main tries to set the timeout & then keeps writing an empty character to the /dev/watchdog in an infinite loop.

In the book 'Embedded Android' by Karim Yaghmour, it is mentioned as,

One of the first things init does is check whether it was invoked as
  ueventd. init includes an implementation of the udev hotplug events
  handler. Because this code is compiled within init’s own code, init
  checks the command-line that was used to invoke it, and if it was
  invoked through the /sbin/ueventd symbolic link to /init, then init
  immediately runs as ueventd.

My questions are

1) I believe that the arguments to this main function are received from kernel bootcmd parameters "init=". Am I right?

2) Under what scenario one would invoke an init to be run only as ueventd or watchdogd?

3) What do they mean by symbolically linked to /init?

Body:
1) I believe that the arguments to this main function are received
  from kernel bootcmd parameters "init=". Am I right?

No, not bootcmd arguments.   argv[0] is the name of the executable being launched.

If you look at the Android.mk for init, you will see:

# Create symlinks.
LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \
    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
    ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd

Here you can see that two extra symbolic links are created, both pointing to init.  These will be included in the final Android boot image in /sbin/

2) Under what scenario one would invoke an init to be run only as
  ueventd or watchdogd?

In init.rc, you can see:

## Daemon processes to be run by init.
##
service ueventd /sbin/ueventd
    class core
    critical
    seclabel u:r:ueventd:s0
    shutdown critical

This is declaring the service ueventd and specifying a path to the ueventd path.  So when the ueventd service is started, it will the the init executable but the argv[0] argument will be ueventd.

watchdogd is done the same way.

So it is the same executable called with three different names init, ueventd, or watchdogd.  Depending on which name it is called with, one of three different code paths are executed (as in the code you referenced).

This is often done when different commands are substantially the same in implementation.  On my Ubuntu system:

$ ls -l /usr/bin/unxz
lrwxrwxrwx 1 root root 2 Oct  3 11:04 /usr/bin/unxz -> xz

You can see that unxz is linked to xz
From the man page for xz: unxz is equivalent to xz --decompress.

So here, there was only one executable, but depending on which executable name is used to launch it, the behavior is different.

3) What do they mean by symbolically linked to /init?

Answered in previous two answers.