问:
Invalid content was found starting with element 'employee'. One of '{contractemployee}' is expected
I have to generate XML and XSD from an entity relationship diagram. My XML is correct but I am not able to validate the XSD i generated with this XML document as it throws up an error: Invalid content was found starting with element 'employee'. One of '{contractemployee}' is expected.

XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<company>
<companyname>capgemini</companyname>
<address>mumbai</address>
    <department>
        <dname>software</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0447654321</deptfaxno>
        <deptemail>soft@capgemini.com</deptemail>
            <employee>
                <empid>101</empid>
                <ename>rajat</ename>
                <emailid>rajat@capgemini.com</emailid>
                <phoneno>9876543211</phoneno>
            </employee>
            <contractemployee>
                <name>jade</name>
                <phoneno>9882507167</phoneno>
            </contractemployee>
    </department>
</company>
</code>```

XSD:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xsd:element name="company">
        <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="companyname" type="xsd:string"/>
            <xsd:element name="address" type="xsd:string"/>
            <xsd:element name="department">
                <xsd:complexType>
                    <xsd:sequence>
                        <xsd:element name="dname" type="xsd:string"/>
                        <xsd:element name="deptphoneno" type="xsd:long"/>
                        <xsd:element name="deptfaxno" type="xsd:int"/>
                        <xsd:element name="deptemail" type="xsd:string"/>
                        <xsd:element name="employee">
                            <xsd:complexType>
                                <xsd:sequence>
                                    <xsd:element name="empid" type="xsd:int"/>
                                    <xsd:element name="ename" type="xsd:string"/>
                                    <xsd:element name="emailid" type="xsd:string"/>
                                    <xsd:element name="phoneno" type="xsd:long"/>
                                </xsd:sequence>
                            </xsd:complexType>
                        </xsd:element>
                        <xsd:element name="contractemployee">
                            <xsd:complexType>
                                <xsd:sequence>
                                    <xsd:element name="name" type="xsd:string"/>
                                    <xsd:element name="phoneno" type="xsd:long"/>
                                </xsd:sequence>
                            </xsd:complexType>
                        </xsd:element>
                    </xsd:sequence>
                </xsd:complexType>
            </xsd:element>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</xsd:schema>
</code>```

答:
You were pretty close to the answer. According to the E-R diagram, there is 1- many mandatory relationship between department and employee while 1-many optional relationship between department and contract employee. Whenever there is optional relationship, we use minOccurs="0".

I'm posting both the XML & XSD so you can understand it better.
XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<company
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='companyxsd.xsd'>
    <companyname>Capgemini</companyname>
    <address>Mumbai</address>
    <department>
        <dname>Operations</dname>
        <deptphoneno>987610</deptphoneno>
        <deptfaxno>223654</deptfaxno>
        <deptemail>op@gmail.com</deptemail>
        <employee>
            <empid>20</empid>
            <ename>Mukesh</ename>
            <emailid>mukesh@gmail.com</emailid>
            <phoneno>967642</phoneno>
        </employee>
        <contractemployee>
            <name>Ramesh</name>
            <phoneno>25643</phoneno>
        </contractemployee>
    </department>
</company>
</code>```

The XSD for this XML:
XSD

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"></xs:element>
<xs:element name="address" type="xs:string"></xs:element>
<xs:element name="department" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"></xs:element>
<xs:element name="deptphoneno" type="xs:long"></xs:element>
<xs:element name="deptfaxno" type="xs:long"></xs:element>
<xs:element name="deptemail" type="xs:string"></xs:element>

<xs:element name="employee" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:int"></xs:element>
<xs:element name="ename" type="xs:string"></xs:element>
<xs:element name="emailid" type="xs:string"></xs:element>
<xs:element name="phoneno" type="xs:long"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="contractemployee" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"></xs:element>
<xs:element name="phoneno" type="xs:long"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:sequence>
</xs:complexType>
</xs:element>

</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code>```

Hope this helps you :)

Body:
I have to generate XML and XSD from an entity relationship diagram. My XML is correct but I am not able to validate the XSD i generated with this XML document as it throws up an error: Invalid content was found starting with element 'employee'. One of '{contractemployee}' is expected.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<company>
<companyname>capgemini</companyname>
<address>mumbai</address>
    <department>
        <dname>software</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0447654321</deptfaxno>
        <deptemail>soft@capgemini.com</deptemail>
            <employee>
                <empid>101</empid>
                <ename>rajat</ename>
                <emailid>rajat@capgemini.com</emailid>
                <phoneno>9876543211</phoneno>
            </employee>
            <contractemployee>
                <name>jade</name>
                <phoneno>9882507167</phoneno>
            </contractemployee>
    </department>
</company>

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xsd:element name="company">
        <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="companyname" type="xsd:string"/>
            <xsd:element name="address" type="xsd:string"/>
            <xsd:element name="department">
                <xsd:complexType>
                    <xsd:sequence>
                        <xsd:element name="dname" type="xsd:string"/>
                        <xsd:element name="deptphoneno" type="xsd:long"/>
                        <xsd:element name="deptfaxno" type="xsd:int"/>
                        <xsd:element name="deptemail" type="xsd:string"/>
                        <xsd:element name="employee">
                            <xsd:complexType>
                                <xsd:sequence>
                                    <xsd:element name="empid" type="xsd:int"/>
                                    <xsd:element name="ename" type="xsd:string"/>
                                    <xsd:element name="emailid" type="xsd:string"/>
                                    <xsd:element name="phoneno" type="xsd:long"/>
                                </xsd:sequence>
                            </xsd:complexType>
                        </xsd:element>
                        <xsd:element name="contractemployee">
                            <xsd:complexType>
                                <xsd:sequence>
                                    <xsd:element name="name" type="xsd:string"/>
                                    <xsd:element name="phoneno" type="xsd:long"/>
                                </xsd:sequence>
                            </xsd:complexType>
                        </xsd:element>
                    </xsd:sequence>
                </xsd:complexType>
            </xsd:element>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</xsd:schema>

Body:
You were pretty close to the answer. According to the E-R diagram, there is 1- many mandatory relationship between department and employee while 1-many optional relationship between department and contract employee. Whenever there is optional relationship, we use minOccurs="0".

I'm posting both the XML & XSD so you can understand it better.
XML

<?xml version="1.0" encoding="UTF-8"?>
<company
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='companyxsd.xsd'>
    <companyname>Capgemini</companyname>
    <address>Mumbai</address>
    <department>
        <dname>Operations</dname>
        <deptphoneno>987610</deptphoneno>
        <deptfaxno>223654</deptfaxno>
        <deptemail>op@gmail.com</deptemail>
        <employee>
            <empid>20</empid>
            <ename>Mukesh</ename>
            <emailid>mukesh@gmail.com</emailid>
            <phoneno>967642</phoneno>
        </employee>
        <contractemployee>
            <name>Ramesh</name>
            <phoneno>25643</phoneno>
        </contractemployee>
    </department>
</company>

The XSD for this XML:
XSD

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"></xs:element>
<xs:element name="address" type="xs:string"></xs:element>
<xs:element name="department" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"></xs:element>
<xs:element name="deptphoneno" type="xs:long"></xs:element>
<xs:element name="deptfaxno" type="xs:long"></xs:element>
<xs:element name="deptemail" type="xs:string"></xs:element>

<xs:element name="employee" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:int"></xs:element>
<xs:element name="ename" type="xs:string"></xs:element>
<xs:element name="emailid" type="xs:string"></xs:element>
<xs:element name="phoneno" type="xs:long"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="contractemployee" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"></xs:element>
<xs:element name="phoneno" type="xs:long"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:sequence>
</xs:complexType>
</xs:element>

</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Hope this helps you :)


来源: stackexchange

问:
How to save websocket frames in Chrome
I am logging websocket traffic using Chrome/Developer Tools. I have no problem to view the websocket frames in network "Frames" window, but I can not save all frames (content enc. as JSON) in an external (text) file.
I have already tried save as HAR and also simply used cntl A,C,V (first "page" copied only) but have so far not been very successful.

I am running Linux Mint 17.

Do you have hints how this can be done?

答:
Update for Chrome 63, January 2018

I managed to export them as JSON as this:

detach an active inspector (if necessary)

start an inspector on the inspector with ctrl-shift-j/cmd-opt-j

paste the following code into that inspector instance.

At this point, you can do whatever you want with the frames. I used the console.save utility from https://bgrins.github.io/devtools-snippets/#console-save to save the frames as a JSON file (included in the snippet below).

