问:
Counting likes in firebase
I'm new at Firebase and I fall into two difficulties right now.

Part of my web-app load photos and collect 'likes - ♥' for them

This is my simple structure in Realtime Database, this is a simplified model:

```<code>"photos": {
  "-h42Z1w9wD4G7AtPcdPb": {
    "author": "9f0f5c90-fa9c-47b9-9757-4fecf640e78c",
    "path": "/images/9932988.jpg"
  },
  "-d9n0ME8H7zYvCBu9pf3": {
    "author": "5db561db-56f9-4d5b-8b32-30d487c03dbf",
    "path": "/images/9865733.jpg"
  },
  <...>
}

"likes": {
  "-s2kEFg6U02KzKf8w0Hi": {
    "from": "9f0f5c90-fa9c-47b9-9757-4fecf640e78c",
    "to": "-d9n0ME8H7zYvCBu9pf3"
  },
  "-rh186npGIuXqZ58KX3v": {
    "from": "5db561db-56f9-4d5b-8b32-30d487c03dbf",
    "to": "-h42Z1w9wD4G7AtPcdPb"
  }
  <...>
}
</code>```

How can I count ON THE BACKEND how many 'likes' put a user with id "9f0f5c90-fa9c-47b9-9757-4fecf640e78c", or how many 'likes' got a photo with id "-s2kEFg6U02KzKf8w0Hi"?

I load 10 photos with query.limitToLast(10). How can I load next 10 photos: from last 11 to 20, then from 21 to 30 for my pagination?

答:
I used to be perplexed with the same thing as you. Thank God for Cloud Functions for Firebase now!

Check out this sample on Github that shows you how to count the number of children and update the counter in a transaction. Though, I would like to add that Cloud Functions are still in Beta.

Title: Counting likes in firebase

Body:
I'm new at Firebase and I fall into two difficulties right now.

Part of my web-app load photos and collect 'likes - ♥' for them

This is my simple structure in Realtime Database, this is a simplified model:

"photos": {
  "-h42Z1w9wD4G7AtPcdPb": {
    "author": "9f0f5c90-fa9c-47b9-9757-4fecf640e78c",
    "path": "/images/9932988.jpg"
  },
  "-d9n0ME8H7zYvCBu9pf3": {
    "author": "5db561db-56f9-4d5b-8b32-30d487c03dbf",
    "path": "/images/9865733.jpg"
  },
  <...>
}

"likes": {
  "-s2kEFg6U02KzKf8w0Hi": {
    "from": "9f0f5c90-fa9c-47b9-9757-4fecf640e78c",
    "to": "-d9n0ME8H7zYvCBu9pf3"
  },
  "-rh186npGIuXqZ58KX3v": {
    "from": "5db561db-56f9-4d5b-8b32-30d487c03dbf",
    "to": "-h42Z1w9wD4G7AtPcdPb"
  }
  <...>
}

How can I count ON THE BACKEND how many 'likes' put a user with id "9f0f5c90-fa9c-47b9-9757-4fecf640e78c", or how many 'likes' got a photo with id "-s2kEFg6U02KzKf8w0Hi"?

I load 10 photos with query.limitToLast(10). How can I load next 10 photos: from last 11 to 20, then from 21 to 30 for my pagination?


来源: stackexchange

问:
sorting list items alphabetically
I have a simple unordered list i.e. a menu (with two levels of submenus). I want its submenus (and submenus of these submenus) to be displayed alphabetically from top to down. The HTML code for the menu is as follows:

```<code>    <div id="sidebar2" class="sidebar" >
         <ul class="goo-collapsible goo-coll-stacked">
           <li class="header">Information Systems</li>
         </ul>
      <div >

       <div id="nav">
         <ul id="navList">

            <li><a href="#">Other Databases and Portals</a>
    <!-- This is the sub nav -->
              <ul class="listTab">
                 <li ><a href='http://www.icar.org.in/rohudatabase/index.php' target="_blank">Rohu Database</a></li>
            <li ><a href='http://117.240.114.67/weedid/aiwsweedident.aspx' target="_blank">Weed Seed Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/cwsmainweeds.aspx' target="_blank">Weed Seedling Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/bwiweedident.aspx' target="_blank">Weed Identification</a></li>

            <li ><a href='http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href='http://www.cropweatheroutlook.in' target="_blank">Crop Weather Outlook: AICRPAM tools</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/formfish/index.html' target="_blank">Automated Species Identification System</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/ornamental/home.aspx' target="_blank">Marine ornamental finfishes and shell fishes</a></li>
            <li ><a href='http://210.212.93.85/agris/breed.aspx' target="_blank">Animal Genetic Resources of India</a></li>
            <li ><a href='http://www.ncipm.org.in/cropsap2014/login.aspx' target="_blank">Crop Pest Surveillance and Advisory</a></li>
            <li ><a href='http://www.ncipm.org.in/ICTMalawi/' target="_blank">ICT Based Pest Surveillance</a></li>
            <li ><a href='http://ctcri.in/statistics/FormsCEI.aspx' target="_blank">TUBER CROPS STATISTICS</a></li>

            <li ><a href='http://www.crijaf.org.in/SideLinks/QuickLinks/AgrometeorologicalData.html' target="_blank">Agrometeorological Data at ICAR-CRIJA</a></li>
            <li ><a href=' http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href=' http://nrcgrapes.nic.in/weather_forecast_based_grape_adv.htm' target="_blank">Weather forecast based grape advice</a></li>
            <li ><a href='http://research.ciphet.in/' target="_blank">Post-Harvest Machinery</a></li>
            <li ><a href='http://cift.res.in/innercontent.php?contentid=NjA=' target="_blank">CIFT Knowledge Base</a></li>
            <li ><a href='http://nrce.nic.in/breeds.php' target="_blank">Equine Breeds of India</a></li>
    </ul>
  </li>
  <li><a href="#">Genetic Resources Portals</a>
    <!-- This is the sub nav -->
    <ul class="listTab">
     <li ><a href='http://www.mgrportal.org.in/' target="_blank">Microbial Genetic Resources Portal</a></li>
            <li ><a href='http://www.nbpgr.ernet.in/PGR_Databases.aspx' target="_blank">PGR Database</a></li>
            <li ><a href='http://www.nbpgr.ernet.in:8080/PGRPortal/(S(fzkcby45lxboum2hufans255))/default.aspx' target="_blank">PGR Portal</a></li>
            <li ><a href='http://210.212.93.85/agrportal/index.htm' target="_blank">Animal Genetic Resources Portal</a></li>
            <li ><a href='http://www.sugarcane.res.in/index.php/en/resrch/genetic-resources' target="_blank">Sugarcane Genetic Resources</a></li>
    </ul>
  </li>
  </div>
  </div>
  <div style="margin-top: 65px;">
  <ul class="goo-collapsible goo-coll-stacked">
    <li class="header">Latest News</li>
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">
    <li><a href="PDF/Digitization AICRPs Information.pdf" target="_blank" >Digitization AICRPs Information</a></li>
    <li><a href="PDF/Draft Format for Technology Database.pdf" >Draft Format for Technology Database</a></li>
    <li><a href="PDF/ICAR Guidelines Research Papers 2014.pdf" >ICAR Guidelines Research Papers 2014</a></li>
    <li><a href="PDF/Letter for Nomination of Nodal officers.pdf" >Letter for Nomination of Nodal officers</a></li>
    <li><a href="PDF/Mapping of Natural Resources.pdf" >Mapping of Natural Resources</a></li>
    <li><a href="JavaScript:display('Circular');" >Circular</a></li>
    </marquee>
    </ul>
    </div>
</div>
</code>```

here the div whose menu I want to be sorted is the one with id=nav (rest are header and footer of the menu).
Please aid me over the matter.

答:
Sorting HTML collections might be troublesome, but I think I could solve this interesting task for you. Well, the idea is to convert collections into arrays and sort arrays since sorting within objects/collections is senseless in JS.

Then we just recreate the whole structure based on sorted arrays and insert it into the page instead of the previous one. The HTML part is just your html input. In JS part I used Jquery. sortItems(arr) is a helper function. I use jQuery.map to convert collections of list objects into arrays of list objects. You have 1 level of nesting here and I introduced new property on the outer li - arrayChildren - to store the nested lists as arrays. In the end, I just iterate through my array and recreate the nested lists from arrayChildren property.

Well, it solves what you asked for although the functionality is quite basic.

$(document).ready(function() {
    function sortItems(arr) {
        arr.sort(function(el1, el2) {
            if(el1.childNodes[0].innerText > el2.childNodes[0].innerText) return 1;
            if(el1.childNodes[0].innerText < el2.childNodes[0].innerText) return -1;
            return 0;
        });
    }
    var items = jQuery.map( $("#nav ul#navList > li"), function( el ) {
        return el;
    });
    for(var i = 0; i < items.length; i++) {
        items[i].arrayChildren = jQuery.map( items[i].childNodes[4].children, function( el ) {
            return el;
        });
        sortItems(items[i].arrayChildren);
    }
    sortItems(items);
    var docfrag = document.createDocumentFragment();
    $.each( items, function( key, value ) {
        var ul = $("ul").addClass("listTab");
        $.each( value.arrayChildren, function( key, val ) {
            $(value).find("ul.listTab").append(val);
        });
        $(docfrag).append(value);
    });
    $("#nav ul#navList").append(docfrag);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar2" class="sidebar" >
         <ul class="goo-collapsible goo-coll-stacked">
           <li class="header">Information Systems</li>
         </ul>
      <div >

       <div id="nav">
         <ul id="navList">

            <li>Other Databases and Portals
    <!-- This is the sub nav -->
              <ul class="listTab">
                 <li >Rohu Database</li>
            <li >Weed Seed Identification</li>
            <li >Weed Seedling Identification</li>
            <li >Weed Identification</li>

            <li >Crop Pest DSS</li>
            <li >Crop Weather Outlook: AICRPAM tools</li>
            <li >Automated Species Identification System</li>
            <li >Marine ornamental finfishes and shell fishes</li>
            <li >Animal Genetic Resources of India</li>
            <li >Crop Pest Surveillance and Advisory</li>
            <li >ICT Based Pest Surveillance</li>
            <li >TUBER CROPS STATISTICS</li>

            <li >Agrometeorological Data at ICAR-CRIJA</li>
            <li >Crop Pest DSS</li>
            <li >Weather forecast based grape advice</li>
            <li >Post-Harvest Machinery</li>
            <li >CIFT Knowledge Base</li>
            <li >Equine Breeds of India</li>
    </ul>
  </li>
  <li>Genetic Resources Portals
    <!-- This is the sub nav -->
    <ul class="listTab">
     <li >Microbial Genetic Resources Portal</li>
            <li >PGR Database</li>
            <li >PGR Portal</li>
            <li >Animal Genetic Resources Portal</li>
            <li >Sugarcane Genetic Resources</li>
    </ul>
  </li>
  </div>
  </div>
  <div style="margin-top: 65px;">
  <ul class="goo-collapsible goo-coll-stacked">
    <li class="header">Latest News</li>
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">
    <li>Digitization AICRPs Information</li>
    <li>Draft Format for Technology Database</li>
    <li>ICAR Guidelines Research Papers 2014</li>
    <li>Letter for Nomination of Nodal officers</li>
    <li>Mapping of Natural Resources</li>
    <li>Circular</li>
    </marquee>
    </ul>
    </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: sorting list items alphabetically

Body:
I have a simple unordered list i.e. a menu (with two levels of submenus). I want its submenus (and submenus of these submenus) to be displayed alphabetically from top to down. The HTML code for the menu is as follows:

Information Systems

Other Databases and Portals

Rohu Database

Weed Seed Identification

Weed Seedling Identification

Weed Identification

Crop Pest DSS

Crop Weather Outlook: AICRPAM tools

Automated Species Identification System

Marine ornamental finfishes and shell fishes

Animal Genetic Resources of India

Crop Pest Surveillance and Advisory

ICT Based Pest Surveillance

TUBER CROPS STATISTICS

Agrometeorological Data at ICAR-CRIJA

Crop Pest DSS

Weather forecast based grape advice

Post-Harvest Machinery

CIFT Knowledge Base

Equine Breeds of India

Genetic Resources Portals

Microbial Genetic Resources Portal

PGR Database

PGR Portal

Animal Genetic Resources Portal

Sugarcane Genetic Resources

Latest News

    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">

Digitization AICRPs Information

Draft Format for Technology Database

ICAR Guidelines Research Papers 2014

Letter for Nomination of Nodal officers

Mapping of Natural Resources

Circular

    </marquee>

here the div whose menu I want to be sorted is the one with id=nav (rest are header and footer of the menu).
Please aid me over the matter.

Body:
Sorting HTML collections might be troublesome, but I think I could solve this interesting task for you. Well, the idea is to convert collections into arrays and sort arrays since sorting within objects/collections is senseless in JS.

Then we just recreate the whole structure based on sorted arrays and insert it into the page instead of the previous one. The HTML part is just your html input. In JS part I used Jquery. sortItems(arr) is a helper function. I use jQuery.map to convert collections of list objects into arrays of list objects. You have 1 level of nesting here and I introduced new property on the outer li - arrayChildren - to store the nested lists as arrays. In the end, I just iterate through my array and recreate the nested lists from arrayChildren property.

Well, it solves what you asked for although the functionality is quite basic.

$(document).ready(function() {
    function sortItems(arr) {
        arr.sort(function(el1, el2) {
            if(el1.childNodes[0].innerText > el2.childNodes[0].innerText) return 1;
            if(el1.childNodes[0].innerText < el2.childNodes[0].innerText) return -1;
            return 0;
        });
    }
    var items = jQuery.map( $("#nav ul#navList > li"), function( el ) {
        return el;
    });
    for(var i = 0; i < items.length; i++) {
        items[i].arrayChildren = jQuery.map( items[i].childNodes[4].children, function( el ) {
            return el;
        });
        sortItems(items[i].arrayChildren);
    }
    sortItems(items);
    var docfrag = document.createDocumentFragment();
    $.each( items, function( key, value ) {
        var ul = $("ul").addClass("listTab");
        $.each( value.arrayChildren, function( key, val ) {
            $(value).find("ul.listTab").append(val);
        });
        $(docfrag).append(value);
    });
    $("#nav ul#navList").append(docfrag);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar2" class="sidebar" >
         <ul class="goo-collapsible goo-coll-stacked">
           <li class="header">Information Systems</li>
         </ul>
      <div >

       <div id="nav">
         <ul id="navList">

            <li><a href="#">Other Databases and Portals</a>
    <!-- This is the sub nav -->
              <ul class="listTab">
                 <li ><a href='http://www.icar.org.in/rohudatabase/index.php' target="_blank">Rohu Database</a></li>
            <li ><a href='http://117.240.114.67/weedid/aiwsweedident.aspx' target="_blank">Weed Seed Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/cwsmainweeds.aspx' target="_blank">Weed Seedling Identification</a></li>
            <li ><a href='http://117.240.114.67/weedid/bwiweedident.aspx' target="_blank">Weed Identification</a></li>

            <li ><a href='http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href='http://www.cropweatheroutlook.in' target="_blank">Crop Weather Outlook: AICRPAM tools</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/formfish/index.html' target="_blank">Automated Species Identification System</a></li>
            <li ><a href='http://www.nbfgr.res.in/Databases/ornamental/home.aspx' target="_blank">Marine ornamental finfishes and shell fishes</a></li>
            <li ><a href='http://210.212.93.85/agris/breed.aspx' target="_blank">Animal Genetic Resources of India</a></li>
            <li ><a href='http://www.ncipm.org.in/cropsap2014/login.aspx' target="_blank">Crop Pest Surveillance and Advisory</a></li>
            <li ><a href='http://www.ncipm.org.in/ICTMalawi/' target="_blank">ICT Based Pest Surveillance</a></li>
            <li ><a href='http://ctcri.in/statistics/FormsCEI.aspx' target="_blank">TUBER CROPS STATISTICS</a></li>

            <li ><a href='http://www.crijaf.org.in/SideLinks/QuickLinks/AgrometeorologicalData.html' target="_blank">Agrometeorological Data at ICAR-CRIJA</a></li>
            <li ><a href=' http://www.crida.in:8080/naip/index.jsp' target="_blank">Crop Pest DSS</a></li>
            <li ><a href=' http://nrcgrapes.nic.in/weather_forecast_based_grape_adv.htm' target="_blank">Weather forecast based grape advice</a></li>
            <li ><a href='http://research.ciphet.in/' target="_blank">Post-Harvest Machinery</a></li>
            <li ><a href='http://cift.res.in/innercontent.php?contentid=NjA=' target="_blank">CIFT Knowledge Base</a></li>
            <li ><a href='http://nrce.nic.in/breeds.php' target="_blank">Equine Breeds of India</a></li>
    </ul>
  </li>
  <li><a href="#">Genetic Resources Portals</a>
    <!-- This is the sub nav -->
    <ul class="listTab">
     <li ><a href='http://www.mgrportal.org.in/' target="_blank">Microbial Genetic Resources Portal</a></li>
            <li ><a href='http://www.nbpgr.ernet.in/PGR_Databases.aspx' target="_blank">PGR Database</a></li>
            <li ><a href='http://www.nbpgr.ernet.in:8080/PGRPortal/(S(fzkcby45lxboum2hufans255))/default.aspx' target="_blank">PGR Portal</a></li>
            <li ><a href='http://210.212.93.85/agrportal/index.htm' target="_blank">Animal Genetic Resources Portal</a></li>
            <li ><a href='http://www.sugarcane.res.in/index.php/en/resrch/genetic-resources' target="_blank">Sugarcane Genetic Resources</a></li>
    </ul>
  </li>
  </div>
  </div>
  <div style="margin-top: 65px;">
  <ul class="goo-collapsible goo-coll-stacked">
    <li class="header">Latest News</li>
    <marquee direction="up" style = "width:100%;margin:0px;padding:0px;" scrolldelay="200" onMouseOver="this.stop();" onMouseOut="this.start();">
    <li><a href="PDF/Digitization AICRPs Information.pdf" target="_blank" >Digitization AICRPs Information</a></li>
    <li><a href="PDF/Draft Format for Technology Database.pdf" >Draft Format for Technology Database</a></li>
    <li><a href="PDF/ICAR Guidelines Research Papers 2014.pdf" >ICAR Guidelines Research Papers 2014</a></li>
    <li><a href="PDF/Letter for Nomination of Nodal officers.pdf" >Letter for Nomination of Nodal officers</a></li>
    <li><a href="PDF/Mapping of Natural Resources.pdf" >Mapping of Natural Resources</a></li>
    <li><a href="JavaScript:display('Circular');" >Circular</a></li>
    </marquee>
    </ul>
    </div>
</div>


问:
How to set the max height of ScrolledComposite in SWT
I have a ScrolledComposite with a button which creates a new button below, "on the next row". And every time I adapt the height of my composite with pack().

But now I want to set the maximum height so, that from a certain size the height of the window stays the same and I get a vertical scrollbar.

答:
Calling pack() will always resize the control so that it can show its entire contents. Instead, the size of the scrolled composite should be managed by the layout of its parent. That is the whole purpose of the scrolled composite: showing the contained controls and offering scroll bars when needed.

Use setMinSize() to control when scroll bars should be shown. The below example features a scrolled composite with a single button. Pushing the button will add another button. Note that after a button was added min size is recomputed in updateMinSize().

```<code>public class DynamicScrolledComposite {

  public static void main( String[] args ) {
    Display display = new Display();
    Shell shell = new Shell( display );
    shell.setLayout( new FillLayout() );
    ScrolledComposite scrolledComposite = new ScrolledComposite( shell, SWT.H_SCROLL | SWT.V_SCROLL );
    scrolledComposite.setExpandVertical( true );
    scrolledComposite.setExpandHorizontal( true );
    scrolledComposite.addListener( SWT.Resize, event -> updateMinSize( scrolledComposite ) );
    Composite composite = new Composite( scrolledComposite, SWT.NONE );
    composite.setLayout( new GridLayout( 1, false ) );
    createButton( composite );
    scrolledComposite.setContent( composite );
    shell.setSize( 600, 300 );
    shell.open();
    while( !shell.isDisposed() ) {
      if( !display.readAndDispatch() )
        display.sleep();
    }
    display.dispose();
  }

  private static void updateMinSize( ScrolledComposite scrolledComposite ) {
    Rectangle clientArea = scrolledComposite.getClientArea();
    clientArea.width -= scrolledComposite.getVerticalBar().getSize().x;
    Point minSize = scrolledComposite.getContent().computeSize( clientArea.width, SWT.DEFAULT );
    scrolledComposite.setMinSize( minSize );
  }

  private static void createButton( Composite parent ) {
    Button button = new Button( parent, SWT.PUSH );
    button.setText( "Add another button" );
    button.addListener( SWT.Selection, new Listener() {
      @Override
      public void handleEvent( Event event ) {
        createButton( parent );
        ScrolledComposite scrolledComposite = ( ScrolledComposite )button.getParent().getParent();
        button.getParent().requestLayout();
        updateMinSize( scrolledComposite );
      }
    } );
  }
}
</code>```

To learn more about the different content management strategies of the ScrolledComposite, see here: http://www.codeaffine.com/2016/03/01/swt-scrolledcomposite/

Body:
Calling pack() will always resize the control so that it can show its entire contents. Instead, the size of the scrolled composite should be managed by the layout of its parent. That is the whole purpose of the scrolled composite: showing the contained controls and offering scroll bars when needed.

Use setMinSize() to control when scroll bars should be shown. The below example features a scrolled composite with a single button. Pushing the button will add another button. Note that after a button was added min size is recomputed in updateMinSize().

public class DynamicScrolledComposite {

  public static void main( String[] args ) {
    Display display = new Display();
    Shell shell = new Shell( display );
    shell.setLayout( new FillLayout() );
    ScrolledComposite scrolledComposite = new ScrolledComposite( shell, SWT.H_SCROLL | SWT.V_SCROLL );
    scrolledComposite.setExpandVertical( true );
    scrolledComposite.setExpandHorizontal( true );
    scrolledComposite.addListener( SWT.Resize, event -> updateMinSize( scrolledComposite ) );
    Composite composite = new Composite( scrolledComposite, SWT.NONE );
    composite.setLayout( new GridLayout( 1, false ) );
    createButton( composite );
    scrolledComposite.setContent( composite );
    shell.setSize( 600, 300 );
    shell.open();
    while( !shell.isDisposed() ) {
      if( !display.readAndDispatch() )
        display.sleep();
    }
    display.dispose();
  }

  private static void updateMinSize( ScrolledComposite scrolledComposite ) {
    Rectangle clientArea = scrolledComposite.getClientArea();
    clientArea.width -= scrolledComposite.getVerticalBar().getSize().x;
    Point minSize = scrolledComposite.getContent().computeSize( clientArea.width, SWT.DEFAULT );
    scrolledComposite.setMinSize( minSize );
  }

  private static void createButton( Composite parent ) {
    Button button = new Button( parent, SWT.PUSH );
    button.setText( "Add another button" );
    button.addListener( SWT.Selection, new Listener() {
      @Override
      public void handleEvent( Event event ) {
        createButton( parent );
        ScrolledComposite scrolledComposite = ( ScrolledComposite )button.getParent().getParent();
        button.getParent().requestLayout();
        updateMinSize( scrolledComposite );
      }
    } );
  }
}

To learn more about the different content management strategies of the ScrolledComposite, see here: http://www.codeaffine.com/2016/03/01/swt-scrolledcomposite/


问:
problem in concurrent web services
Hi All
       I have developed a web services. I am getting problem when two different user are trying to access web services concurrently.
       In web services two  methods  are there

setInputParameter

getUserService

suppose

```<code>          Time               User              Operation
          10:10 am           user1             setInputParameter
          10:15 am           user2             setInputParameter
          10:20 am           user1             getUserService
</code>```

User1  is getting result according to the input parameter seted by user2 not by ( him own )

I am using  axis2 1.4 ,eclipse ant build,
My services are goes here

User class

service class

service.xml

build file

testclass

```<code>package com.jimmy.pojo;

public class User {
 private String firstName;
 private String lastName;
 private String[] addressCity;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String[] getAddressCity() {
  return addressCity;
 }

 public void setAddressCity(String[] addressCity) {
  this.addressCity = addressCity;
 }

}
[/code]

[code=java]package com.jimmy.service;

import com.jimmy.pojo.User;

public class UserService {
 private User user;

 public void setInputParameter(User userInput) {
  user = userInput;
 }

 public User getUserService() {
  user.setFirstName(user.getFirstName() + " changed ");
  if (user.getAddressCity() == null) {
   user.setAddressCity(new String[] { "New City Added" });
  } else {
   user.getAddressCity()[0] = "===========";
  }
  return user;
 }

}
[/code]

[code=java]<service name="MyWebServices" scope="application">
 <description>
  My Web Service
    </description>
 <messageReceivers>
  <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
   class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
  <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
   class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
 </messageReceivers>
 <parameter name="ServiceClass">com.jimmy.service.UserService
 </parameter>

</service>[/code]

[code=java]
<project name="MyWebServices" basedir="." default="generate.service">
 <property name="service.name" value="UserService" />
 <property name="dest.dir" value="build" />
 <property name="dest.dir.classes" value="${dest.dir}/${service.name}" />
 <property name="dest.dir.lib" value="${dest.dir}/lib" />
 <property name="axis2.home" value="../../" />
 <property name="repository.path" value="${axis2.home}/repository" />
 <path id="build.class.path">
  <fileset dir="${axis2.home}/lib">
   <include name="*.jar" />
  </fileset>
 </path>
 <path id="client.class.path">
  <fileset dir="${axis2.home}/lib">
   <include name="*.jar" />
  </fileset>
  <fileset dir="${dest.dir.lib}">
   <include name="*.jar" />
  </fileset>
 </path>
 <target name="clean">
  <delete dir="${dest.dir}" />
  <delete dir="src" includes="com/jimmy/pojo/stub/**"/>
 </target>
 <target name="prepare">
  <mkdir dir="${dest.dir}" />
  <mkdir dir="${dest.dir}/lib" />
  <mkdir dir="${dest.dir.classes}" />
  <mkdir dir="${dest.dir.classes}/META-INF" />
 </target>
 <target name="generate.service" depends="clean,prepare">
  <copy file="src/META-INF/services.xml" tofile="${dest.dir.classes}/META-INF/services.xml" overwrite="true" />
  <javac srcdir="src" destdir="${dest.dir.classes}" includes="com/jimmy/service/**,com/jimmy/pojo/**">
   <classpath refid="build.class.path" />
  </javac>
  <jar basedir="${dest.dir.classes}" destfile="${dest.dir}/${service.name}.aar" />
  <copy file="${dest.dir}/${service.name}.aar" tofile="${repository.path}/services/${service.name}.aar" overwrite="true" />
 </target>
</project>

[/code]

[code=java]package com.jimmy.test;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

import com.jimmy.pojo.User;

public class MyWebServices {
 @SuppressWarnings("unchecked")
 public static void main(String[] args1) throws AxisFault {
  RPCServiceClient serviceClient = new RPCServiceClient();
  Options options = serviceClient.getOptions();
  EndpointReference targetEPR = new EndpointReference(
    "http://localhost:8080/axis2/services/MyWebServices");
  options.setTo(targetEPR);
  // Setting the Input Parameter
  QName opSetQName = new QName("http://service.jimmy.com",
    "setInputParameter");
  User user = new User();
  String[] cityList = new String[] { "Bangalore", "Mumbai" };
  /*       We need to set this for user 2 as user 2    */
  user.setFirstName("User 1  first name");
  user.setLastName("User 1 Last name");
  user.setAddressCity(cityList);
  Object[] opSetInptArgs = new Object[] { user };
  serviceClient.invokeRobust(opSetQName, opSetInptArgs);

  // Getting the weather
  QName opGetWeather = new QName("http://service.jimmy.com",
    "getUserService");

  Object[] opGetWeatherArgs = new Object[] {};
  Class[] returnTypes = new Class[] { User.class };

  Object[] response = serviceClient.invokeBlocking(opGetWeather,
    opGetWeatherArgs, returnTypes);

  System.out.println("Context :"+serviceClient.getServiceContext());

  User result = (User) response[0];

  if (result == null) {
   System.out.println("User is not initialized!");
   return;
  } else {
   System.out.println("*********printing result********");
   String[] list =result.getAddressCity();
   System.out.println(result.getFirstName());
   System.out.println(result.getLastName());
   for (int indx = 0; indx < list.length ; indx++) {
    String string = result.getAddressCity()[indx];
    System.out.println(string);
   }
  }

 }
}
</code>```

答:
It appears to me that you are trying to maintain state between two subsequent calls of the webservice. For this purpose you are maintaining a private field in Service class. But as the service class is not instantiated on each request you are getting state shared between all the users of webservice.

What you need to do is to store the state in some kind of session scope. The webservice clients will then need to pass-back some session token with each request.

One way of doing stateful webservices with Axis 2 is detailed here

ContentLicense: CC BY-SA 2.5

Title: problem in concurrent web services

Body:
Hi All
       I have developed a web services. I am getting problem when two different user are trying to access web services concurrently.
       In web services two  methods  are there

setInputParameter

getUserService

suppose

          Time               User              Operation
          10:10 am           user1             setInputParameter
          10:15 am           user2             setInputParameter
          10:20 am           user1             getUserService

User1  is getting result according to the input parameter seted by user2 not by ( him own )

I am using  axis2 1.4 ,eclipse ant build,
My services are goes here

User class

service class

service.xml

build file

testclass

package com.jimmy.pojo;

public class User {
 private String firstName;
 private String lastName;
 private String[] addressCity;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String[] getAddressCity() {
  return addressCity;
 }

 public void setAddressCity(String[] addressCity) {
  this.addressCity = addressCity;
 }

}
[/code]

[code=java]package com.jimmy.service;

import com.jimmy.pojo.User;

public class UserService {
 private User user;

 public void setInputParameter(User userInput) {
  user = userInput;
 }

 public User getUserService() {
  user.setFirstName(user.getFirstName() + " changed ");
  if (user.getAddressCity() == null) {
   user.setAddressCity(new String[] { "New City Added" });
  } else {
   user.getAddressCity()[0] = "===========";
  }
  return user;
 }

}
[/code]

[code=java]<service name="MyWebServices" scope="application">
 <description>
  My Web Service
    </description>
 <messageReceivers>
  <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
   class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
  <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
   class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
 </messageReceivers>
 <parameter name="ServiceClass">com.jimmy.service.UserService
 </parameter>

</service>[/code]

[code=java]
<project name="MyWebServices" basedir="." default="generate.service">
 <property name="service.name" value="UserService" />
 <property name="dest.dir" value="build" />
 <property name="dest.dir.classes" value="${dest.dir}/${service.name}" />
 <property name="dest.dir.lib" value="${dest.dir}/lib" />
 <property name="axis2.home" value="../../" />
 <property name="repository.path" value="${axis2.home}/repository" />
 <path id="build.class.path">
  <fileset dir="${axis2.home}/lib">
   <include name="*.jar" />
  </fileset>
 </path>
 <path id="client.class.path">
  <fileset dir="${axis2.home}/lib">
   <include name="*.jar" />
  </fileset>
  <fileset dir="${dest.dir.lib}">
   <include name="*.jar" />
  </fileset>
 </path>
 <target name="clean">
  <delete dir="${dest.dir}" />
  <delete dir="src" includes="com/jimmy/pojo/stub/**"/>
 </target>
 <target name="prepare">
  <mkdir dir="${dest.dir}" />
  <mkdir dir="${dest.dir}/lib" />
  <mkdir dir="${dest.dir.classes}" />
  <mkdir dir="${dest.dir.classes}/META-INF" />
 </target>
 <target name="generate.service" depends="clean,prepare">
  <copy file="src/META-INF/services.xml" tofile="${dest.dir.classes}/META-INF/services.xml" overwrite="true" />
  <javac srcdir="src" destdir="${dest.dir.classes}" includes="com/jimmy/service/**,com/jimmy/pojo/**">
   <classpath refid="build.class.path" />
  </javac>
  <jar basedir="${dest.dir.classes}" destfile="${dest.dir}/${service.name}.aar" />
  <copy file="${dest.dir}/${service.name}.aar" tofile="${repository.path}/services/${service.name}.aar" overwrite="true" />
 </target>
</project>

[/code]

[code=java]package com.jimmy.test;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

import com.jimmy.pojo.User;

public class MyWebServices {
 @SuppressWarnings("unchecked")
 public static void main(String[] args1) throws AxisFault {
  RPCServiceClient serviceClient = new RPCServiceClient();
  Options options = serviceClient.getOptions();
  EndpointReference targetEPR = new EndpointReference(
    "http://localhost:8080/axis2/services/MyWebServices");
  options.setTo(targetEPR);
  // Setting the Input Parameter
  QName opSetQName = new QName("http://service.jimmy.com",
    "setInputParameter");
  User user = new User();
  String[] cityList = new String[] { "Bangalore", "Mumbai" };
  /*       We need to set this for user 2 as user 2    */
  user.setFirstName("User 1  first name");
  user.setLastName("User 1 Last name");
  user.setAddressCity(cityList);
  Object[] opSetInptArgs = new Object[] { user };
  serviceClient.invokeRobust(opSetQName, opSetInptArgs);

  // Getting the weather
  QName opGetWeather = new QName("http://service.jimmy.com",
    "getUserService");

  Object[] opGetWeatherArgs = new Object[] {};
  Class[] returnTypes = new Class[] { User.class };

  Object[] response = serviceClient.invokeBlocking(opGetWeather,
    opGetWeatherArgs, returnTypes);

  System.out.println("Context :"+serviceClient.getServiceContext());

  User result = (User) response[0];

  if (result == null) {
   System.out.println("User is not initialized!");
   return;
  } else {
   System.out.println("*********printing result********");
   String[] list =result.getAddressCity();
   System.out.println(result.getFirstName());
   System.out.println(result.getLastName());
   for (int indx = 0; indx < list.length ; indx++) {
    String string = result.getAddressCity()[indx];
    System.out.println(string);
   }
  }

 }
}


问:
extract parts of URL string with regex
I have an object value/string that is a url. I need to extract the piece of the url that contains a unique identifier. How can this be done via regex?

Here is the example string:

```<code>http://images.example.com/examp/img/uuid/c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/100/105/1.0
</code>```

I am trying to extract just what is after uuid/ and before /100

答:
```<code>var identifier=string.split("/")[6];
</code>```

Simlly take out the stuff between the 5th and the 6th slash.

Title: extract parts of URL string with regex

Body:
I have an object value/string that is a url. I need to extract the piece of the url that contains a unique identifier. How can this be done via regex?

Here is the example string:

http://images.example.com/examp/img/uuid/c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/100/105/1.0

I am trying to extract just what is after uuid/ and before /100

Body:
var identifier=string.split("/")[6];

Simlly take out the stuff between the 5th and the 6th slash.


问:
How to display limited data using Angular.js?
I have seen enough examples on how to display the limited results using limitTo. But unfortunately it isn't working as expected. Currently, it is displaying the entire list but I want to limit it to only 8 key,value items in 4/4 blocks.

Here is the plnkr.

```<code>  <ul>
      <li ng-repeat="(key,value) in stocks |limitTo :8">
            {{key +" "+ value}}
      </li>
  </ul>

 <script>
    var app = angular.module('smallcaseApp', []);
    app.controller('stockCtrl', function($scope, $http) {
    $http.get("data.json").then(function(response) {
        $scope.stocks = response.data.price;
      });
    });
 </script>
</code>```

答:
For limitTo input should be either array or string/number. You need to create custom filter to handle it. Here's working plunk for your issue </p>

```<code>app.filter('objLimitTo', [function(){
return function(obj, limit){
    if(obj){
      var keys = Object.keys(obj);
      if(keys.length < 1){
        return [];
      }
    }

    var result = {},
    count = 0;
    angular.forEach(keys, function(key){
        if(count >= limit){
            return false;
        }
        result[key] = obj[key];
        count++;
    });
    return result;
};
}]);
</code>```

<p>http://plnkr.co/edit/8d3gUqg4vHeGQWUXYrat?p=preview </p>

Body:
I have seen enough examples on how to display the limited results using limitTo. But unfortunately it isn't working as expected. Currently, it is displaying the entire list but I want to limit it to only 8 key,value items in 4/4 blocks.

Here is the plnkr.

            {{key +" "+ value}}

Body:
For limitTo input should be either array or string/number. You need to create custom filter to handle it. Here's working plunk for your issue

app.filter('objLimitTo', [function(){
return function(obj, limit){
    if(obj){
      var keys = Object.keys(obj);
      if(keys.length < 1){
        return [];
      }
    }

    var result = {},
    count = 0;
    angular.forEach(keys, function(key){
        if(count >= limit){
            return false;
        }
        result[key] = obj[key];
        count++;
    });
    return result;
};
}]);

http://plnkr.co/edit/8d3gUqg4vHeGQWUXYrat?p=preview


问:
how to print multiple max values from an array in java
I have just started programming in java, and I was trying some stuff out. I had written some code for creating my own array with x indexes that I could fill in as the program runs. So if I run the program I could say x = 5 and I would have 5 indexes to fill in (e.g. 5, 2, 7, 4 and 7). The program would then find the max value and print it. I was then wondering if I could have my program print the number of times my maxValue was in the array. In the example above it would be two. I just can't seem to find out how to do this though.

This is the code I have so far:

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

public class oefeningen {

static void maxValue(int[] newArray){//this method decides the largest number in the array

    int result = newArray[0];
    for (int i=1; i<newArray.length; i++){
        if (newArray[i] > result){
            result = newArray[i];
        }
    }
        System.out.println("The largest number is: " +result);
}

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    int x; //this is the main part of the array
    System.out.println("Please enter size of array:");
    x = keyboard.nextInt();
    int[] newArray = new int[x];

    for (int j=1; j<=x; j++){//this bit is used for manually entering numbers in the array
        System.out.println("Please enter next value:");
        newArray[j-1] = keyboard.nextInt();
    }
    maxValue(newArray);
}
}
</code>```

答:
Just pass array and any value to count how many times it appears in array

```<code>public int checkAmountOfValuesInArray(int[] array, int val) {
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i]==val) count++;
        }
        return count;
}
</code>```

or if you want to do everything in one loop:

```<code>static void maxValue(int[] newArray) {//this method decides the largest number in the array
        int result = newArray[0];
        int count = 1;

        for (int i = 1; i < newArray.length; i++) {
            if (newArray[i] > result) {
                result = newArray[i];
                count = 1;
            } else if (newArray[i] == result) {
                count++;
            }
        }
        System.out.println("The largest number is: " + result+ ", repeated: " + count + " times");
    }