```<code>// https://bgrins.github.io/devtools-snippets/#console-save
(function(console){
  console.save = function(data, filename){
    if(!data) {
      console.error('Console.save: No data')
      return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
      data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
    e = document.createEvent('MouseEvents'),
    a = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
  }
})(console)

// Frame/Socket message counter + filename
var iter = 0;

// This replaces the browser's `webSocketFrameReceived` code with the original code
// and adds two lines, one to save the socket message and one to increment the counter.
SDK.NetworkDispatcher.prototype.webSocketFrameReceived = function (requestId, time, response) {
  var networkRequest = this._inflightRequestsById[requestId];
  if (!networkRequest) return;
  console.save(JSON.parse(response.payloadData), iter + ".json")
  iter++;
  networkRequest.addFrame(response, time, false);
  networkRequest.responseReceivedTime = time;
  this._updateNetworkRequest(networkRequest);
}
</code>```

This will save all incoming socket frames to your default download location.

ContentLicense: CC BY-SA 3.0

Title: How to save websocket frames in Chrome

Body:
Update for Chrome 63, January 2018

I managed to export them as JSON as this:

detach an active inspector (if necessary)

start an inspector on the inspector with ctrl-shift-j/cmd-opt-j

paste the following code into that inspector instance.

At this point, you can do whatever you want with the frames. I used the console.save utility from https://bgrins.github.io/devtools-snippets/#console-save to save the frames as a JSON file (included in the snippet below).