</code>```

Body:
I have just started programming in java, and I was trying some stuff out. I had written some code for creating my own array with x indexes that I could fill in as the program runs. So if I run the program I could say x = 5 and I would have 5 indexes to fill in (e.g. 5, 2, 7, 4 and 7). The program would then find the max value and print it. I was then wondering if I could have my program print the number of times my maxValue was in the array. In the example above it would be two. I just can't seem to find out how to do this though.

This is the code I have so far:

import java.util.*;

public class oefeningen {

static void maxValue(int[] newArray){//this method decides the largest number in the array

    int result = newArray[0];
    for (int i=1; i<newArray.length; i++){
        if (newArray[i] > result){
            result = newArray[i];
        }
    }
        System.out.println("The largest number is: " +result);
}

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    int x; //this is the main part of the array
    System.out.println("Please enter size of array:");
    x = keyboard.nextInt();
    int[] newArray = new int[x];

    for (int j=1; j<=x; j++){//this bit is used for manually entering numbers in the array
        System.out.println("Please enter next value:");
        newArray[j-1] = keyboard.nextInt();
    }
    maxValue(newArray);
}
}

Body:
Just pass array and any value to count how many times it appears in array

public int checkAmountOfValuesInArray(int[] array, int val) {
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i]==val) count++;
        }
        return count;
}

or if you want to do everything in one loop:

static void maxValue(int[] newArray) {//this method decides the largest number in the array
        int result = newArray[0];
        int count = 1;

        for (int i = 1; i < newArray.length; i++) {
            if (newArray[i] > result) {
                result = newArray[i];
                count = 1;
            } else if (newArray[i] == result) {
                count++;
            }
        }
        System.out.println("The largest number is: " + result+ ", repeated: " + count + " times");
    }


问:
Python convert True False matrix to image
I have a matrix consisting of True and False values. I want to print this as an image where all the True values are white and the False values are black. The matrix is called indices. I have tried the following:

```<code>indices = indices.astype(int)  #To convert the true to 1 and false to 0
indices*=255                   #To change all the 1's to 255
cv2.imshow('Indices',indices)
cv2.waitKey()
</code>```

This is printing a fully black image. When I try, print (indices==255).sum(), it returns a values of 669 which means that there are 669 elements/pixels in the indices matrix which should be white. But I can only see a pure black image. How can I fix this?

答:
As far as I know, opencv represents an image as a matrix of floats ranging from 0 to 1, or an integer with values between the minimum and the maximum of that type.

An int has no bounds (except the boundaries of what can be represented with all available memory). If you however use np.uint8, that means you are working with (unsigned) bytes, where the minimum is 0 and the maximum 255.

So there are several options. The two most popular would be:

cast to np.uint8 and then multiply with 255:

```<code>indices = indices.astype(<b>np.uint8</b>)  #convert to an unsigned byte
indices*=255
cv2.imshow('Indices',indices)
cv2.waitKey()</code>```

Use a float representation:

```<code>indices = indices.astype(<b>float</b>)
cv2.imshow('Indices',indices)
cv2.waitKey()</code>```

Note that you could also choose to use np.uint16 for instance to use unsigned 16-bit integers. In that case you will have to multiply with 65'535. The advantage of this approach is that you can use an arbitrary color depth (although most image formats use 24-bit colors (8 bits per channel), there is no reason not to use 48-bit colors. If you for instance are doing image processing for a glossy magazine, then it can be beneficial to work with more color depth.

Furthermore even if the end result is a 24-bit colorpalette, one can sometimes better use a higher color depth for the different steps in image processing.

Body:
I have a matrix consisting of True and False values. I want to print this as an image where all the True values are white and the False values are black. The matrix is called indices. I have tried the following:

indices = indices.astype(int)  #To convert the true to 1 and false to 0
indices*=255                   #To change all the 1's to 255
cv2.imshow('Indices',indices)
cv2.waitKey()

This is printing a fully black image. When I try, print (indices==255).sum(), it returns a values of 669 which means that there are 669 elements/pixels in the indices matrix which should be white. But I can only see a pure black image. How can I fix this?

Body:
As far as I know, opencv represents an image as a matrix of floats ranging from 0 to 1, or an integer with values between the minimum and the maximum of that type.

An int has no bounds (except the boundaries of what can be represented with all available memory). If you however use np.uint8, that means you are working with (unsigned) bytes, where the minimum is 0 and the maximum 255.

So there are several options. The two most popular would be:

cast to np.uint8 and then multiply with 255:

indices = indices.astype(np.uint8)  #convert to an unsigned byte
indices*=255
cv2.imshow('Indices',indices)
cv2.waitKey()

Use a float representation:

indices = indices.astype(float)
cv2.imshow('Indices',indices)
cv2.waitKey()

Note that you could also choose to use np.uint16 for instance to use unsigned 16-bit integers. In that case you will have to multiply with 65'535. The advantage of this approach is that you can use an arbitrary color depth (although most image formats use 24-bit colors (8 bits per channel), there is no reason not to use 48-bit colors. If you for instance are doing image processing for a glossy magazine, then it can be beneficial to work with more color depth.

Furthermore even if the end result is a 24-bit colorpalette, one can sometimes better use a higher color depth for the different steps in image processing.


问:
gtk+ c simulating tab key from code
I'm trying to build a Gtk C GUI application and I can't use the mouse or keyboard for it. My input device is an external keypad connected to the application with serial port.

My problem is that I want to switch between some GtkButtons in my form when a key on my keypad is pressed (like when using the Tab key in a GUI applications).

Here's what I tried so far:

```<code>      GTK_WIDGET_GET_CLASS(widget)->move_focus(widget,GTK_DIR_TAB_FORWARD);
</code>```

But the problem is that the focus is not visible until I actually press the Tab key on my keyboard. When I run the application, it seems as if nothing is happening, but when I press Tab once, I see that focus is changing.

What am I doing wrong?

答:
make sure that GtkWindow is TOP LEVEL type , because for top level window you can access widgets within that window using keyboard TAB key without doing any addition in code for using TAB.
Post your code for more accurate solution.</p>

Title: gtk+ c simulating tab key from code

Body:
I'm trying to build a Gtk C GUI application and I can't use the mouse or keyboard for it. My input device is an external keypad connected to the application with serial port.

My problem is that I want to switch between some GtkButtons in my form when a key on my keypad is pressed (like when using the Tab key in a GUI applications).

Here's what I tried so far:

      GTK_WIDGET_GET_CLASS(widget)->move_focus(widget,GTK_DIR_TAB_FORWARD);

But the problem is that the focus is not visible until I actually press the Tab key on my keyboard. When I run the application, it seems as if nothing is happening, but when I press Tab once, I see that focus is changing.

What am I doing wrong?


答:
You could keep track within your maxValue function, and reset the counter every time a new max is discovered. Something like this:</p>

```<code>static void maxValue(int[] newArray){//this method decides the largest number in the array

    int count = 0;
    int result = newArray[0];
    for (int i=1; i<newArray.length; i++){
        if (newArray[i] > result){
            result = newArray[i];
            // reset the count
            count = 1;
        }
        // Check for a value equal to the current max
        else if (newArray[i] == result) {
             // increment the count when you find another match of the current max
             count++;
        }
    }
    System.out.println("The largest number is: " +result);
    System.out.println("The largest number appears " + count + " times in the array");
}
</code>```

Title: how to print multiple max values from an array in java

Body:
You could keep track within your maxValue function, and reset the counter every time a new max is discovered. Something like this:

static void maxValue(int[] newArray){//this method decides the largest number in the array

    int count = 0;
    int result = newArray[0];
    for (int i=1; i<newArray.length; i++){
        if (newArray[i] > result){
            result = newArray[i];
            // reset the count
            count = 1;
        }
        // Check for a value equal to the current max
        else if (newArray[i] == result) {
             // increment the count when you find another match of the current max
             count++;
        }
    }
    System.out.println("The largest number is: " +result);
    System.out.println("The largest number appears " + count + " times in the array");
}


问:
Selenium RC in Hudson
is there a way to install selenium into hudson, and have it run a test via a .dll (c#)? all i can find so far is a html script.

Thanks

答:
The fix i've found for this, was to use gallio and push my compiled DLL throw its gallio.echo console. </p>

<p>hudson passes and fails the job based on the results from gallio. </p>

Title: Selenium RC in Hudson

Body:
The fix i've found for this, was to use gallio and push my compiled DLL throw its gallio.echo console.

hudson passes and fails the job based on the results from gallio.


问:
What is a baseless method in Nim?
I'm new to the language. When trying to compile a new object type with a method (where the first argument is an instance of my new type), the compiler warned me like this:</p>

```<code>Warning: use {.base.} for base methods; baseless methods are deprecated [UseBase]
</code>```

答:
This warning typically happens to me when I define a method on a derived type -- thinking that I'm overriding behavior from a base type -- but the method signature is wrong and I'm effectively not overriding any method, hence the warning.

e.g.,

```<code>type
  Base = ref object of RootObj
  Derived  = ref object of Base