// https://bgrins.github.io/devtools-snippets/#console-save
(function(console){
  console.save = function(data, filename){
    if(!data) {
      console.error('Console.save: No data')
      return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
      data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
    e = document.createEvent('MouseEvents'),
    a = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
  }
})(console)

// Frame/Socket message counter + filename
var iter = 0;

// This replaces the browser's `webSocketFrameReceived` code with the original code
// and adds two lines, one to save the socket message and one to increment the counter.
SDK.NetworkDispatcher.prototype.webSocketFrameReceived = function (requestId, time, response) {
  var networkRequest = this._inflightRequestsById[requestId];
  if (!networkRequest) return;
  console.save(JSON.parse(response.payloadData), iter + ".json")
  iter++;
  networkRequest.addFrame(response, time, false);
  networkRequest.responseReceivedTime = time;
  this._updateNetworkRequest(networkRequest);
}

This will save all incoming socket frames to your default download location.

ContentLicense: CC BY-SA 4.0


问:
Django Programming error column does not exist even after running migrations
I run python manage.py makemigrations and I get:
    No changes detected
Then, python manage.py migrate and I get:
    No migrations to apply.

Then, I try to push the changes to production:
    git push heroku master
    Everything up-to-date

Then, in production, I repeat the command:
    heroku run python manage.py migrate
    No migrations to apply.

Just in case, I run makemigrations in production:

```<code>heroku run python manage.py makemigrations
No changes detected
</code>```

WHY then I get a

```<code>ProgrammingError at ....

column .... does not exist
</code>```

"No changes detected" means the database is coherent with the code.
How can I debug this?¡?

答: I had a similar issue - the error message appeared when I clicked on the model on the django-admin site. I solved it by commenting out the field in models.py, then running migrations. Following this I uncommented the field and re ran the migrations. After that the error message disappeared.</p>

Body:
I run python manage.py makemigrations and I get:
    No changes detected
Then, python manage.py migrate and I get:
    No migrations to apply.

Then, I try to push the changes to production:
    git push heroku master
    Everything up-to-date

Then, in production, I repeat the command:
    heroku run python manage.py migrate
    No migrations to apply.

Just in case, I run makemigrations in production:

heroku run python manage.py makemigrations
No changes detected

WHY then I get a

ProgrammingError at ....

column .... does not exist

"No changes detected" means the database is coherent with the code.
How can I debug this?¡?


问:
SQL error: login failed for user 'domain\user'
I have looked at many posts on this issue, but for me all the proposed solutions didnt work. I am trying to access a database with a remote user, so I am setting the connection credentials as needed. I get the error as shown in the subject of this post. I have checked all the permissions, things like that, windows/sql authentication, etc. Any quick ideas of another potential problem?</p>

答: Presuming the user has the permission, and you have entered the password correctly as you say, then another thing to look at would be to ensure the user is authorized to access the database remotely.</p>


问:
Testing method which contains Scanner (TestNG)
I'm stuck with testing method that require user input. Here are my methods in IOHandler class:

```<code>Callable<Integer> getNumber = new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        try {
            return scanner.nextInt();
        } catch (InputMismatchException e) {
            writeOut("Bad params !\n");
            scanner.nextLine();
        }
        return call();
    }
};

 Optional<Object> handleIOAndGetInput(Callable function) {
    try {
        return Optional.ofNullable(function.call());
    } catch (IOException e) {
        System.err.println("Stream doesn't work");
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
    return Optional.empty();
}
</code>```

This is method in my Test class:

```<code>@Test
public void shouldTakeUserInput() {
    IOHandler ioHandler=new IOHandler();
    Assert.assertEquals((ioHandler.handleIOAndGetInput(ioHandler.getNumber)).orElse(null), 5);
}
</code>```

So I red some of similar posts, but I cound't find answear to my problem. Everything I red was about faking input right into assert, but in my case I have to feed this scanner inside Callable getNumber. Looking forward to any tips about it. Thanks in advance!

答:
unfortunately this is an instance where you need to stub in the information or use a framework that will stub it in for you

try Mockito

this is a normal issue with java dev.

Body:
I'm stuck with testing method that require user input. Here are my methods in IOHandler class:

Callable<Integer> getNumber = new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        try {
            return scanner.nextInt();
        } catch (InputMismatchException e) {
            writeOut("Bad params !\n");
            scanner.nextLine();
        }
        return call();
    }
};

 Optional<Object> handleIOAndGetInput(Callable function) {
    try {
        return Optional.ofNullable(function.call());
    } catch (IOException e) {
        System.err.println("Stream doesn't work");
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
    return Optional.empty();
}

This is method in my Test class:

@Test
public void shouldTakeUserInput() {
    IOHandler ioHandler=new IOHandler();
    Assert.assertEquals((ioHandler.handleIOAndGetInput(ioHandler.getNumber)).orElse(null), 5);
}

So I red some of similar posts, but I cound't find answear to my problem. Everything I red was about faking input right into assert, but in my case I have to feed this scanner inside Callable getNumber. Looking forward to any tips about it. Thanks in advance!


问:
primefaces selectonemenu change event not working for null value
I have a selectonemenu that includes some items. And a null item for showing "please choose one"..
MY goal is to query some data when I select one of them. And if i select the "please choose one" do another thing.

But eventually, the change event is fired for normal values but if I select "please choose one" item , it is not fired. Thanks for your help. Here is my code.

```<code><p:selectOneMenu style="width: 200px" id="positionForward" value="#{hrProcessController.queryCriteria.positionForward}" converter="listConverter"
                                             effect="fade" var="u" filter="true" filterMatchMode="startsWith" validator="#{hrProcessController.isOpenPositionForwValid}">
                                <f:selectItem itemLabel="#{menu['onemenu.choose']}" itemValue="#{null}"/>
                                <f:selectItems value="#{hrProcessController.positionList}" var="position" itemLabel="#{position.name}" itemValue="#{position}" />
                                <p:ajax event="change" listener="#{hrProcessController.onPositionSelect}" update="openPositionForward"/>

                                <p:column>
                                    <h:outputText value="#{u==null ? menu['onemenu.choose'] : u.name}" />
                                </p:column>
</p:selectOneMenu>

public void onPositionSelect()
{
    if(queryCriteria.getPositionForward()!=null)
    {
        OpenPositionQueryCriteria criteria = new OpenPositionQueryCriteria();
        criteria.setPosition(queryCriteria.getPositionForward());
        List<OpenPosition> openPositions = openPositionService.searchOpenPosition(criteria);
        setOpenPositionList(openPositions);
    }
    else
    {
        List<OpenPosition> positions = openPositionService.getActiveOpenPositionList();
        setOpenPositionList(positions);
    }
}
</code>```

答:
If you use itemValue="#{null}" or itemValue="", the valueChangeListener method never will be called.

That's a better approach if you want your first item null:

```<code>        <f:selectItem
            itemDisabled="true"
            itemLabel="#{null}"
            itemValue="#{null}" />
</code>```

Body:
I have a selectonemenu that includes some items. And a null item for showing "please choose one"..
MY goal is to query some data when I select one of them. And if i select the "please choose one" do another thing.

But eventually, the change event is fired for normal values but if I select "please choose one" item , it is not fired. Thanks for your help. Here is my code.

                                <f:selectItem itemLabel="#{menu['onemenu.choose']}" itemValue="#{null}"/>
                                <f:selectItems value="#{hrProcessController.positionList}" var="position" itemLabel="#{position.name}" itemValue="#{position}" />

                                    <h:outputText value="#{u==null ? menu['onemenu.choose'] : u.name}" />

public void onPositionSelect()
{
    if(queryCriteria.getPositionForward()!=null)
    {
        OpenPositionQueryCriteria criteria = new OpenPositionQueryCriteria();
        criteria.setPosition(queryCriteria.getPositionForward());
        List<OpenPosition> openPositions = openPositionService.searchOpenPosition(criteria);
        setOpenPositionList(openPositions);
    }
    else
    {
        List<OpenPosition> positions = openPositionService.getActiveOpenPositionList();
        setOpenPositionList(positions);
    }
}

Body:
If you use itemValue="#{null}" or itemValue="", the valueChangeListener method never will be called.

That's a better approach if you want your first item null:

        <f:selectItem
            itemDisabled="true"
            itemLabel="#{null}"
            itemValue="#{null}" />


问:
Rails - Delegate method to last record in has_many relation
I have a model with A with a has_many B model association.
I would like to do something like this in my A model:

```<code>def my_method
 self.bs.last.my_method
end
</code>```

In other words, I would like to delegate my_method to my last B object in the association. Is that possible to achieve with delegate? Think it would be more elegant. Thank you!

答:
I think you can do that if you create a method to return the last 'bs' object:

```<code>def last_bs
  self.bs.last
end
</code>```

then delegate:

```<code>delegate :my_method, to: :last_bs
</code>```

UPDATE: This can also be achieved by:

```<code>delegate :my_method, to: "bs.last", allow_nil: true
</code>```

Body:
I have a model with A with a has_many B model association.
I would like to do something like this in my A model:

def my_method
 self.bs.last.my_method
end

In other words, I would like to delegate my_method to my last B object in the association. Is that possible to achieve with delegate? Think it would be more elegant. Thank you!

Body:
I think you can do that if you create a method to return the last 'bs' object:

def last_bs
  self.bs.last
end

then delegate:

delegate :my_method, to: :last_bs

UPDATE: This can also be achieved by:

delegate :my_method, to: "bs.last", allow_nil: true


问:
Is there a SASS.js? Something like LESS.js?
I have used LESS.js before. It's easy to use, something like

```<code><link rel="stylesheet/less" href="main.less" type="text/css">
<script src="less.js" type="text/javascript"></script>
</code>```

I saw SASS.js. How can I use it in a similar way? Parsing a SASS file for use immediately in HTML. It seems like SASS.js is more for use with Node.js?

```<code>var sass = require('sass')
sass.render('... string of sass ...')
// => '... string of css ...'

sass.collect('... string of sass ...')
// => { selectors: [...], variables: { ... }, mixins: { ... }}
</code>```

答:
There is no officially sanctioned JavaScript implementation of sass or scss. There are a couple of implementations in progress that I've seen, but none that I can recommend using at this time.

However, please a few points:

Why should you make all your users compile your stylesheets when you can do it once for all of them.

What would your site look like if JavaScript is disabled.

If you decide to change to a server-side implementation at a future time, all your templates must be changed accordingly.

So while it's a little more setup to get started, we (the sass core team) think that server side compilation is the best long term approach. Similarly, the less developers prefer server side compilation for production stylesheets.

Body:
I have used LESS.js before. It's easy to use, something like

<link rel="stylesheet/less" href="main.less" type="text/css">

I saw SASS.js. How can I use it in a similar way? Parsing a SASS file for use immediately in HTML. It seems like SASS.js is more for use with Node.js?

var sass = require('sass')
sass.render('... string of sass ...')
// => '... string of css ...'

sass.collect('... string of sass ...')
// => { selectors: [...], variables: { ... }, mixins: { ... }}


问:
I can't use Delete key to delete a character (its normal functioning) in Vim on tmux
I played around with tmux config. I love tmux and I don't want to stop using it, but for some reason the delete key doesn't delete anymore. It deletes a character and works normally in vim, but not in vim when opened from tmux. Backspace works fine. Just the delete key stopped working only in vim running on tmux. Any ideas? </p>

答:
You may need to remap the delete key in your .vimrc. For instance, like this:

```<code>inoremap ^? <c-h>
cnoremap ^? <c-h>

" Debian-specific variation
inoremap <esc>[3~ <c-h>
cnoremap <esc>[3~ <c-h>
</code>```

I have both of these in my .vimrc, and have for years, and it's worked everywhere for me. With or without tmux.

I will note though that the ^? in the first two lines is NOT the characters ^ and ?, it is a single embedded delete character. The way to insert this is to edit your .vimrc with vim, and use this sequence to insert it:

Press CtrlV, then press Delete.

If done properly, Vim should show it to you as a ^?, but it is a single character in the file. The rest of the lines are typed exactly as they are shown.

This will remap the delete key to send backspace, and you can use them interchangeably.

Body:
You may need to remap the delete key in your .vimrc. For instance, like this:

inoremap ^? <c-h>
cnoremap ^? <c-h>

" Debian-specific variation
inoremap <esc>[3~ <c-h>
cnoremap <esc>[3~ <c-h>

I have both of these in my .vimrc, and have for years, and it's worked everywhere for me. With or without tmux.

I will note though that the ^? in the first two lines is NOT the characters ^ and ?, it is a single embedded delete character. The way to insert this is to edit your .vimrc with vim, and use this sequence to insert it:

Press CtrlV, then press Delete.

If done properly, Vim should show it to you as a ^?, but it is a single character in the file. The rest of the lines are typed exactly as they are shown.

This will remap the delete key to send backspace, and you can use them interchangeably.


问:
Best way to perform mutually exclusive selection in a tableview in different sections in swift 3
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

```<code>   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }
</code>```

答:
Ok, so I figured it out, I created a method that would loop and check through all the rows and called it in both tableview didselect and deselect</p>

```<code>func updateTableViewSelections(selectedIndex:IndexPath)
    {

        for  i in 0  ..< tableView.numberOfSections
        {
            for k in 0  ..< tableView.numberOfRows(inSection: i)
            {

                if let cell = tableView.cellForRow(at: IndexPath(row: k, section: i))

                {

                    if sections.getType(index: i) == selectedIndex.section
                    {
                        if (selectedIndex.row == k && cell.isSelected)
                        {
                            cell.setSelected(cell.isSelected, animated: false)
                        }
                        else
                        {
                            cell.setSelected(false, animated: false)
                        }
                    }
                }

            }
        }

    }
</code>```

Body:
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }

Body:
Ok, so I figured it out, I created a method that would loop and check through all the rows and called it in both tableview didselect and deselect

func updateTableViewSelections(selectedIndex:IndexPath)
    {

        for  i in 0  ..< tableView.numberOfSections
        {
            for k in 0  ..< tableView.numberOfRows(inSection: i)
            {

                if let cell = tableView.cellForRow(at: IndexPath(row: k, section: i))

                {

                    if sections.getType(index: i) == selectedIndex.section
                    {
                        if (selectedIndex.row == k && cell.isSelected)
                        {
                            cell.setSelected(cell.isSelected, animated: false)
                        }
                        else
                        {
                            cell.setSelected(false, animated: false)
                        }
                    }
                }

            }
        }

    }


问:
How to export VARCHAR2 data that includes commas(!) to Excel from MSSQLMgmtStudio(2012)
First, a grumble: MS builds SQL Server Studio AND Excel, but can't make one save in the standard format of the other?

OK, I'm a data analyst, but not allowed to change/mod either the data or structures directly. So full READ, but no WRITE.

I'm trying to do a dump so I can do some of this analysis offline, as I have no remote access either.

So one VARCHAR2 column in this table is for comments on the purchase of the asset being described/tracked. Of course, there are commas. The only export types built into SQL Server Studio are .csv and .txt, and .csv just turns into a mess when 'comma' is included as a delimiter.

So after an hour or so of screwing around with this, (including reading a thread on methods for excluding the one column from a SELECT while still exporting the other 221 columns in the table, without having to write them all out manually (fun reading, impressive, but means I'd have to figure out which of them actually works, and then still export the one column separately and insert it in the Excel separately)) I am throwing this problem on the pile at StackOverflow.

Someone else must have worked around this frustration of the .csv format as export VS the commas embedded in 'comment' text.
Any help would be appreciated.

答:
Why don't you simply select all data in ssms result window, then copy and then paste in a blank excel file?
It should copy paste all data in correct format including comma valued fields in single column.

Try that.


问:
Disable shortcuts in Access 2013
Is their a way to disable default keyboard shortcuts in Access 2013's forms? Like disabling ctrl+s = save record?

答:
Only method I found to disable ctrl+p was with an AutoKeys macro. Perhaps the same is true for cmd+s.

However, not seeing cmd+ referenced in https://support.office.com/en-us/article/Run-an-Access-macro-by-using-a-keyboard-shortcut-0D267570-D3DA-46EB-9BFB-A3C81AF676BE

Did you perhaps mean ctrl+s?

Title: Disable shortcuts in Access 2013


问:
What is the best way in PHP or JS to expand shortened URLs like Bitly, Tinyurl to find the original URL?
I am using the Twitter and Facewbook API to pull posts that potentially contain shortened URLs using bit.ly or TinyURL like services. I need to do a real-time expansion to get the original URL then pull content from that URL into my app.</p>

答:
You can just use PHP and CURL to connect to the URL and get back the Location parameter:

Here is what comes back -

```<code>> $ curl -I http://bit.ly/2V6CFi
> HTTP/1.1 301 Moved Server:
> nginx/0.7.67 Date: Tue, 21 Dec 2010
> 01:58:47 GMT Content-Type: text/html;
> charset=utf-8 Connection: keep-alive
> Set-Cookie:
> _bit=4d1009d7-00298-02f7f-c6ac8fa8;domain=.bit.ly;expires=Sat
> Jun 18 21:58:47 2011;path=/; HttpOnly
> Cache-control: private; max-age=90
> Location: http://www.google.com/
> MIME-Version: 1.0

Content-Length: 284
</code>```

So you can look for the Location parameter in the header to see where the page page actually goes.

ContentLicense: CC BY-SA 2.5

Body:
You can just use PHP and CURL to connect to the URL and get back the Location parameter:

Here is what comes back -

> $ curl -I http://bit.ly/2V6CFi
> HTTP/1.1 301 Moved Server:
> nginx/0.7.67 Date: Tue, 21 Dec 2010
> 01:58:47 GMT Content-Type: text/html;
> charset=utf-8 Connection: keep-alive
> Set-Cookie:
> _bit=4d1009d7-00298-02f7f-c6ac8fa8;domain=.bit.ly;expires=Sat
> Jun 18 21:58:47 2011;path=/; HttpOnly
> Cache-control: private; max-age=90
> Location: http://www.google.com/
> MIME-Version: 1.0

Content-Length: 284

So you can look for the Location parameter in the header to see where the page page actually goes.


问:
merging fields from pivot table to prep mail merge
I am prepping a mail merge to notify interested parties of entities that there has been an address change. I extracted all information fine and have it in Excel. The problem is, there is a ton is data and some emails have multiple entities. I have attached an example of this.

Is there anyway to get the email and corresponding entities in cells right next to each other? (total of 2 cells for each set)

i.e. from

 TO
.

答:
Try this:

```<code>Sub Sum()
Dim i As Integer, j As Integer, size As Integer, Bound As Integer: size = 0
Dim lRow As Long
Dim sht As Worksheet
Dim arr() As Variant, arr2() As Variant
Dim data As String

Set sht = Worksheets("Sheet1") 'Adjust

lRow = sht.Cells(sht.Rows.Count, 2).End(xlUp).Row

For i = 1 To lRow
    If sht.Cells(i, 1).Value <> "" Then
        ReDim Preserve arr(size)
        arr(size) = i
        size = size + 1
    End If
Next
arr2 = sht.Range("A1:B" & lRow)
sht.Range("A1:B" & lRow).Columns.Clear
For i = 0 To UBound(arr)
    If i + 1 > UBound(arr) Then
        Bound = lRow
    Else
        Bound = arr(i + 1) - 1
    End If
    For j = arr(i) To Bound
        If j = Bound Then
            data = data & arr2(j, 2)
        Else
            data = data & arr2(j, 2) & vbNewLine
        End If
    Next j
    sht.Cells(i + 1, 1).Value = arr2(arr(i), 1)
    sht.Cells(i + 1, 2).Value = data
    data = ""
Next i
End Sub
</code>```

Input:

Output:

So what it does basically is, that i go trough Col A and get the rows of the emails. Then it store the data in an array and deletes the content of the columns. Finally it will then go trough the array (it uses the first array to get the index of the second array) and give out the desired format.

Body:
Try this:

Sub Sum()
Dim i As Integer, j As Integer, size As Integer, Bound As Integer: size = 0
Dim lRow As Long
Dim sht As Worksheet
Dim arr() As Variant, arr2() As Variant
Dim data As String

Set sht = Worksheets("Sheet1") 'Adjust

lRow = sht.Cells(sht.Rows.Count, 2).End(xlUp).Row

For i = 1 To lRow
    If sht.Cells(i, 1).Value <> "" Then
        ReDim Preserve arr(size)
        arr(size) = i
        size = size + 1
    End If
Next
arr2 = sht.Range("A1:B" & lRow)
sht.Range("A1:B" & lRow).Columns.Clear
For i = 0 To UBound(arr)
    If i + 1 > UBound(arr) Then
        Bound = lRow
    Else
        Bound = arr(i + 1) - 1
    End If
    For j = arr(i) To Bound
        If j = Bound Then
            data = data & arr2(j, 2)
        Else
            data = data & arr2(j, 2) & vbNewLine
        End If
    Next j
    sht.Cells(i + 1, 1).Value = arr2(arr(i), 1)
    sht.Cells(i + 1, 2).Value = data
    data = ""
Next i
End Sub

Input:

Output:

So what it does basically is, that i go trough Col A and get the rows of the emails. Then it store the data in an array and deletes the content of the columns. Finally it will then go trough the array (it uses the first array to get the index of the second array) and give out the desired format.


问:
C# Design of the transparent form
There are some problems and design of the transparent form:
1. I can not move form over an empty form-space
2. I can move the form by letters, but not even for the label
3. The text is distorted against a light background, if it is light.
4. The text is distorted on a dark background, if it is dark.

If you help, I attach the file with the corrected design, can anyone need it.

答:
GDI+ only allows to mask one color and to smoothly render text, you need more than one color.

Is Windows Forms really necessary? You may want to switch to WPF, which supports full transparency.

Title: C# Design of the transparent form


问:
Side loading instant app failed: Reading bundle timed out
Unable to use Android Emulator, for testing the Instant Apps!! Every-time I'm getting "Side loading instant app failed: Reading bundle timed out."

I'm using, Android Studio 3.0 Canary-5

Emulator: Nexus 5X image running Android 6.0 (API level 23), x86, with Google APIs. Google APIs Intel x86 Atom System Image (Revision 21)

Note: After updating Android Studio 3.0 (Canary-4 > Canary-5) &
  Emulator system image from revision (20 > 21). I'm unable to run the
  instant App through emulator. Always I'm getting the error message saying "Side loading instant app failed: Reading bundle timed out."

```<code>com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                                at tey.get(:com.google.android.gms:1)
                                                                                at tir.a(:com.google.android.gms:25)
                                                                                at tir.a(:com.google.android.gms:16)
                                                                                at tir.a(:com.google.android.gms:9)
                                                                                at tir.b(:com.google.android.gms:0)
                                                                                at tio.b(:com.google.android.gms:0)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:14)
                                                                                at tiu.run(:com.google.android.gms:0)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at awjn.c(:com.google.android.gms:0)
                                                                                at lbb.a(:com.google.android.gms:97)
                                                                                at tem.b(:com.google.android.gms:43)
                                                                                at tem.a(:com.google.android.gms:0)
                                                                                at tez.call(:com.google.android.gms:1)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)

    W/ActivityManager: Unable to start service Intent { act=com.google.android.instantapps.devman.iapk.LOAD cmp=com.google.android.instantapps.devman/.iapk.IapkLoadService (has extras) } U=0: not found
</code>```

Appreciate your help.

Update:

Found solution in Android studio release notes here. This is a known-issue under Android Studio canary-5.

Reliability issue with instant app provisioning cache. If you manually
  unprovision your device or emulator image for instant app development,
  and then deploy the instant app from Android Studio, the deployment
  will fail because Android Studio will not provision your
  device/emulator image again. To workaround for this issue: Go into the
  Run Configuration dialog and select the instantapp module on the
  left-hand pane. Click the “Instant App Provision” task under “Before
  launch:Gradle-aware Make, Instant App Provision” Click the edit (the
  pencil icon) Check “Clear provisioned devices cache”

答:
devman.apk is missing under sdk/extras/google/instantapps/tools/apks/debug folder. Please sideload it manually before running your instant app:

```<code>adb install /path/to/android/sdk/extras/google/instantapps/tools/apks/release/devman.apk
</code>```

Body:
Unable to use Android Emulator, for testing the Instant Apps!! Every-time I'm getting "Side loading instant app failed: Reading bundle timed out."

I'm using, Android Studio 3.0 Canary-5

Emulator: Nexus 5X image running Android 6.0 (API level 23), x86, with Google APIs. Google APIs Intel x86 Atom System Image (Revision 21)

Note: After updating Android Studio 3.0 (Canary-4 > Canary-5) &
  Emulator system image from revision (20 > 21). I'm unable to run the
  instant App through emulator. Always I'm getting the error message saying "Side loading instant app failed: Reading bundle timed out."

com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                                at tey.get(:com.google.android.gms:1)
                                                                                at tir.a(:com.google.android.gms:25)
                                                                                at tir.a(:com.google.android.gms:16)
                                                                                at tir.a(:com.google.android.gms:9)
                                                                                at tir.b(:com.google.android.gms:0)
                                                                                at tio.b(:com.google.android.gms:0)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:14)
                                                                                at tiu.run(:com.google.android.gms:0)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at awjn.c(:com.google.android.gms:0)
                                                                                at lbb.a(:com.google.android.gms:97)
                                                                                at tem.b(:com.google.android.gms:43)
                                                                                at tem.a(:com.google.android.gms:0)
                                                                                at tez.call(:com.google.android.gms:1)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)

    W/ActivityManager: Unable to start service Intent { act=com.google.android.instantapps.devman.iapk.LOAD cmp=com.google.android.instantapps.devman/.iapk.IapkLoadService (has extras) } U=0: not found

Appreciate your help.

Update:

Found solution in Android studio release notes here. This is a known-issue under Android Studio canary-5.

Reliability issue with instant app provisioning cache. If you manually
  unprovision your device or emulator image for instant app development,
  and then deploy the instant app from Android Studio, the deployment
  will fail because Android Studio will not provision your
  device/emulator image again. To workaround for this issue: Go into the
  Run Configuration dialog and select the instantapp module on the
  left-hand pane. Click the “Instant App Provision” task under “Before
  launch:Gradle-aware Make, Instant App Provision” Click the edit (the
  pencil icon) Check “Clear provisioned devices cache”

Body:
devman.apk is missing under sdk/extras/google/instantapps/tools/apks/debug folder. Please sideload it manually before running your instant app:

adb install /path/to/android/sdk/extras/google/instantapps/tools/apks/release/devman.apk


问:
Combinations and Permutations in F#
I've recently written the following combinations and permutations functions for an F# project, but I'm quite aware they're far from optimised.

```<code>/// Rotates a list by one place forward.
let rotate lst =
    List.tail lst @ [List.head lst]

/// Gets all rotations of a list.
let getRotations lst =
    let rec getAll lst i = if i = 0 then [] else lst :: (getAll (rotate lst) (i - 1))
    getAll lst (List.length lst)

/// Gets all permutations (without repetition) of specified length from a list.
let rec getPerms n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> getRotations |> Seq.collect (fun r -> Seq.map ((@) [List.head r]) (getPerms (k - 1) (List.tail r)))

/// Gets all permutations (with repetition) of specified length from a list.
let rec getPermsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> Seq.collect (fun x -> Seq.map ((@) [x]) (getPermsWithRep (k - 1) lst))
    // equivalent: | k, _ -> lst |> getRotations |> Seq.collect (fun r -> List.map ((@) [List.head r]) (getPermsWithRep (k - 1) r))

/// Gets all combinations (without repetition) of specified length from a list.
let rec getCombs n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombs (k - 1) xs)) (getCombs k xs)

/// Gets all combinations (with repetition) of specified length from a list.
let rec getCombsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombsWithRep (k - 1) lst)) (getCombsWithRep k xs)
</code>```

Does anyone have any suggestions for how these functions (algorithms) can be sped up? I'm particularly interested in how the permutation (with and without repetition) ones can be improved. The business involving rotations of lists doesn't look too efficient to me in retrospect.

Update

Here's my new implementation for the getPerms function, inspired by Tomas's answer.

Unfortunately, it's not really any fast than the existing one. Suggestions?

```<code>let getPerms n lst =
    let rec getPermsImpl acc n lst = seq {
        match n, lst with
        | k, x :: xs ->
            if k > 0 then
                for r in getRotations lst do
                    yield! getPermsImpl (List.head r :: acc) (k - 1) (List.tail r)
            if k >= 0 then yield! getPermsImpl acc k []
        | 0, [] -> yield acc
        | _, [] -> ()
        }
    getPermsImpl List.empty n lst
</code>```

答:
If you want to write efficient functional code, then it is a good idea to avoid using the @ operator, because concatentation of lists is very inefficient.

Here is an example of how you can write a function to generate all combinations:

```<code>let rec combinations acc size set = seq {
  match size, set with
  | n, x::xs ->
      if n > 0 then yield! combinations (x::acc) (n - 1) xs
      if n >= 0 then yield! combinations acc n xs
  | 0, [] -> yield acc
  | _, [] -> () }

combinations [] 3 [1 .. 4]
</code>```

The parameters of the function are:

acc is used to remember elements that are already selected to be included in the combination (initially this is an empty list)

size is the remaining number of elements that we need to add to acc (initially this is the required size of the combinations)

set is the set elements to choose from

The function is implemented using a simple recursion. If we need to generate combinations of size n then we can either add or don't add the current element, so we try to generate combinations using both options (first case) and add all of them to the generated sequence using yield!. If we need 0 more elements, then we successfuly generated a combination (second case) and if we end with some other number but don't have any remaining elements to use then we cannot return anything (last case).

Combinations with repetition would be similar - the difference is that you don't need to remove the elements from the list (by using just xs in the recursive calls) so there are more options of what to do.

Title: Combinations and Permutations in F#

Body:
I've recently written the following combinations and permutations functions for an F# project, but I'm quite aware they're far from optimised.

/// Rotates a list by one place forward.
let rotate lst =
    List.tail lst @ [List.head lst]

/// Gets all rotations of a list.
let getRotations lst =
    let rec getAll lst i = if i = 0 then [] else lst :: (getAll (rotate lst) (i - 1))
    getAll lst (List.length lst)

/// Gets all permutations (without repetition) of specified length from a list.
let rec getPerms n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> getRotations |> Seq.collect (fun r -> Seq.map ((@) [List.head r]) (getPerms (k - 1) (List.tail r)))

/// Gets all permutations (with repetition) of specified length from a list.
let rec getPermsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, _ -> lst |> Seq.collect (fun x -> Seq.map ((@) [x]) (getPermsWithRep (k - 1) lst))
    // equivalent: | k, _ -> lst |> getRotations |> Seq.collect (fun r -> List.map ((@) [List.head r]) (getPermsWithRep (k - 1) r))

/// Gets all combinations (without repetition) of specified length from a list.
let rec getCombs n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombs (k - 1) xs)) (getCombs k xs)