method doSomething(b: Base, n: int) {.base.} =
  ...

# !!! This method gets warning because it's not overriding the base
# !!! doSomething method due to different parameter types
method doSomething(d: Derived, n: string) =
  ...
</code>```

Title: What is a baseless method in Nim?

Body:
I'm new to the language. When trying to compile a new object type with a method (where the first argument is an instance of my new type), the compiler warned me like this:

Warning: use {.base.} for base methods; baseless methods are deprecated [UseBase]

Body:
This warning typically happens to me when I define a method on a derived type -- thinking that I'm overriding behavior from a base type -- but the method signature is wrong and I'm effectively not overriding any method, hence the warning.

e.g.,

type
  Base = ref object of RootObj
  Derived  = ref object of Base

method doSomething(b: Base, n: int) {.base.} =
  ...

# !!! This method gets warning because it's not overriding the base
# !!! doSomething method due to different parameter types
method doSomething(d: Derived, n: string) =
  ...


问:
Swift 3: Use NSPredicate(format:) to filter objects by type/class
I got stuck with a problem regarding the NSPredicate syntax. I want to filter an array of objects by their class types.

```<code>class ClassA: NSObject {}
class ClassB: ClassA {}
class ClassC: ClassA {}

let array: [ClassA] = [ClassB(), ClassC()]
</code>```

Now I want to use an NSPredicate to get a filtered array only with ClassB items.

I could use Blocks to do so, and it would be something like this:

```<code>let predicate = NSPredicate { (object, nil) -> Bool in
    return object is ClassB
}
</code>```

Although this is a legitimate approach, I also want to do the exact same thing with NSPredicate(format:).

Among other attempts I unsuccessfully tried the following:

```<code>let predicate = NSPredicate(format: "self = %@", [ClassB.self])
let predicate = NSPredicate(format: "SELF isKindOfClass: %@", [ClassB.self])
</code>```

I think it must be just a syntax problem, but I'm looking for over an hour to solve this with no result.

Thanks in advance.

答:
This should work:

```<code>let predicate = NSPredicate(format: "class = %@", ClassB.self)
</code>```

Here is a documentation page about predicates - https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html#//apple_ref/doc/uid/TP40001793-CJBDBHCB

Body:
I got stuck with a problem regarding the NSPredicate syntax. I want to filter an array of objects by their class types.

class ClassA: NSObject {}
class ClassB: ClassA {}
class ClassC: ClassA {}

let array: [ClassA] = [ClassB(), ClassC()]

Now I want to use an NSPredicate to get a filtered array only with ClassB items.

I could use Blocks to do so, and it would be something like this:

let predicate = NSPredicate { (object, nil) -> Bool in
    return object is ClassB
}

Although this is a legitimate approach, I also want to do the exact same thing with NSPredicate(format:).

Among other attempts I unsuccessfully tried the following:

let predicate = NSPredicate(format: "self = %@", [ClassB.self])
let predicate = NSPredicate(format: "SELF isKindOfClass: %@", [ClassB.self])

I think it must be just a syntax problem, but I'm looking for over an hour to solve this with no result.

Thanks in advance.

Body:
This should work:

let predicate = NSPredicate(format: "class = %@", ClassB.self)

Here is a documentation page about predicates - https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html#//apple_ref/doc/uid/TP40001793-CJBDBHCB


问:
show same page with different menu item active
I have these 2 menu and sub-menus for my help manual which has a page leftmenu.php where I have all the menu's and I have included this file above all my pages.

```<code><li>
    <a href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu 1 </span><span class="fa arrow"></span></a>
    <ul class="nav nav-second-level collapse">
        <li><a href="project.php">Project Management</a></li>
        <li><a href="task.php">Task Management</a></li>
        <li><a href="defect.php">Defect Management</a></li>
        <li><a href="customer1.php">Customer Management</a></li>
        <li><a href="user.php">User Management</a></li>
        <li><a href="settings.php">Settings</a></li>
    </ul>