/// Gets all combinations (with repetition) of specified length from a list.
let rec getCombsWithRep n lst =
    match n, lst with
    | 0, _ -> seq [[]]
    | _, [] -> seq []
    | k, (x :: xs) -> Seq.append (Seq.map ((@) [x]) (getCombsWithRep (k - 1) lst)) (getCombsWithRep k xs)

Does anyone have any suggestions for how these functions (algorithms) can be sped up? I'm particularly interested in how the permutation (with and without repetition) ones can be improved. The business involving rotations of lists doesn't look too efficient to me in retrospect.

Update

Here's my new implementation for the getPerms function, inspired by Tomas's answer.

Unfortunately, it's not really any fast than the existing one. Suggestions?

let getPerms n lst =
    let rec getPermsImpl acc n lst = seq {
        match n, lst with
        | k, x :: xs ->
            if k > 0 then
                for r in getRotations lst do
                    yield! getPermsImpl (List.head r :: acc) (k - 1) (List.tail r)
            if k >= 0 then yield! getPermsImpl acc k []
        | 0, [] -> yield acc
        | _, [] -> ()
        }
    getPermsImpl List.empty n lst

Body:
If you want to write efficient functional code, then it is a good idea to avoid using the @ operator, because concatentation of lists is very inefficient.

Here is an example of how you can write a function to generate all combinations:

let rec combinations acc size set = seq {
  match size, set with
  | n, x::xs ->
      if n > 0 then yield! combinations (x::acc) (n - 1) xs
      if n >= 0 then yield! combinations acc n xs
  | 0, [] -> yield acc
  | _, [] -> () }

combinations [] 3 [1 .. 4]

The parameters of the function are:

acc is used to remember elements that are already selected to be included in the combination (initially this is an empty list)

size is the remaining number of elements that we need to add to acc (initially this is the required size of the combinations)

set is the set elements to choose from

The function is implemented using a simple recursion. If we need to generate combinations of size n then we can either add or don't add the current element, so we try to generate combinations using both options (first case) and add all of them to the generated sequence using yield!. If we need 0 more elements, then we successfuly generated a combination (second case) and if we end with some other number but don't have any remaining elements to use then we cannot return anything (last case).

Combinations with repetition would be similar - the difference is that you don't need to remove the elements from the list (by using just xs in the recursive calls) so there are more options of what to do.


问:
How to undo a successful "git cherry-pick"?
On a local repo, I've just executed git cherry-pick SHA without any conflicts or problems. I then realized I didn't want to do what I just did. I have not pushed this anywhere.

How can I remove just this cherry pick?

I'd like to know if there's a way to do this:

when I have other local changes

when I have no other local changes

Preferably with one command for both cases if possible.

答:
If possible, avoid hard resets. Hard resets are one of the very few destructive operations in git. Luckily, you can undo a cherry-pick without resets and avoid anything destructive.

Note the hash of the cherry-pick you want to undo, say it is ${bad_cherrypick}. Do a git revert ${bad_cherrypick}. Now the contents of your working tree are as they were before your bad cherry-pick.

Repeat your git cherry-pick ${wanted_commit}, and when you're happy with the new cherry-pick, do a git rebase -i ${bad_cherrypick}~1. During the rebase, delete both ${bad_cherrypick} and its corresponding revert.