</li>
<li>
    <a href=""><i class="fa fa-ticket"></i> <span class="nav-label">Main menu 2 </span><span class="fa arrow"></span></a>
    <ul class="nav nav-second-level collapse">
        <li><a href="ticket.php">Ticket Management</a></li>
        <li><a href="resolution.php">Resolutions</a></li>
        <li><a href="customer.php">Customer Management</a></li>
        <li><a href="user.php">User Management</a></li>
        <li><a href="settings.php">Settings</a></li>
    </ul>
</li>
</code>```

Now I have this one customer.php which I would like to use in both the menu's but the menu from where Customer Management is clicked should only be active.
How to I achieve this as I am using only php and html for this.
Thankyou

My code now:

```<code><li <?= active('leads|user|settings')?>>
                    <a href=""><i class="fa fa-diamond"></i> <span class="nav-label">Main menu1</span> <span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li <?= active('leads') ?>><a href="leads.php">Lead Management</a></li>
                        <li <?= active('user') ?>><a href="user.php">User Management</a></li>
                        <li <?= active('settings') ?>><a href="settings.php">Settings</a></li>
                    </ul>
                </li>

                <li <?= active('project|task|defect|customer1|users|settings1')?>>
                    <a href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu2 </span><span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level collapse">
                      <li <?= active('project') ?>><a href="project.php">Project Management</a></li>
                        <li <?= active('task') ?>><a href="task.php">Task Management</a></li>
                        <li <?= active('defect') ?>><a href="defect.php">Defect Management</a></li>
                        <li <?= active('customer1') ?>><a href="customer1.php">Customer Management</a></li>
                        <li <?= active('users') ?>><a href="users.php">User Management</a></li>
                        <li <?= active('settings1') ?>><a href="settings1.php">Settings</a></li>
                    </ul>
                </li>