The branch you are working on will only have the good cherry-pick. No resets needed!


问:
How to create real function in Bigquery Legacy SQL
I know UDF in legacy sql, but UDF need you pass whole row into function, and return whole record, and UDF can't put into select section, this is not real function I need, Is Bigquery Legacy SQL can write function like Standard SQL? (can put into select or where section)

thanks :)

答: This functionality is only supported in Standard SQL (and as Elliott mentions in the comments, is unlikely to be added to Legacy SQL because it is being phased out).</p>


问:
Selecting block of code in Visual Studio Code
Is there a keyboard shortcut or an extension that would allow me to select a block of code?

I'd like to select everything between curly braces, between HTML tags, etc.

答: Try the expand-region extension. It currently works for JavaScript and HTML. To select ever-increasing or decreasing scope.</p>


问:
Combine XML Files using PHP
Trying to combine the two xml files using php and then save a new merged xml.

http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml and http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml

```<code><FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>
</code>```

and

```<code><FCDMC>
<rpt_info created="07-06-2017 11:23"/>
<return_rain id="770" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
</code>```

Want the output to look like this

```<code><FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>
</code>```

I am trying to write the PHP script but it has been unsuccesful.  I am not getting any results or errors. XML is blank http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml as is the php http://alert.fcd.maricopa.gov/alert/Google/v3/php/merge_test.php.Here is the sript.

```<code>$doc1 = new DOMDocument();
$doc1->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml');

$doc2 = new DOMDocument();
$doc2->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml');

// get 'res' element of document 1
$res1 = $doc1->getElementsByTagName('gage_rain')->item(0); //edited res - items

// iterate over 'item' elements of document 2
$items2 = $doc2->getElementsByTagName('return_rain');
for ($i = 0; $i < $items2->length; $i ++) {
    $item2 = $items2->item($i);

    // import/copy item from document 2 to document 1
    $item1 = $doc1->importNode($item2, true);

    // append imported item to document 1 'res' element
    $res1->appendChild($item1);

}
$doc1->save('http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml'); //edited -added saving into xml file
</code>```

Anyone know what is wrong here??  I would like the php to save the desired output as a new merged xml file at location http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml.

答:
Since you need to merge attributes from the rain nodes in both XML, consider XSLT, the special-purpose XML transformation language. With XSLT's document() function, you can parse from an external saved file in a current or subdirectory relative to the xsl script.

PHP can run XSLT 1.0 scripts  with the php-xsl class which is enabled as an extension in .ini file. No for loops or if logic needed for this approach.

XSLT (save as .xsl file in same directory: alert.fcd.maricopa.gov/alert/Google/xml/) or embed as a PHP string)

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/FCDMC">
    <xsl:copy>
      <xsl:copy-of select="rpt_info"/>
      <xsl:apply-templates select="gage_rain"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="gage_rain">
    <xsl:copy>
        <xsl:variable name="curr_id" select="@id"/>
        <xsl:copy-of select="@*"/>
        <xsl:copy-of select="document('fcdmc_alert_return.xml')/FCDMC/return_rain[@id=$curr_id]/@*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

PHP (load only the first XML as XSL handles the second XML)

```<code>// Load the XML source and XSLT file
$cd = dirname(__FILE__);
$doc = new DOMDocument();
$doc->load($cd.'/fcdmc_alert_rain_v3.xml');

$xsl = new DOMDocument;
$xsl->load($cd.'/XSLT_Script.xsl');           // OR $xsl->loadXML($xslstr);

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

// Transform XML source
$newXml = $proc->transformToXML($doc);

// Save output to file
$xmlfile = $cd.'/merged.xml';
file_put_contents($xmlfile, $newXml);
</code>```

Output

```<code><?xml version="1.0"?>
<FCDMC>
  <rpt_info created="07-06-2017  11:39"/>
  <gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" name="Tat Momolikot Dam [TM]" lat="  32.65120" long="-111.92830" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="775" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.69" rainscore="1" name="Gila R. @ Maricopa Rd. [SP]" lat="  33.17076" long="-112.00601" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="780" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.22" rainscore="1" name="Gila River at Olberg [SP]" lat="  33.08706" long="-111.68700" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="785" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="2.13" rainscore="1" name="Santa Cruz R. @ SR 84 [SP]" lat="  32.87952" long="-111.82895" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="795" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="0.43" rainscore="1" name="Greene Wash @ SR 84 [SP]" lat="  32.87946" long="-111.93369" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  ...
</code>```

Title: Combine XML Files using PHP

Body:
Trying to combine the two xml files using php and then save a new merged xml.

http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml and http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml

<FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>

and

<FCDMC>
<rpt_info created="07-06-2017 11:23"/>
<return_rain id="770" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>

Want the output to look like this

<FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>

I am trying to write the PHP script but it has been unsuccesful.  I am not getting any results or errors. XML is blank http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml as is the php http://alert.fcd.maricopa.gov/alert/Google/v3/php/merge_test.php.Here is the sript.

$doc1 = new DOMDocument();
$doc1->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml');

$doc2 = new DOMDocument();
$doc2->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml');

// get 'res' element of document 1
$res1 = $doc1->getElementsByTagName('gage_rain')->item(0); //edited res - items

// iterate over 'item' elements of document 2
$items2 = $doc2->getElementsByTagName('return_rain');
for ($i = 0; $i < $items2->length; $i ++) {
    $item2 = $items2->item($i);

    // import/copy item from document 2 to document 1
    $item1 = $doc1->importNode($item2, true);

    // append imported item to document 1 'res' element
    $res1->appendChild($item1);

}
$doc1->save('http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml'); //edited -added saving into xml file

Anyone know what is wrong here??  I would like the php to save the desired output as a new merged xml file at location http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml.

Body:
Since you need to merge attributes from the rain nodes in both XML, consider XSLT, the special-purpose XML transformation language. With XSLT's document() function, you can parse from an external saved file in a current or subdirectory relative to the xsl script.

PHP can run XSLT 1.0 scripts  with the php-xsl class which is enabled as an extension in .ini file. No for loops or if logic needed for this approach.

XSLT (save as .xsl file in same directory: alert.fcd.maricopa.gov/alert/Google/xml/) or embed as a PHP string)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/FCDMC">
    <xsl:copy>
      <xsl:copy-of select="rpt_info"/>
      <xsl:apply-templates select="gage_rain"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="gage_rain">
    <xsl:copy>
        <xsl:variable name="curr_id" select="@id"/>
        <xsl:copy-of select="@*"/>
        <xsl:copy-of select="document('fcdmc_alert_return.xml')/FCDMC/return_rain[@id=$curr_id]/@*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

PHP (load only the first XML as XSL handles the second XML)

// Load the XML source and XSLT file
$cd = dirname(__FILE__);
$doc = new DOMDocument();
$doc->load($cd.'/fcdmc_alert_rain_v3.xml');

$xsl = new DOMDocument;
$xsl->load($cd.'/XSLT_Script.xsl');           // OR $xsl->loadXML($xslstr);

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

// Transform XML source
$newXml = $proc->transformToXML($doc);

// Save output to file
$xmlfile = $cd.'/merged.xml';
file_put_contents($xmlfile, $newXml);

Output

<?xml version="1.0"?>
<FCDMC>
  <rpt_info created="07-06-2017  11:39"/>
  <gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" name="Tat Momolikot Dam [TM]" lat="  32.65120" long="-111.92830" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="775" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.69" rainscore="1" name="Gila R. @ Maricopa Rd. [SP]" lat="  33.17076" long="-112.00601" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="780" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.22" rainscore="1" name="Gila River at Olberg [SP]" lat="  33.08706" long="-111.68700" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="785" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="2.13" rainscore="1" name="Santa Cruz R. @ SR 84 [SP]" lat="  32.87952" long="-111.82895" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  <gage_rain id="795" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="0.43" rainscore="1" name="Greene Wash @ SR 84 [SP]" lat="  32.87946" long="-111.93369" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>
  ...


问:
Why doesn't Internet explorer 11 object support property or method 'findIndex'
I have an array of objects from which I need to find a particular index and then delete the corresponding object from the array.

I used the findIndex() method :

```<code>var index = data.findIndex(x => x.OBJECTID == objectID);
data.splice(index, 1);
</code>```

This works fine in Chrome but in IE 11, it throws

object doesn't support property or method 'findIndex'

I solved this by using the solution from this stackoverflow answer:   findIndex() method issue with internet explorer

On inspecting the console log, I noticed a difference between the array of objects in Chrome and IE 11:

In IE 11, the console log, the array of objects is :
enter image description here

while in Chrome, it's:
enter image description here

Notice that the objects in Chrome are of type object but in IE, they're of type [object object]. Is that why the findIndex() method fails? If so, why is the type different and if not, why does the findIndex() fail in IE 11?

答:
I believe your issue is not only findIndex, but also I.E. doesn't support lambda functions.