</code>```

答:
```<code>function active($page) {
    if (preg_match("/$page\./",$_SERVER["PHP_SELF"])) {
        echo "class=active";
    }
}
</code>```

Example

```<code><li><a href=index.php <?= active('index') ?>>Home</a></li>
</code>```

EDIT:

And Example for Main Menu 1

```<code><a <?= active('project|task|defect|customer1|user|settings') ?> href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu 1 </span><span class="fa arrow"></span></a>
</code>```

OwnerDisplayName: anon

Body:
I have these 2 menu and sub-menus for my help manual which has a page leftmenu.php where I have all the menu's and I have included this file above all my pages.

     Main menu 1

Project Management

Task Management

Defect Management

Customer Management

User Management

Settings

     Main menu 2

Ticket Management

Resolutions

Customer Management

User Management

Settings

Now I have this one customer.php which I would like to use in both the menu's but the menu from where Customer Management is clicked should only be active.
How to I achieve this as I am using only php and html for this.
Thankyou

My code now:

<li <?= active('leads|user|settings')?>>
                     Main menu1

                        <li <?= active('leads') ?>>Lead Management

                        <li <?= active('user') ?>>User Management

                        <li <?= active('settings') ?>>Settings

                <li <?= active('project|task|defect|customer1|users|settings1')?>>
                     Main menu2

                      <li <?= active('project') ?>>Project Management

                        <li <?= active('task') ?>>Task Management

                        <li <?= active('defect') ?>>Defect Management

                        <li <?= active('customer1') ?>>Customer Management

                        <li <?= active('users') ?>>User Management

                        <li <?= active('settings1') ?>>Settings

Body:
function active($page) {
    if (preg_match("/$page\./",$_SERVER["PHP_SELF"])) {
        echo "class=active";
    }
}

Example

<li><a href=index.php <?= active('index') ?>>Home</a></li>

EDIT:

And Example for Main Menu 1

<a <?= active('project|task|defect|customer1|user|settings') ?> href=""><i class="fa fa-briefcase"></i> <span class="nav-label">Main menu 1 </span><span class="fa arrow"></span></a>


问:
Move mutable reference out of mutable object
I have an iterator over an enum that has a mutable reference in one of its variants. Now I want to move this reference out self and return it. To avoid having two mutable references to the same object at the same time, I want to change the enum variant of self to one that does not have the reference. Below is a code example:

```<code>enum Test<'a> {
    A(&'a mut usize),
    B,
}

impl<'a> Iterator for Test<'a> {
    type Item = &'a mut usize;

    fn next(&mut self) -> Option<Self::Item> {
        match *self {
            Test::A(r) => Some(r), // TODO: return mutable reference and change self to B
            Test::B => None,
        }
    }
}

fn main() {
    let mut v = 1;
    let mut it = Test::A(&mut v);
    it.next();
}
</code>```

The question is related to Change selector in match when selector is a mutable reference, but that solution does not work here.

答:
I would use a swap:

```<code>fn next(&mut self) -> Option<Self::Item> {
    if let Test::A(_) = *self {
        let mut to_swap = Test::B;

        std::mem::swap(self, &mut to_swap);
        match to_swap {
            Test::A(r)  => Some(r),
            _           => unreachable!(), // never reached
        }
    } else {
        None
    }
}
</code>```

You can use an helper function as follow:

```<code>impl<'a> Iterator for Test<'a> {
    type Item = &'a mut usize;

    fn next(&mut self) -> Option<Self::Item> {
        if let Test::A(_) = *self {
            let mut to_swap = Test::B;

            std::mem::swap(self, &mut to_swap);
            to_swap.consume_as_a()
        } else {
            None
        }
    }
}

impl<'a> Test<'a> {
    fn consume_as_a(self) -> Option<&'a mut usize> {
        match self {
            Test::A(r)  => Some(r),
            _           => None,
        }
    }
}
</code>```

Body:
I have an iterator over an enum that has a mutable reference in one of its variants. Now I want to move this reference out self and return it. To avoid having two mutable references to the same object at the same time, I want to change the enum variant of self to one that does not have the reference. Below is a code example:

enum Test<'a> {
    A(&'a mut usize),
    B,
}

impl<'a> Iterator for Test<'a> {
    type Item = &'a mut usize;

    fn next(&mut self) -> Option<Self::Item> {
        match *self {
            Test::A(r) => Some(r), // TODO: return mutable reference and change self to B
            Test::B => None,
        }
    }
}

fn main() {
    let mut v = 1;
    let mut it = Test::A(&mut v);
    it.next();
}

The question is related to Change selector in match when selector is a mutable reference, but that solution does not work here.

Body:
I would use a swap:

fn next(&mut self) -> Option<Self::Item> {
    if let Test::A(_) = *self {
        let mut to_swap = Test::B;

        std::mem::swap(self, &mut to_swap);
        match to_swap {
            Test::A(r)  => Some(r),
            _           => unreachable!(), // never reached
        }
    } else {
        None
    }
}

You can use an helper function as follow:

impl<'a> Iterator for Test<'a> {
    type Item = &'a mut usize;

    fn next(&mut self) -> Option<Self::Item> {
        if let Test::A(_) = *self {
            let mut to_swap = Test::B;

            std::mem::swap(self, &mut to_swap);
            to_swap.consume_as_a()
        } else {
            None
        }
    }
}

impl<'a> Test<'a> {
    fn consume_as_a(self) -> Option<&'a mut usize> {
        match self {
            Test::A(r)  => Some(r),
            _           => None,
        }
    }
}


问:
Cassandra insertion: InvalidQueryException: Invalid null value in condition for column
Hi I'm starting working with Cassandra, I'm trying to insert data into Cassandra table using this code in Java in REST server created by DropWizard

```<code>    public int insertqueueid(Datafilter data) throws UnknownHostException
    {
    PreparedStatement prep = defaultSession.prepare("insert into queueid (queueid, filter, nom, date) values (?,?,?,?)");
    BoundStatement bound = prep.bind(data.getQueued(),data.getFilter(),getName(), new Date()) ;
    defaultSession.execute(bound);
    return 0 ;
    }
</code>```

But it gives me this error :

ERROR [2017-07-03 23:45:57,514] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 5d2d169dd71c2520
  ! com.datastax.driver.core.exceptions.InvalidQueryException: Invalid null value in condition for column queueid
  ! at com.datastax.driver.core.Responses$Error.asException(Responses.java:136)
  ! at com.datastax.driver.core.DefaultResultSetFuture.onSet(DefaultResultSetFuture.java:179)
  ! at com.datastax.driver.core.RequestHandler.setFinalResult(RequestHandler.java:177)

What do you think, it's the problem ?

Sorry for bad language

答:
Based on the error it looks like NULL value is being passed to the queueid column. I assume it's the partition key of the table and you can't pass NULL for that column.

Please check the data and fix it accordingly.

Body:
Hi I'm starting working with Cassandra, I'm trying to insert data into Cassandra table using this code in Java in REST server created by DropWizard

    public int insertqueueid(Datafilter data) throws UnknownHostException
    {
    PreparedStatement prep = defaultSession.prepare("insert into queueid (queueid, filter, nom, date) values (?,?,?,?)");
    BoundStatement bound = prep.bind(data.getQueued(),data.getFilter(),getName(), new Date()) ;
    defaultSession.execute(bound);
    return 0 ;
    }

But it gives me this error :

ERROR [2017-07-03 23:45:57,514] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 5d2d169dd71c2520
  ! com.datastax.driver.core.exceptions.InvalidQueryException: Invalid null value in condition for column queueid
  ! at com.datastax.driver.core.Responses$Error.asException(Responses.java:136)
  ! at com.datastax.driver.core.DefaultResultSetFuture.onSet(DefaultResultSetFuture.java:179)
  ! at com.datastax.driver.core.RequestHandler.setFinalResult(RequestHandler.java:177)

What do you think, it's the problem ?

Sorry for bad language


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
The do while loop has been forgotten, I think :)

Taken from here.

The C#  while statement executes a statement or a block of statements until a specified expression evaluates to false . In some situation you may want to execute the loop at least one time and then check the condition. In this case you can use do..while loop.

The difference between  do..while and while is that do..while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. From the following example you can understand how  do..while loop function.

```<code>using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int count = 5;
            do{
                MessageBox.Show(" Loop Executed ");
                count++;
            }while (count <=4);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int count = 5;
            while (count <=4){
                MessageBox.Show(" Loop Executed ");
                count++;
            }
        }
    }
}
</code>```

Title: When to use each type of loop?

Body:
The do while loop has been forgotten, I think :)

Taken from here.

The C#  while statement executes a statement or a block of statements until a specified expression evaluates to false . In some situation you may want to execute the loop at least one time and then check the condition. In this case you can use do..while loop.

The difference between  do..while and while is that do..while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. From the following example you can understand how  do..while loop function.

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int count = 5;
            do{
                MessageBox.Show(" Loop Executed ");
                count++;
            }while (count <=4);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int count = 5;
            while (count <=4){
                MessageBox.Show(" Loop Executed ");
                count++;
            }
        }
    }
}


问:
How do I fetch and save files using JavaScript?
My goal is to create a program on a webpage. The program will Fetch  an assembly folder. Then extract CNC files from the assembly folder and put the CNC files into one folder and sort the CNC files into 3 other folders (plywood, aluminum, or steel) based upon the filament type metadata in the CNC files.

What is the best method to doing this using JavaScript?

Is there a way to detect file properties such as whether a file is a CNC using JavaScript?

I was also thinking of incorporating Python, since JavaScript is too simple a language for this type of process. Is there a way to link JavaScript and Python, such that JavaScript will be the main class and Python will be used as a subclass(es)?

Thank you!

答:
In, short you can't. It is not possible to do this using JavaScript in the browser. It is entirely possible to do this using Node.js. You can also certainly call Python from JavaScript and vice versa in Node. So to answer your questions:

The best method is using Node.js if you want to use JavaScript.

It depends on what you mean by "file properties". If you mean the EXIF data, then you can use a package called exif-parser or something similar. Maybe you want the MIME type of the file, if so then use mime-types. There's bound to be a package that you can utilize to achieve your needs.

It is possible to run JavaScript from Python and vice versa, but why? Both languages are more than capable on their own.


问:
Translate this Excel formula into VBA code (function)
This is the formula in Excel that I'm trying to convert to VBA code:

```<code>=IFERROR(IF(effDate>curDate,0,IF((curDate-effDate+1)>nDays,nDays*(nSpend/365),((nSpend/365)*(curDate-effDate+1))-IF((curDate-effDate+1)-nDays>0,nSpend/365,0))),0)
</code>```

For checking working purposes here are the values for each variable:

```<code>effDate: 1/1/17 (dimmed as value)
curDate: 3/31/17 (dimmed as value)
nDays: 60
nSpend: 1600
</code>```

Correct answer: 263

I tried to make it work for two days now and I retyped in about a hundred different way and none of them work. The code may work for one cell but it doesn't calculate correctly for the others. Or it doesn't work at all. Here is one of the examples of what I made earlier (name of the function is APFcst):

```<code>If effDate > curDate then
APFcst = 0
Exit Function
End if

If (curDate - effDate + 1) > nDays then
APFcst = nDays * (nSpend / 365)
Else
val1 = (nSpend / 365) * (curDate - effDatea + 1)
end if

if (curDate - effDate + 1) - nDays > 0 then
val2 = nSpend / 365
else
val2 = 0
end if

APFcst = val1 - val2
Exit Function
End if
</code>```

NOTE: everything is dimmed properly, the issue that I'm having is just translating the actual formula so it'll give me the correct answer.
Please help! I've been staring at this for so long that I might not see an obvious solution.

答:
After noticing that the last IF check in your formula is redundant, here's a simplification of your equation:

```<code>Function xAPFcst(effDate, curDate, nSpend, nDays) As double
  xAPFcst = IIf(effDate > curDate, 0, (nSpend / 365) * Application.Min(nDays, curDate - effDate + 1))
End function
</code>```

Body:
This is the formula in Excel that I'm trying to convert to VBA code:

=IFERROR(IF(effDate>curDate,0,IF((curDate-effDate+1)>nDays,nDays*(nSpend/365),((nSpend/365)*(curDate-effDate+1))-IF((curDate-effDate+1)-nDays>0,nSpend/365,0))),0)

For checking working purposes here are the values for each variable:

effDate: 1/1/17 (dimmed as value)
curDate: 3/31/17 (dimmed as value)
nDays: 60
nSpend: 1600

Correct answer: 263

I tried to make it work for two days now and I retyped in about a hundred different way and none of them work. The code may work for one cell but it doesn't calculate correctly for the others. Or it doesn't work at all. Here is one of the examples of what I made earlier (name of the function is APFcst):

If effDate > curDate then
APFcst = 0
Exit Function
End if

If (curDate - effDate + 1) > nDays then
APFcst = nDays * (nSpend / 365)
Else
val1 = (nSpend / 365) * (curDate - effDatea + 1)
end if

if (curDate - effDate + 1) - nDays > 0 then
val2 = nSpend / 365
else
val2 = 0
end if

APFcst = val1 - val2
Exit Function
End if

NOTE: everything is dimmed properly, the issue that I'm having is just translating the actual formula so it'll give me the correct answer.
Please help! I've been staring at this for so long that I might not see an obvious solution.

Body:
After noticing that the last IF check in your formula is redundant, here's a simplification of your equation:

Function xAPFcst(effDate, curDate, nSpend, nDays) As double
  xAPFcst = IIf(effDate > curDate, 0, (nSpend / 365) * Application.Min(nDays, curDate - effDate + 1))
End function


问:
Changing INT with FLOAT
I have this program:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 3
#define m 3

int main(void)
{
int i;
int j;
int mat[n][m];
int sum = 0;

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        printf("Enters the matrix values[%d][%d]: ", i, j);
        scanf("%d", &mat[i][j]);
    }
}

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
}

printf("the sum of all elements of matrix is: %d\n", sum);

for (i = 0; i < n; i++)
{
    sum = 0;
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
    sum = sum / m;
    printf("The average of the i-th line is %d e': %d\n", i, sum);
}
getch();
}
</code>```

This program works but if the result of sum is an odd number, the average of i-th line is approximated by default.

For solving it I have changed "int summ" with "float summ" but it doesn't work.

Can Someone help me please?

答: That's because you are printing a %d for sum in the end, which is used for int types. If you want the float to be printed correctly, you have to use %f.</p>

Title: Changing INT with FLOAT

Body:
I have this program:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 3
#define m 3

int main(void)
{
int i;
int j;
int mat[n][m];
int sum = 0;

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        printf("Enters the matrix values[%d][%d]: ", i, j);
        scanf("%d", &mat[i][j]);
    }
}

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
}

printf("the sum of all elements of matrix is: %d\n", sum);

for (i = 0; i < n; i++)
{
    sum = 0;
    for (j = 0; j < m; j++)
    {
        sum = sum + mat[i][j];
    }
    sum = sum / m;
    printf("The average of the i-th line is %d e': %d\n", i, sum);
}
getch();
}

This program works but if the result of sum is an odd number, the average of i-th line is approximated by default.

For solving it I have changed "int summ" with "float summ" but it doesn't work.

Can Someone help me please?


问:
os.path.isfile is not working with if statement
I wanted to create a code that would help me to copy similar jpg files.So it was important to me to know whether the files exist or not.

For that I wrote down the following code:

```<code>from os import path
import shutil

oldfile = input("Which file do you want to copy? write that in numbers : ")
fadress = input("What is your file adress : ")
newfadress = input("Where do you want to copy your file : ")

f_num2 = oldfile.split('-')

for each_num in f_num2:
      print(each_num)
      newname = '_DSC{}.JPG'.format(each_num)
      new2 = 'DSC_{}.JPG'.format(each_num)
      if path.isfile(fadress + '\\' + newname):
          shutil.copy(fadress + '\\' + newname, newfadress)
          print(newname)
      elif path.isfile(fadress + '\\' + new2):
          shutil.copy(fadress + '\\' + new2, newfadress)
          print(new2)
</code>```

It's working before the if statements.But it seems that the if statements are not taking the output of os.path.isfile function.What should I do to make this code work?

答:
can you strip fadress before using it and join paths using path.join?

```<code>path.isfile(path.join(fadress.strip(), newname))
</code>```

(or) strip it while reading fadress itself?

```<code>fadress = input("What is your file adress : ").strip()
</code>```

Body:
I wanted to create a code that would help me to copy similar jpg files.So it was important to me to know whether the files exist or not.

For that I wrote down the following code:

from os import path
import shutil

oldfile = input("Which file do you want to copy? write that in numbers : ")
fadress = input("What is your file adress : ")
newfadress = input("Where do you want to copy your file : ")

f_num2 = oldfile.split('-')

for each_num in f_num2:
      print(each_num)
      newname = '_DSC{}.JPG'.format(each_num)
      new2 = 'DSC_{}.JPG'.format(each_num)
      if path.isfile(fadress + '\\' + newname):
          shutil.copy(fadress + '\\' + newname, newfadress)
          print(newname)
      elif path.isfile(fadress + '\\' + new2):
          shutil.copy(fadress + '\\' + new2, newfadress)
          print(new2)

It's working before the if statements.But it seems that the if statements are not taking the output of os.path.isfile function.What should I do to make this code work?

Body:
can you strip fadress before using it and join paths using path.join?

path.isfile(path.join(fadress.strip(), newname))

(or) strip it while reading fadress itself?

fadress = input("What is your file adress : ").strip()


问:
init a COO matrix from its attributes (data,row,col)
I have a script that computes the three attributes of the COO format:

```<code>data    COO format data array of the matrix
row     COO format row index array of the matrix
col     COO format column index array of the matrix
</code>```

And i want to use these three arrays to initialise a coo_matrix() in order to use the methods available to the coo_matrix class. What would be the fastest way to do that without changing the main script?

答:
scipy.sparse documentation

```<code>coo_matrix((data, (row, column)), [shape=(M, N)])
</code>```

Body:
I have a script that computes the three attributes of the COO format:

data    COO format data array of the matrix
row     COO format row index array of the matrix
col     COO format column index array of the matrix

And i want to use these three arrays to initialise a coo_matrix() in order to use the methods available to the coo_matrix class. What would be the fastest way to do that without changing the main script?

Body:
scipy.sparse documentation

coo_matrix((data, (row, column)), [shape=(M, N)])


问:
How I search a string in core data with swift 3?
I want to search a string in my DB and it keeps returning all records from core data. The other questions I saw here didn't work. Suggestions? </p>

```<code>var users:[Users] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let myrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

        let predicate = NSPredicate(format: "name = '%@'", "alex")
        myrequest.predicate = predicate

        do{
            users = try context.fetch(myrequest) as! [Users]

        }catch{
            print("error")
        }

    }
</code>```

答:
You should not use single quotes in your predicate. Try with this:</p>

```<code>let predicate = NSPredicate(format: "name = %@", "alex")
myrequest.predicate = predicate
</code>```

Body:
I want to search a string in my DB and it keeps returning all records from core data. The other questions I saw here didn't work. Suggestions?