Using a for loop is inevitable for IE support. Or you can use lodash version of findIndex

```<code>var users = [
    { 'user': 'barney',  'active': false },
    { 'user': 'fred',    'active': false },
    { 'user': 'pebbles', 'active': true }
 ];

_.findIndex(users, function(o) { return o.user == 'barney'; });
</code>```

Body:
I have an array of objects from which I need to find a particular index and then delete the corresponding object from the array.

I used the findIndex() method :

var index = data.findIndex(x => x.OBJECTID == objectID);
data.splice(index, 1);

This works fine in Chrome but in IE 11, it throws

object doesn't support property or method 'findIndex'

I solved this by using the solution from this stackoverflow answer:   findIndex() method issue with internet explorer

On inspecting the console log, I noticed a difference between the array of objects in Chrome and IE 11:

In IE 11, the console log, the array of objects is :
enter image description here

while in Chrome, it's:
enter image description here

Notice that the objects in Chrome are of type object but in IE, they're of type [object object]. Is that why the findIndex() method fails? If so, why is the type different and if not, why does the findIndex() fail in IE 11?

Body:
I believe your issue is not only findIndex, but also I.E. doesn't support lambda functions.

Using a for loop is inevitable for IE support. Or you can use lodash version of findIndex

var users = [
    { 'user': 'barney',  'active': false },
    { 'user': 'fred',    'active': false },
    { 'user': 'pebbles', 'active': true }
 ];

_.findIndex(users, function(o) { return o.user == 'barney'; });


问:
Creating polymorphic associations has_many/has_one
I have two rails models - Shipments and Notes.
Notes is a polymorphic association with a body and status.

A shipment can have many notes. (has_many :notes, as: :notable)

However, I'd also like to create a has_one relationship in Shipments to show the most recent note with a status that isn't null.

I've tried a few different things but with no luck, including the code below. Anyone know how I can do this? I'm using ruby on rails 4. Please let me know if I can provide any other information.

has_one :last_note_with_status, -> {
  where('notes.notable_type = Shipment')
  .where('notes.status is not null')
  .order(created_at: :desc) }, class_name: 'Note'

答:
You don't have the foreign key...

```<code>has_one :last_note_with_status,
  -> { where(notable_type: 'Shipment').where.not(status: nil) },
  class_name: 'Note',
  foreign_key: :notable_id
</code>```

This will give you a single record.  From the sounds of what you are wanting, something like this might work:

```<code>  scope: :last_unresolved, joins(:notes)
     .where('notes.created_at = (SELECT MAX(notes.created_at) FROM notes WHERE notes.notable_id = shipments.id AND notes.notable_type = "Shipment")')
     .where('notes.status NOT IN (?)', ["Delivered", "Resolved"])
     .where('shipments.status NOT IN (?)', ["Delivered", "Resolved"])
     .group('shipments.id')
</code>```

Untested, but you can try something like this

Body:
You don't have the foreign key...

has_one :last_note_with_status,
  -> { where(notable_type: 'Shipment').where.not(status: nil) },
  class_name: 'Note',
  foreign_key: :notable_id

This will give you a single record.  From the sounds of what you are wanting, something like this might work:

  scope: :last_unresolved, joins(:notes)
     .where('notes.created_at = (SELECT MAX(notes.created_at) FROM notes WHERE notes.notable_id = shipments.id AND notes.notable_type = "Shipment")')
     .where('notes.status NOT IN (?)', ["Delivered", "Resolved"])
     .where('shipments.status NOT IN (?)', ["Delivered", "Resolved"])
     .group('shipments.id')

Untested, but you can try something like this


问:
C# - using List<T>.Find() with custom objects
I'm trying to use a List<T> with a custom class of mine, and being able to use methods like Contains(), Find(), etc., on the list. I thought I'd just have to overload the operator == but apparently, one way of doing that is to use a delegate method with the Find()...

Note: Right now, I've overloaded the Equals() method to get the Contains() method to work, but I still couldn't get the Find() function to work.

What would be the best way of getting both to work?

I'm using the latest C# /.NET framework version with mono, on linux.

edit: Here's my code

```<code>using System;
namespace GuerreDesClans
{
public class Reponse : IEquatable<Reponse>
{
    public Reponse ()
    {
        m_statement = string.Empty;
        m_pointage = 0;
    }

    public Reponse (string statement, int pointage)
    {
        m_pointage = pointage;
        m_statement = statement;
    }

    /*
     * attributs privés
     */

    private string m_statement;
    private int m_pointage;

    /*
     * properties
     */

    public string Statement {
        get { return m_statement; }
        set { m_statement = value; }
    }

    public int Pointage {
        get { return m_pointage; }
        set { m_pointage = value; }
    }

    /*
     * Equatable
     */

    public bool Equals (Reponse other)
    {
        if (this.m_statement == other.m_statement)
            return true;
        else
            return false;
    }
}
</code>```

}

and how I would like to search my Reponse objects using the find() function...

```<code>list.find("statement1"); // would return a Reponse object
</code>```

答:
You can use find with a Predicate as follows:

```<code>list.Find(x => x.Id == IdToFind);
</code>```

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

Body:
I'm trying to use a List<T> with a custom class of mine, and being able to use methods like Contains(), Find(), etc., on the list. I thought I'd just have to overload the operator == but apparently, one way of doing that is to use a delegate method with the Find()...

Note: Right now, I've overloaded the Equals() method to get the Contains() method to work, but I still couldn't get the Find() function to work.

What would be the best way of getting both to work?

I'm using the latest C# /.NET framework version with mono, on linux.

edit: Here's my code

using System;
namespace GuerreDesClans
{
public class Reponse : IEquatable<Reponse>
{
    public Reponse ()
    {
        m_statement = string.Empty;
        m_pointage = 0;
    }

    public Reponse (string statement, int pointage)
    {
        m_pointage = pointage;
        m_statement = statement;
    }

    /*
     * attributs privés
     */

    private string m_statement;
    private int m_pointage;

    /*
     * properties
     */

    public string Statement {
        get { return m_statement; }
        set { m_statement = value; }
    }

    public int Pointage {
        get { return m_pointage; }
        set { m_pointage = value; }
    }

    /*
     * Equatable
     */

    public bool Equals (Reponse other)
    {
        if (this.m_statement == other.m_statement)
            return true;
        else
            return false;
    }
}

}

and how I would like to search my Reponse objects using the find() function...

list.find("statement1"); // would return a Reponse object

Body:
You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).


问:
How do I execute "use dbname" over Oracle dblink to Sybase?
How do I access tables in my user schema in Sybase from Oracle?

In isql I can do

```<code>use mydb
go
</code>```

How do I select from mydb tables from Oracle using dblink NITSYB5?

This does not work:

```<code>select count(*) from  "mydb"."lon_client_confirm_exec"@NITSYB5;
</code>```

Error:

```<code>ORA-00942: table or view does not exist
[Oracle][ODBC Sybase Wire Protocol driver][SQL Server]"mydb"."lon_client_confirm_exec" not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
 {42S02,NativeErr = 208}
ORA-02063: preceding 3 lines from NITSYB5
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 3 Column: 30
</code>```

答:
NOTE: I don't work with Oracle and hence know nothing about Oracle's dblink, so fwiw ...

In Sybase ASE the fully qualified table name format is: <dbname>.<owner>.

If you leave out the <owner> then the optimizer will first look for tables owned by the user running the query, then look for tables owned by dbo.

In your example it appears you've left out the <owner>.  If the table is owned by your user or dbo then I'd suggest you try adding an additional period, eg:

```<code>select count(*) from mydb..lon_client_confirm_exec@NITSYB5;
</code>```

NOTE: Add quotes as/if needed by Oracle's dblink.

Body:
How do I access tables in my user schema in Sybase from Oracle?

In isql I can do

use mydb
go

How do I select from mydb tables from Oracle using dblink NITSYB5?

This does not work:

select count(*) from  "mydb"."lon_client_confirm_exec"@NITSYB5;

Error:

ORA-00942: table or view does not exist
[Oracle][ODBC Sybase Wire Protocol driver][SQL Server]"mydb"."lon_client_confirm_exec" not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
 {42S02,NativeErr = 208}
ORA-02063: preceding 3 lines from NITSYB5
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 3 Column: 30

Body:
NOTE: I don't work with Oracle and hence know nothing about Oracle's dblink, so fwiw ...

In Sybase ASE the fully qualified table name format is: <dbname>.<owner>.<table>

If you leave out the <owner> then the optimizer will first look for tables owned by the user running the query, then look for tables owned by dbo.

In your example it appears you've left out the <owner>.  If the table is owned by your user or dbo then I'd suggest you try adding an additional period, eg:

select count(*) from mydb..lon_client_confirm_exec@NITSYB5;

NOTE: Add quotes as/if needed by Oracle's dblink.


问:
Why is https being forced locally?
I recently added in a simple config.force_ssl to my production.rb after obtaining a certificate. Added nothing to development.rb.

I pushed this up to production, and tried running locally, but now https is being forced on localhost:3000.

So I first tried modifying config.force_ssl to config.force_ssl = true unless Rails.env.development?. Keep in mind, this line only exists within production.rb. Still being forced.

Then I tried commenting the line out completely. Still being forced.

I restarted the server each time.

I'm starting the server with foreman. My procfile is:

```<code>web: rails s -p 3000
client: sh -c 'rm app/assets/webpack/* || true && cd client && bundle exec rake react_on_rails:locale && yarn run build:development'
</code>```

Was something cached the first time I did this?

Is the client portion of my Procfile doing something?

答:
This is due to your browser cache, try cleaning your cache and App data or use different browser.

If once your localhost is in https, then it will still use https unless browser cache and data removed.

You can also change port where rails application is running.

Title: Why is https being forced locally?

Body:
I recently added in a simple config.force_ssl to my production.rb after obtaining a certificate. Added nothing to development.rb.

I pushed this up to production, and tried running locally, but now https is being forced on localhost:3000.

So I first tried modifying config.force_ssl to config.force_ssl = true unless Rails.env.development?. Keep in mind, this line only exists within production.rb. Still being forced.

Then I tried commenting the line out completely. Still being forced.

I restarted the server each time.

I'm starting the server with foreman. My procfile is:

web: rails s -p 3000
client: sh -c 'rm app/assets/webpack/* || true && cd client && bundle exec rake react_on_rails:locale && yarn run build:development'

Was something cached the first time I did this?

Is the client portion of my Procfile doing something?


问:
Access: After Running my VBA code data get split in two records
Ok guys, I'm somewhat new to Access and VBA and I need some help. I've been trying to figure out a problem I'm having my database is suppose to save all the data entered into a form onto a table my when i try to save it splits the record. I have tried everything but can't get it to work.

Just FYI the form auto populates: Name, Phone and Email when ID is entered and Equipment when Tag # is entered.

Here is my VBA Code

```<code>Option Compare Database

Private Sub Submit_button_Click()
Dim db As Database
Dim rec As Recordset

Set db = CurrentDb

Set rec = db.OpenRecordset("student_check_out")

rec.AddNew
rec("ID") = Me.PID
rec("Student Name") = Me.Borrower
rec("Phone") = Me.PHONE
rec("E-mail") = Me.EMAIL
rec("Tag #") = Me.Tag
rec("Equipment") = Me.Equipment
rec("Class") = Me.Class
rec("CDL Staff") = Me.CDL_Staff
rec("Check Out Date") = Me.Check_Out_Date
rec.Update
rec.Close

DoCmd.Close acForm, "Students"

End Sub
</code>```

答: I assume the form is not bound. "Class" is a reserved word (see it highlighted "blue" in the code). Please rename the textbox, even if it's "Class_" or "Class1", etc.</p>

Body:
Ok guys, I'm somewhat new to Access and VBA and I need some help. I've been trying to figure out a problem I'm having my database is suppose to save all the data entered into a form onto a table my when i try to save it splits the record. I have tried everything but can't get it to work.

Just FYI the form auto populates: Name, Phone and Email when ID is entered and Equipment when Tag # is entered.

Here is my VBA Code

Option Compare Database

Private Sub Submit_button_Click()
Dim db As Database
Dim rec As Recordset

Set db = CurrentDb

Set rec = db.OpenRecordset("student_check_out")

rec.AddNew
rec("ID") = Me.PID
rec("Student Name") = Me.Borrower
rec("Phone") = Me.PHONE
rec("E-mail") = Me.EMAIL
rec("Tag #") = Me.Tag
rec("Equipment") = Me.Equipment
rec("Class") = Me.Class
rec("CDL Staff") = Me.CDL_Staff
rec("Check Out Date") = Me.Check_Out_Date
rec.Update
rec.Close

DoCmd.Close acForm, "Students"

End Sub


问:
Using CUDA with Visual Studio 2017
I'm trying to install CUDA, but I get a message saying "No supported version of visual studio was found". I think that this is because I am using Visual Studio 2017 (Community), and CUDA currently only supports up to Visual Studio 2015. Unfortunately, Microsoft will not allow me to download old versions of Visual Studio without paying a subscription fee.

Is there a way I can get around the compatibility issue with VS 2017, or can I not use CUDA?

答:
If you want to install CUDA 8.0 with Visual Studio 2017 you need to install additional components for Visual Studio 2017.

Click on the Start Menu and type Visual Studio Installer. Open Visual Studio Installer

Open Individual components tab and select VC++ 2015.3 v140 toolset

under Compilers, build tools and runtimes.

You also need to install .NET Framework 3.5 if you didn't have it installed.
 Nvda.Build.CudaTasks.v8.0.dll assembly dependents on MS .NET Framework 3.5.

Open Classical Control Panel, go to Programs and features
and press Turn Windows features on or off. Check .NET Framework 3.5 and press OK.

Download full CUDA toolkit distribution and extract it somewhere on your disk.

If you didn't have CUDA toolkit installed, do it now. If you have only Visual Studio 2017 installed, unselect Visual Studio integration checkbox.

Now you want to receive the "No supported version of the visual studio was found" error.

But in order to successfully build Cuda toolkit projects in Visual Studio 2017, you also need to follow steps 5 and 6.

Go to the CUDAVisualStudioIntegration\extras\visual_studio_integration\MSBuildExtensions
folder in your extracted distribution, copy all the files and paste them to
 C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140\BuildCustomizations:

In the last step, you will need to edit your Cuda projects to recognize NVidia's build tasks from Visual Studio 2017. Open your .vcxproj file in a text editor and find all occurrences of CUDA 8.0.props. Replace the macro at the beginning of the string with $(VCTargetsPath14) so that XML snippet would look as follows:

<ImportGroup Label="ExtensionSettings">
      <Import Project="$(VCTargetsPath14)\BuildCustomizations\CUDA 8.0.props" /></ImportGroup>

Don't forget to edit the custom targets path at the end of the file:

<ImportGroup Label="ExtensionTargets">
      <Import Project="$(VCTargetsPath14)\BuildCustomizations\CUDA 8.0.targets" /></ImportGroup>

Make sure to double check your path conifuration!

If you use nvcc from command prompt you might not be calling cl.exe from Visual Studio folder!

Now you can build your Cuda project from Visual Studio 2017.

Parts of this solution are from Oleg Tarasov blog.

Title: Using CUDA with Visual Studio 2017


问:
How to remove all duplicate items from a list
How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.

For example, in my code below, the list lseparatedOrbList has 12 items - one is repeated six times, one is repeated five times, and there is only one instance of one. I want it to change the list so there are only three items - one of each, and in the same order they appeared before. I tried this:

```<code>for i in lseparatedOrbList:
   for j in lseparatedOrblist:
        if lseparatedOrbList[i] == lseparatedOrbList[j]:
            lseparatedOrbList.remove(lseparatedOrbList[j])
</code>```

But I get the error:

```<code>Traceback (most recent call last):
  File "qchemOutputSearch.py", line 123, in <module>
    for j in lseparatedOrblist:
NameError: name 'lseparatedOrblist' is not defined
</code>```

I'm guessing because it's because I'm trying to loop through lseparatedOrbList while I loop through it, but I can't think of another way to do it.

答:
There is a faster way to fix this:</p>

```<code>list = [1, 1.0, 1.41, 1.73, 2, 2, 2.0, 2.24, 3, 3, 4, 4, 4, 5, 6, 6, 8, 8, 9, 10]
list2=[]

for value in list:
    try:
        list2.index(value)
    except:
        list2.append(value)
list.clear()
for value in list2:
    list.append(value)
list2.clear()
print(list)
print(list2)
</code>```

Body:
How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.

For example, in my code below, the list lseparatedOrbList has 12 items - one is repeated six times, one is repeated five times, and there is only one instance of one. I want it to change the list so there are only three items - one of each, and in the same order they appeared before. I tried this:

for i in lseparatedOrbList:
   for j in lseparatedOrblist:
        if lseparatedOrbList[i] == lseparatedOrbList[j]:
            lseparatedOrbList.remove(lseparatedOrbList[j])

But I get the error:

Traceback (most recent call last):
  File "qchemOutputSearch.py", line 123, in <module>
    for j in lseparatedOrblist:
NameError: name 'lseparatedOrblist' is not defined

I'm guessing because it's because I'm trying to loop through lseparatedOrbList while I loop through it, but I can't think of another way to do it.

Body:
There is a faster way to fix this:

list = [1, 1.0, 1.41, 1.73, 2, 2, 2.0, 2.24, 3, 3, 4, 4, 4, 5, 6, 6, 8, 8, 9, 10]
list2=[]

for value in list:
    try:
        list2.index(value)
    except:
        list2.append(value)
list.clear()
for value in list2:
    list.append(value)
list2.clear()
print(list)
print(list2)