var users:[Users] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let myrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

        let predicate = NSPredicate(format: "name = '%@'", "alex")
        myrequest.predicate = predicate

        do{
            users = try context.fetch(myrequest) as! [Users]

        }catch{
            print("error")
        }

    }

Body:
You should not use single quotes in your predicate. Try with this:

let predicate = NSPredicate(format: "name = %@", "alex")
myrequest.predicate = predicate


问:
Unexpected Token @ when using babel decorator
I am currently building a react project and have started incorporating redux using connect. I am using decorators to reference this i.e.

```<code>const mapStateToProps = (state) => {
    return {
        active: state.sortOrder
    }
};

@connect(mapStateToProps)
export default class SortFilter extends Component {
    //component code here
}
</code>```

SyntaxError: /Sort.js: Unexpected token (10:0)
      @connect(mapStateToProps)

THis is my webpack config which I have included the babel-transform-decorators and stage-0 preset (as this seemed to be a solution for others).

```<code>const PATH = require('path');

const webpack = require("webpack");

const ROOT = '../../../';

const APP_FOLDER = PATH.resolve(__dirname, ROOT, 'app/');
const APP_ENTRY_FILE = PATH.resolve(__dirname, ROOT, APP_FOLDER, 'client.js');

const BUILD_FOLDER = PATH.resolve(__dirname, ROOT, 'app/public/js/');
const PUBLIC_PATH = '/js/';

const BUILD_FILE = 'app.js';

const ESLINT_CONFIG_FILE = PATH.resolve(__dirname, ROOT, 'tools/build/config/eslint-config.json');

var webpackConfig = {
entry: {
    app: APP_ENTRY_FILE
},
output: {
    path: BUILD_FOLDER,
    publicPath: PUBLIC_PATH,
    filename: BUILD_FILE
},
devtool: 'inline-source-map',
debug: true,
bail: true,
eslint: {
    configFile: ESLINT_CONFIG_FILE
},
module: {
    preLoaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'eslint-loader'
        }
    ],
    loaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'babel',
            query: {
                compact: false,
                cacheDirectory: true,
                presets: ['es2015', 'react', 'stage-0'],
                plugins: ['transform-decorators-legacy']
            }
        }
    ]
},
externals: {
    'axios': 'axios',
    'react': 'React',
    'react-router': 'ReactRouter',
    'history': 'History',
    'react-dom': 'ReactDOM'
},
plugins: [
    new webpack.NoErrorsPlugin()
]
};

module.exports = webpackConfig;
</code>```

Any help in solving this would be much appreciated.

答:
You need to install babel-plugin-transform-decorators:

```<code>npm install babel-plugin-transform-decorators-legacy --save-dev
</code>```

then add in .babelrc:

```<code>"plugins": ["transform-decorators-legacy"]
</code>```

Body:
I am currently building a react project and have started incorporating redux using connect. I am using decorators to reference this i.e.

const mapStateToProps = (state) => {
    return {
        active: state.sortOrder
    }
};

@connect(mapStateToProps)
export default class SortFilter extends Component {
    //component code here
}

SyntaxError: /Sort.js: Unexpected token (10:0)
      @connect(mapStateToProps)

THis is my webpack config which I have included the babel-transform-decorators and stage-0 preset (as this seemed to be a solution for others).

const PATH = require('path');

const webpack = require("webpack");

const ROOT = '../../../';

const APP_FOLDER = PATH.resolve(__dirname, ROOT, 'app/');
const APP_ENTRY_FILE = PATH.resolve(__dirname, ROOT, APP_FOLDER, 'client.js');

const BUILD_FOLDER = PATH.resolve(__dirname, ROOT, 'app/public/js/');
const PUBLIC_PATH = '/js/';

const BUILD_FILE = 'app.js';

const ESLINT_CONFIG_FILE = PATH.resolve(__dirname, ROOT, 'tools/build/config/eslint-config.json');

var webpackConfig = {
entry: {
    app: APP_ENTRY_FILE
},
output: {
    path: BUILD_FOLDER,
    publicPath: PUBLIC_PATH,
    filename: BUILD_FILE
},
devtool: 'inline-source-map',
debug: true,
bail: true,
eslint: {
    configFile: ESLINT_CONFIG_FILE
},
module: {
    preLoaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'eslint-loader'
        }
    ],
    loaders: [
        {
            test: /\.js$/,
            include: [
                APP_FOLDER
            ],
            loader: 'babel',
            query: {
                compact: false,
                cacheDirectory: true,
                presets: ['es2015', 'react', 'stage-0'],
                plugins: ['transform-decorators-legacy']
            }
        }
    ]
},
externals: {
    'axios': 'axios',
    'react': 'React',
    'react-router': 'ReactRouter',
    'history': 'History',
    'react-dom': 'ReactDOM'
},
plugins: [
    new webpack.NoErrorsPlugin()
]
};

module.exports = webpackConfig;

Any help in solving this would be much appreciated.

Body:
You need to install babel-plugin-transform-decorators:

npm install babel-plugin-transform-decorators-legacy --save-dev

then add in .babelrc:

"plugins": ["transform-decorators-legacy"]


问:
Python : AttributeError: 'int' object has no attribute 'append'
I have a dict of int, list. What I'm trying to do is loop through `something' and if the key is present in the dict add the item to the lsit or else create a new list and add the item.
This is my code.

```<code>levels = {}
if curr_node.dist in levels:
   l = levels[curr_node.dist]
   l.append(curr_node.tree_node.val)...........***
else:
   levels[curr_node.dist] = []
   levels[curr_node.dist].append(curr_node.tree_node.val)
   levels[curr_node.dist] = curr_node.tree_node.val
</code>```

My question is two-fold.
1. I get the following error,
Line 27: AttributeError: 'int' object has no attribute 'append'
Line 27 is the line marked with ***
What am I missing that's leading to the error.

How can I run this algorithm of checking key and adding to a list in a dict more pythonically.

答:
You set a list first, then replace that list with the value:

```<code>else:
   levels[curr_node.dist] = []
   levels[curr_node.dist].append(curr_node.tree_node.val)
   levels[curr_node.dist] = curr_node.tree_node.val
</code>```

Drop that last line, it breaks your code.

Instead of using if...else, you could use the dict.setdefault() method to assign an empty list when the key is missing, and at the same time return the value for the key:

```<code>levels.setdefault(curr_node.dist, []).append(curr_node.tree_node.val)
</code>```

This one line replaces your 6 if: ... else ... lines.

You could also use a collections.defaultdict() object:

```<code>from collections import defaultdict

levels = defaultdict(list)
</code>```

and

```<code>levels[curr_node.dist].append(curr_node.tree_node.val)
</code>```

For missing keys a list object is automatically added. This has a downside: later code with a bug in it that accidentally uses a non-existing key will get you an empty list, making matters confusing when debugging that error.

Body:
I have a dict of int, list. What I'm trying to do is loop through `something' and if the key is present in the dict add the item to the lsit or else create a new list and add the item.
This is my code.

levels = {}
if curr_node.dist in levels:
   l = levels[curr_node.dist]
   l.append(curr_node.tree_node.val)...........***
else:
   levels[curr_node.dist] = []
   levels[curr_node.dist].append(curr_node.tree_node.val)
   levels[curr_node.dist] = curr_node.tree_node.val

My question is two-fold.
1. I get the following error,
Line 27: AttributeError: 'int' object has no attribute 'append'
Line 27 is the line marked with ***
What am I missing that's leading to the error.

How can I run this algorithm of checking key and adding to a list in a dict more pythonically.

Body:
You set a list first, then replace that list with the value:

else:
   levels[curr_node.dist] = []
   levels[curr_node.dist].append(curr_node.tree_node.val)
   levels[curr_node.dist] = curr_node.tree_node.val

Drop that last line, it breaks your code.

Instead of using if...else, you could use the dict.setdefault() method to assign an empty list when the key is missing, and at the same time return the value for the key:

levels.setdefault(curr_node.dist, []).append(curr_node.tree_node.val)

This one line replaces your 6 if: ... else ... lines.

You could also use a collections.defaultdict() object:

from collections import defaultdict

levels = defaultdict(list)

and

levels[curr_node.dist].append(curr_node.tree_node.val)

For missing keys a list object is automatically added. This has a downside: later code with a bug in it that accidentally uses a non-existing key will get you an empty list, making matters confusing when debugging that error.


问:
Laravel: Compare two dates against today with Eloquent
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

```<code>public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}
</code>```

答:
use where date function like this   </p>

```<code>$today = Carbon::now();
$event = Event::with('businesses')
           ->whereDate('startdate', '<', $today->format('Y-m-d'))
           ->whereDate('enddate', '>', $today->format('Y-m-d'))
           ->get();
</code>```

Body:
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}

Body:
use where date function like this

$today = Carbon::now();
$event = Event::with('businesses')
           ->whereDate('startdate', '<', $today->format('Y-m-d'))
           ->whereDate('enddate', '>', $today->format('Y-m-d'))
           ->get();


问:
How to initialize a a struct of structs inside a header file in C?
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system.  In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize.  I am getting warnings when I compile with the way the legacy code was written.  Any tips on how I can get this to work with staying inside the same header file?

The following is a simplified example I made of what they are doing.

```<code>struct A
{

    struct B  temp1;
    struct C  temp2;
};

struct B
{

    int temp3;
    int temp4;
    int temp5;
};

struct C
{

    int temp6;
    int temp7;
    int temp8;
};

//These are the variables in how they are related to the initialization below

//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};

struct A test_one = {{1,2,3},{4,5,6}};
</code>```

答:
The code you posted is not compilable, since it is illegal to use incomplete type to declare struct members. I assume that you simply misarranged your struct definitions: the definitions for B and C should go first.

Having said that, the only warning this code can generate is the "warning" from linker that might complain about multiple definitions of the same object test_one, if the header file is included in multiple translation units. In C this is technically illegal, although many compilers allow it as a popular compiler extension.

So, what "warnings" are you getting?

Body:
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system.  In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize.  I am getting warnings when I compile with the way the legacy code was written.  Any tips on how I can get this to work with staying inside the same header file?

The following is a simplified example I made of what they are doing.

struct A
{

    struct B  temp1;
    struct C  temp2;
};

struct B
{

    int temp3;
    int temp4;
    int temp5;
};

struct C
{

    int temp6;
    int temp7;
    int temp8;
};

//These are the variables in how they are related to the initialization below

//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};

struct A test_one = {{1,2,3},{4,5,6}};