问:
Redirecting a path to the same container but different port with Traefik
I have the following setup with docker compose (running swarm mode):

```<code>mydomain.com --> ContainerA:8080
</code>```

But what I would like is through labels, specify the following for the same container:

```<code>mydomain.com/test --> ContainerA:80
mydomain.com --> ContainerA:8080
</code>```

So far I have the following Labels in compose:

```<code>deploy:
  labels:
    - traefik.port=8080
    - traefik.docker.network=apps
    - traefik.protocol=http
    - traefik.frontend.rule=Host:mydomain.com
</code>```

Thanks in advance

EDIT:

Now I have tried with this, following your advice.Here is what I have set up, but still doesn't work, I get a 404 error:

- traefik.docker.network=apps
 - traefik.main.protocol=http
 - traefik.main.port=8069
 - traefik.main.frontend.rule=Host:odoo.mydomain.com
 - traefik.worker.port=8072
 - traefik.worker.protocol=http
 - traefik.worker.frontend.rule=Host:odoo.mydomain.com;PathPrefixStrip:/longpolling

答:
If you need to bind multiple ports of a container, you have to use the traefik.<service-name>.* labels described here in the documentation.
For example,

```<code>deploy:
  labels:
    - traefik.first.port=80
    - traefik.first.frontend.rule=Host:mydomain.com;PathPrefixStrip:/test
    - traefik.second.port=8080
    - traefik.second.frontend.rule=Host:mydomain.com
</code>```

Body:
I have the following setup with docker compose (running swarm mode):

mydomain.com --> ContainerA:8080

But what I would like is through labels, specify the following for the same container:

mydomain.com/test --> ContainerA:80
mydomain.com --> ContainerA:8080

So far I have the following Labels in compose:

deploy:
  labels:
    - traefik.port=8080
    - traefik.docker.network=apps
    - traefik.protocol=http
    - traefik.frontend.rule=Host:mydomain.com

Thanks in advance

EDIT:

Now I have tried with this, following your advice.Here is what I have set up, but still doesn't work, I get a 404 error:

- traefik.docker.network=apps
 - traefik.main.protocol=http
 - traefik.main.port=8069
 - traefik.main.frontend.rule=Host:odoo.mydomain.com
 - traefik.worker.port=8072
 - traefik.worker.protocol=http
 - traefik.worker.frontend.rule=Host:odoo.mydomain.com;PathPrefixStrip:/longpolling

Body:
If you need to bind multiple ports of a container, you have to use the traefik.<service-name>.* labels described here in the documentation.
For example,

deploy:
  labels:
    - traefik.first.port=80
    - traefik.first.frontend.rule=Host:mydomain.com;PathPrefixStrip:/test
    - traefik.second.port=8080
    - traefik.second.frontend.rule=Host:mydomain.com


来源: stackexchange

问:
Slick - Auto sliding to a new item that been added to the slide
I've been testing many way on the Slick slider add & remove function.

It worked fine until I want to try to make it automatically sliding to the new item that has been added to the slideshow by pressing the Add new slide button.

```<code>$('.js-add-slide').on('click', function() {
  slideIndex++;
  $('.add-remove').slick('slickAdd','<div><h3>' + slideIndex + '</h3></div>');
});

$('.js-remove-slide').on('click', function() {
  $('.add-remove').slick('slickRemove',slideIndex - 1);
  if (slideIndex !== 0){
    slideIndex--;
  }
});
</code>```

I've tried slickGoTo but it not work out as I want so I'm totally lost here.

答:
You were close in your codepen:

Try this:

```<code>$('.js-add-slide').on('click', function() {
  slideIndex++;
  var currentSlide = $('.slider-info').slick('slickCurrentSlide');
  $('.slider-info').slick('slickAdd','<div><h3>' + slideIndex + '</h3></div>');
  $('.slider-info').slick('slickGoTo', currentSlide + 1);
});
</code>```

You need to actually get the currentSlide, in your codepen you only passed the string 'slickCurrentSlide' and you did not call the method slickCurrentSlideof the slick object.

Here the working codepen

ContentLicense: CC BY-SA 3.0

Body:
I've been testing many way on the Slick slider add & remove function.

It worked fine until I want to try to make it automatically sliding to the new item that has been added to the slideshow by pressing the Add new slide button.

$('.js-add-slide').on('click', function() {
  slideIndex++;
  $('.add-remove').slick('slickAdd','

' + slideIndex + '

');
});

$('.js-remove-slide').on('click', function() {
  $('.add-remove').slick('slickRemove',slideIndex - 1);
  if (slideIndex !== 0){
    slideIndex--;
  }
});

I've tried slickGoTo but it not work out as I want so I'm totally lost here.

Body:
You were close in your codepen:

Try this:

$('.js-add-slide').on('click', function() {
  slideIndex++;
  var currentSlide = $('.slider-info').slick('slickCurrentSlide');
  $('.slider-info').slick('slickAdd','<div><h3>' + slideIndex + '</h3></div>');
  $('.slider-info').slick('slickGoTo', currentSlide + 1);
});

You need to actually get the currentSlide, in your codepen you only passed the string 'slickCurrentSlide' and you did not call the method slickCurrentSlideof the slick object.

Here the working codepen


问:
Data Store for a Mac/iPhone Hybrid App
I've been doing iPhone development for the last 5 months or so, and have been using Gus Mueller's FMDB for database interaction. My next project will have both a Mac and an iPhone application, and they will share data between them, although in the end, the iPhone will be mostly a viewer app, with some minor editing capabilities.

My question is this: Will Core Data make my life easy enough on the Mac side, that it would be worth it to write my data model twice, using Core Data on the Mac, and FMDB on the iPhone? Or should I just use FMDB for both so that I can reuse the same code for both the Mac and iPhone?

I've poked at Core Data a little, but not much (mostly just the examples in the Hillegas book), so any specific examples in favor of Core Data would be greatly appreciated. For the record, I really like FMDB, I'm just wondering if Core Data would make my life that much easier in this situation.

Edit:
I understand the core differences between FMDB and Core Data, I'm mostly looking to find out if what Core Data provides "for free" makes it worth coding my data model twice.

答: You may also want to investigate the OmniDataObjects framework from the OmniGroup. It implements a subset of the CoreData functionality on top of SQLite on both OS X and iPhone OS. I believe they used it in both the OS X and iPhone versions of OmniFocus.</p>

OwnerDisplayName: shauber

ContentLicense: CC BY-SA 2.5

Title: Data Store for a Mac/iPhone Hybrid App

LastEditorDisplayName: shauber

OwnerDisplayName: Barry Wark


问:
MASM32 Overwriting a file using assembly
I'm currently doing an encryption in some of my files as an exercise. However, I'm having a trouble in overwriting a .txt file and having a hard time identifying what went wrong. Below is the part of the code I've been working on which I think has the problem.

```<code>  push 0
  push FILE_ATTRIBUTE_NORMAL
  push OPEN_EXISTING
  push 0
  push 0
  push FILE_READ_DATA
  push offset fData.cFileName
  call CreateFile

  mov hndl, eax

  push 0
  push hndl
  call GetFileSize

  mov fSize, eax

  push 0
  push offset bfrLen
  push fSize
  push offset bfr
  push hndl
  call ReadFile

  push hndl
  call CloseHandle

  lea esi, bfr
  mov al, [esi]
  cmp al, 7fh
  jg skip
  encrypt:
    mov al, [esi]
    xor al, 0ffh
    mov [esi], al
    inc esi
    mov al, [esi]
    cmp al, 00h
    jne encrypt

  push 0
  push FILE_ATTRIBUTE_NORMAL
  push CREATE_ALWAYS
  push 0
  push 0
  push FILE_WRITE_DATA
  push offset file
  call CreateFile

  mov hndl, eax

  push offset bfr
  call lstrlen

  push 0
  push offset bfrLen
  push fSize
  push offset bfr
  push hndl
  call WriteFile

  push hndl
  call CloseHandle

  skip:
    ret
</code>```

Review my code, guys! Thanks in advance.

答:
```<code>mov al, [esi]
cmp al, 7fh
jg skip
</code>```

This is a useless test! Nothing can ever be greater (signed byte) than 127.

Perhaps you meant to test for the above (unsigned byte) condition?

```<code>cmp byte [esi], 7Fh
ja  skip             ;Skip if from 128 to 255
</code>```

Just a thought. Maybe this test must be repeated with each iteration? We can't possibly know these details of your task.

Body:
I'm currently doing an encryption in some of my files as an exercise. However, I'm having a trouble in overwriting a .txt file and having a hard time identifying what went wrong. Below is the part of the code I've been working on which I think has the problem.

  push 0
  push FILE_ATTRIBUTE_NORMAL
  push OPEN_EXISTING
  push 0
  push 0
  push FILE_READ_DATA
  push offset fData.cFileName
  call CreateFile

  mov hndl, eax

  push 0
  push hndl
  call GetFileSize

  mov fSize, eax

  push 0
  push offset bfrLen
  push fSize
  push offset bfr
  push hndl
  call ReadFile

  push hndl
  call CloseHandle

  lea esi, bfr
  mov al, [esi]
  cmp al, 7fh
  jg skip
  encrypt:
    mov al, [esi]
    xor al, 0ffh
    mov [esi], al
    inc esi
    mov al, [esi]
    cmp al, 00h
    jne encrypt

  push 0
  push FILE_ATTRIBUTE_NORMAL
  push CREATE_ALWAYS
  push 0
  push 0
  push FILE_WRITE_DATA
  push offset file
  call CreateFile

  mov hndl, eax

  push offset bfr
  call lstrlen

  push 0
  push offset bfrLen
  push fSize
  push offset bfr
  push hndl
  call WriteFile

  push hndl
  call CloseHandle

  skip:
    ret

Review my code, guys! Thanks in advance.

Body:
mov al, [esi]
cmp al, 7fh
jg skip

This is a useless test! Nothing can ever be greater (signed byte) than 127.

Perhaps you meant to test for the above (unsigned byte) condition?

cmp byte [esi], 7Fh
ja  skip             ;Skip if from 128 to 255

Just a thought. Maybe this test must be repeated with each iteration? We can't possibly know these details of your task.


问:
Prototype.js 1.7 uncaught exception: Syntax error, unrecognized expression: [object HTMLInputElement]
This code worked for Prototype.js 1.6, but since upgrading to 1.7 i get an error: uncaught exception: Syntax error, unrecognized expression: [object HTMLInputElement]

```<code>document.observe('dom:loaded', function() {
    $$('.validate-length').each(function(elem) {
        var note = elem.next('.note');
        var counter = new Element('span');
        note.insert(counter);

        var curLen = $(elem).getValue().length;
        var maxLen = elem.className.match(/maximum-length-(\d+)/)[1];
        var count  = maxLen - curLen;

        if (curLen >= maxLen) {
            counter.update(' (-' + count + ')').setStyle({'color': 'red'});
        } else {
            counter.update(' (+' + count + ')').setStyle({'color': 'green'});
        }

        $$(elem).invoke('observe', 'keyup', function() {
            var curLen = $(elem).getValue().length;
            var count  = maxLen - curLen;
            if (curLen >= maxLen) {
                counter.update(' (-' + count + ')').setStyle({'color': 'red'});
            } else {
                counter.update(' (+' + count + ')').setStyle({'color': 'green'});
            }
        });
    });
});
</code>```

Seems something is wrong here: $$(elem).invoke('observe', 'keyup', function() {

Appreciate any help.

答:
When you are inside an enumerator, looping over a collection, your instance variable (elem) is a singular object, not a collection. So you want to use elem.observe('keyup', function() { ... }); to instantiate your observer.

The "double-dollar" function finds a collection of DOM elements that match the CSS selector passed as its first argument. But you've already done that at the top of the script, so now each member of that collection is already "found" (and extended with all of Prototype's methods), and does not need any further wrapping in order to be acted upon.

There's some optimizations available to you in this as well. You should create a single function to do the countdown, maybe using the addMethods factory to chain it on to the input's prototype, so you don't need to create a new anonymous function for each of your textareas. Next, if you have more than a very few of these inputs on each page, you might want to look at the "deferred observer" pattern to allow you to write one observer for the whole page, rather than creating a separate one for each input.

Examples, as requested:

```<code>Element.addMethods({
  // setup once, memoize the counter element and maxLen
  prepare_for_countdown: function(element){
    var elm = $(element);
    // even if you call it multiple times, it only works once
    if(!elm.retrieve('counter')){
      var counter = new Element('span');
      elm.next('.note').insert(counter);
      elm.store('counter', counter);
      var maxLen = elm.readAttribute('data-max-length');
      elm.store('maxLen', maxLen);
    }
    return elm; // so you can chain
  },
  // display the value, run once at load and on each observed keyup
  countdown: function(element){
    var elm = $(element);
    var curLen = elm.getValue().length;
    var maxLen = elm.retrieve('maxLen');
    var count  = maxLen - curLen;
    var counter = elm.retrieve('counter');
    if (curLen >= maxLen) {
      counter.update(' (' + count + ')').setStyle({'color': 'red'});
    } else {
      counter.update(' (+' + count + ')').setStyle({'color': 'green'});
    }
    return elm;
  }
});

// run setup and call countdown once outside of listener to initialize
$$('.validate-length').invoke('prepare_for_countdown').invoke('countdown');

// deferred listener, only responds to keyups that issue from a matching element
document.on('keyup', '.validate-length', function(evt, elm){
  elm.countdown();
});
</code>```

Body:
This code worked for Prototype.js 1.6, but since upgrading to 1.7 i get an error: uncaught exception: Syntax error, unrecognized expression: [object HTMLInputElement]

document.observe('dom:loaded', function() {
    $$('.validate-length').each(function(elem) {
        var note = elem.next('.note');
        var counter = new Element('span');
        note.insert(counter);

        var curLen = $(elem).getValue().length;
        var maxLen = elem.className.match(/maximum-length-(\d+)/)[1];
        var count  = maxLen - curLen;

        if (curLen >= maxLen) {
            counter.update(' (-' + count + ')').setStyle({'color': 'red'});
        } else {
            counter.update(' (+' + count + ')').setStyle({'color': 'green'});
        }

        $$(elem).invoke('observe', 'keyup', function() {
            var curLen = $(elem).getValue().length;
            var count  = maxLen - curLen;
            if (curLen >= maxLen) {
                counter.update(' (-' + count + ')').setStyle({'color': 'red'});
            } else {
                counter.update(' (+' + count + ')').setStyle({'color': 'green'});
            }
        });
    });
});

Seems something is wrong here: $$(elem).invoke('observe', 'keyup', function() {

Appreciate any help.

Body:
When you are inside an enumerator, looping over a collection, your instance variable (elem) is a singular object, not a collection. So you want to use elem.observe('keyup', function() { ... }); to instantiate your observer.

The "double-dollar" function finds a collection of DOM elements that match the CSS selector passed as its first argument. But you've already done that at the top of the script, so now each member of that collection is already "found" (and extended with all of Prototype's methods), and does not need any further wrapping in order to be acted upon.

There's some optimizations available to you in this as well. You should create a single function to do the countdown, maybe using the addMethods factory to chain it on to the input's prototype, so you don't need to create a new anonymous function for each of your textareas. Next, if you have more than a very few of these inputs on each page, you might want to look at the "deferred observer" pattern to allow you to write one observer for the whole page, rather than creating a separate one for each input.

Examples, as requested:

Element.addMethods({
  // setup once, memoize the counter element and maxLen
  prepare_for_countdown: function(element){
    var elm = $(element);
    // even if you call it multiple times, it only works once
    if(!elm.retrieve('counter')){
      var counter = new Element('span');
      elm.next('.note').insert(counter);
      elm.store('counter', counter);
      var maxLen = elm.readAttribute('data-max-length');
      elm.store('maxLen', maxLen);
    }
    return elm; // so you can chain
  },
  // display the value, run once at load and on each observed keyup
  countdown: function(element){
    var elm = $(element);
    var curLen = elm.getValue().length;
    var maxLen = elm.retrieve('maxLen');
    var count  = maxLen - curLen;
    var counter = elm.retrieve('counter');
    if (curLen >= maxLen) {
      counter.update(' (' + count + ')').setStyle({'color': 'red'});
    } else {
      counter.update(' (+' + count + ')').setStyle({'color': 'green'});
    }
    return elm;
  }
});

// run setup and call countdown once outside of listener to initialize
$$('.validate-length').invoke('prepare_for_countdown').invoke('countdown');

// deferred listener, only responds to keyups that issue from a matching element
document.on('keyup', '.validate-length', function(evt, elm){
  elm.countdown();
});


问:
Alternative to using relationship with SQLite
I'm creating an app which is going to have some data that is stored in an SQLite database. I want the user to be able to create "folders" which can be assigned to each data item.

I was going to do this using a one to many relationship e.g. one "folder" can have many data objects under it but having looked at relationships with SQLite and Android it seems that this would only work in 2.2+ so I'm just wondering what the alternative is?

Any information is much appreciated.

答: You can still have relationships; older versions of SQLite just won't enforce them.  As a stopgap, you can build triggers to do it; in fact there's a handy generator that will generate the SQL for you to use as a starting point.</p>


问:
Watch website and wait for events
I want to analyze a website that is not mine.
So, I want to use Javascript to do it at my end in the browser.
After I click a button on the website I want to trigger a timer and as soon as a notification from the website comes back, the timer should stop and save the notification that came back.
How can I do this the easiest way?

I cannot give you the link to the website, because it's hosted in a private network.

My first question would be, how I can log all events that are triggered on a website to the console, so I know the name of the button I want to wait for.

Thanks!
dave

答:
All events on a specific DOM node:

To see all the events for a specific DOMnode, or window (only works on chrome i believe, didnt test it elsewhere):

```<code>getEventListeners(window)
</code>```

this will give you an object with all the events, then you can intercept them with

```<code>window.addEventListener(eventName, fn, true);
</code>```

The whole application:

this way your event will be called whenever an event on that node is triggered (window in this case)

if you want absolutely all events on the whole app, you can achieve it with using something like firebug

Specific event on a specific element:

if you want a button click only, you can do the following:

```<code>var specificButton = document.querySelector('#specific-button')
specificButton.addEventListener('click', function() {});
</code>```

Implementation:

if you do not own the sourcecode, you can use something like greasemonkey or tampermonkey to inject your javascript into the page.

if you are using it on a server, you can use cheerio to parse the returned html from the get request, and apply queries on it, but you will lose the ability for listening to live events from io devices.

Title: Watch website and wait for events

Body:
All events on a specific DOM node:

To see all the events for a specific DOMnode, or window (only works on chrome i believe, didnt test it elsewhere):

getEventListeners(window)

this will give you an object with all the events, then you can intercept them with

window.addEventListener(eventName, fn, true);

The whole application:

this way your event will be called whenever an event on that node is triggered (window in this case)

if you want absolutely all events on the whole app, you can achieve it with using something like firebug

Specific event on a specific element:

if you want a button click only, you can do the following:

var specificButton = document.querySelector('#specific-button')
specificButton.addEventListener('click', function() {});

Implementation:

if you do not own the sourcecode, you can use something like greasemonkey or tampermonkey to inject your javascript into the page.

if you are using it on a server, you can use cheerio to parse the returned html from the get request, and apply queries on it, but you will lose the ability for listening to live events from io devices.


问:
Batch insert in documentdb using java driver
I'm using the java-sdk for CRUD operation in cosmosdb, I was able to do basic insert of a employee DTO and all looks good. But now I want to do batch insert and could not able to find appropriate api for this.

I come across the cosmosdb documentation where they are recommend using stored procedure(server side JS) but I prefer a direct java driver option like other nosql provides are giving.

Is there anything I'm missing and which one will be preferable, the stored procedure or the java driver option(if exist)? Below is the code snippet I'm using for inserting single document.

```<code>documentClient.createDocument(getCollection().getSelfLink(), document, null, false).getResource();
</code>```

答:
On the client side, you may do single writes to  your collection, just like you're currently doing.  There is no client side batch insert API call.

With a stored procedure, you would be able to pass any payload you wanted to the stored proc,and then you could transactionally insert multiple documents to a collection (or  a partition  if using a partitioned collection). With a single client side call to that stored procedure.

So, using a stored procedure, you're still able to do a single client side call, effectively accomplishing what you're specifically looking for. You'll just need to set up your payload appropriately so that your stored procedure code can separate each individual document to be inserted.

Body:
I'm using the java-sdk for CRUD operation in cosmosdb, I was able to do basic insert of a employee DTO and all looks good. But now I want to do batch insert and could not able to find appropriate api for this.

I come across the cosmosdb documentation where they are recommend using stored procedure(server side JS) but I prefer a direct java driver option like other nosql provides are giving.

Is there anything I'm missing and which one will be preferable, the stored procedure or the java driver option(if exist)? Below is the code snippet I'm using for inserting single document.

documentClient.createDocument(getCollection().getSelfLink(), document, null, false).getResource();


问:
Delete data from datatable via AJAX call
I have a view where I have AJAX call

Here is code of AJAX request, it's just hit method on back end:

```<code><script>
// deleting
$("#send").click(
    function sender() {
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            type: 'Post',
            dataType: 'json',
            processData: false,
            url: '@Url.Action("DeleteAll", "Questions")',
            success: function(da) {
                if (da.Result === "Success") {

                    alert("Data deleted!");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function(da) {
                alert('Error');
            }
        });
    });
</code>```

And method on back end

```<code>public ActionResult DeleteAll()
{
    ApplicationDbContext context =  new ApplicationDbContext();
    List<InvitationMail> query = context.InvitationMails.ToList();
    foreach (InvitationMail q in query)
    {
        context.DeleteObject(q);
    }
    context.SaveChanges();
    return Json(new {Result = "Success", Message = "Saved Successfully"});
}
</code>```

But I have this error

I need to delete all data from  InvitationMail table, how I can do this?

答:
Use Removerange function its work much faster than foreach:

```<code>List<InvitationMail> query = context.InvitationMails.ToList();
context.InvitationMails.Removerange(query);
context.SaveChanges();
</code>```

Body:
Use Removerange function its work much faster than foreach:

List<InvitationMail> query = context.InvitationMails.ToList();
context.InvitationMails.Removerange(query);
context.SaveChanges();


问:
Tic Tac Toe how to tell user there is no winner?
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.</p>

```<code>public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

答:
Currently you are not going to track no winner, as your if() check for a line of same symbols which were played.

No winner means no line of the same symbols, but the fact that the board is full. You can count not-plaid (count 2s in your array) or increment a counter each time a symbol is played. As soon as you plaid 9 but there is no winning line, then it's a draw.

```<code>if(gameState[winningPostion[0]] == gameState[winningPostion[1]]
                && gameState[winningPostion[1]] == gameState[winningPostion[2]]
                && gameState[winningPostion[0]] !=2 ) {
    //somebody has scored a line, but who?
} else if (haveWePlayed9()) {
    //no winner
}
</code>```

Body:
I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O  wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }

}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Body:
Currently you are not going to track no winner, as your if() check for a line of same symbols which were played.

No winner means no line of the same symbols, but the fact that the board is full. You can count not-plaid (count 2s in your array) or increment a counter each time a symbol is played. As soon as you plaid 9 but there is no winning line, then it's a draw.

if(gameState[winningPostion[0]] == gameState[winningPostion[1]]
                && gameState[winningPostion[1]] == gameState[winningPostion[2]]
                && gameState[winningPostion[0]] !=2 ) {
    //somebody has scored a line, but who?
} else if (haveWePlayed9()) {
    //no winner
}


问:
SQL Server Group By with Multiplication
I have this SQL Server 2005 Query

```<code>SELECT OI.BILL_NO,OI.ITEM_NAME,ODS.QUANTITY
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
</code>```

I am getting this result :

Now my requirement is to to get the total Quantity of Every Distinct ITEM_NAME, Example:

```<code>CHURIDER           5
CHURI PA           4
LACHA              1
ASTRA              1
ASTRA LACHA DOUBLE 1
</code>```

like this,all Distinct ITEM_NAME and their Total Quantity

答:
This looks like a simple aggregation query with group by, and sum():

```<code>SELECT OI.ITEM_NAME,sum(ODS.QUANTITY) as Quantity
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
group by OI.ITEM_NAME
</code>```

Title: SQL Server Group By with Multiplication

Body:
I have this SQL Server 2005 Query

SELECT OI.BILL_NO,OI.ITEM_NAME,ODS.QUANTITY
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'

I am getting this result :

Now my requirement is to to get the total Quantity of Every Distinct ITEM_NAME, Example:

CHURIDER           5
CHURI PA           4
LACHA              1
ASTRA              1
ASTRA LACHA DOUBLE 1

like this,all Distinct ITEM_NAME and their Total Quantity

Body:
This looks like a simple aggregation query with group by, and sum():

SELECT OI.ITEM_NAME,sum(ODS.QUANTITY) as Quantity
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
group by OI.ITEM_NAME


问:
how to make a single Main Menu active(has the colour ) in Accordian menu - jquery , javascript
here is the fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/13/

As you can see the Menu 2  does not have any child item , how to make the 'Menu 2 ' to have color when clicked (same color which appears while hovering submenu )

JS

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

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });
</code>```

HTML

```<code><ul id="accordion" class="accordion">
<li>
                            <div class="link">Menu 1</div>
                            <ul class="submenu">
                                <li ><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                         <li>
                            <ul class="link">Menu 2</ul>
                        </li>
                        <li>
                            <div class="link">Menu 3</div>
                            <ul class="submenu">
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                        </ul>
</code>```

CSS

```<code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}
</code>```

答:
You can assign menu 2 with a new class with the background or color (.m2color)

add a toggleClass to menu2 with a click handler

Snippet edited to make slideUp work as well when re-clicking opened menu or menu2:

$(document).ready(function() {
  $("#accordion > li > div").on("click", function() {
    $(this).next().slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
      $(".menu2").removeClass("m2color");
    }
  });
  $(".menu2").on("click", function() {
    $(this).toggleClass("m2color");
    $("#accordion > li > div").next().slideUp();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

.m2color {
  background: #b63b4d;
  color: #FFF;
}</code>```

Menu 1

submenu1

submenu1

submenu1

Menu 2

Menu 3

submenu1

submenu1

submenu1

```
</div>
</div>
</p>

<p>Original Snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {

  $("#accordion > li > div").click(function() {
    $("#submenu li").slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
      //remove color when other menu option are clicked
      $(".menu2").removeClass("m2color");
    }
  });
  // you can remove the color by re-clicking on menu 2 as well
  $(".menu2").on("click", function() {
    $(this).toggleClass("m2color");
  })
});</code>```

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

/* new class*/

.m2color {
  background: #b63b4d;
  color: #FFF;
}```
<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>
<ul id="accordion" class="accordion">
  <li>
    <div class="link">Menu 1</div>
    <ul class="submenu">
      <li>submenu1</li>
      <li>submenu1</li>
      <li>submenu1</li>
    </ul>
  </li>
  <li>
    <ul class="link menu2">Menu 2</ul>
  </li>
  <li>
    <div class="link">Menu 3</div>
    <ul class="submenu">
      <li>submenu1</li>
      <li>submenu1</li>
      <li>submenu1</li>
    </ul>
  </li>
</ul></code>```

Body:
here is the fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/13/

As you can see the Menu 2  does not have any child item , how to make the 'Menu 2 ' to have color when clicked (same color which appears while hovering submenu )

JS

 $(document).ready(function () {

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });

HTML

Menu 1

submenu1

submenu1

submenu1

Menu 2

Menu 3

submenu1

submenu1

submenu1

CSS

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

Body:
You can assign menu 2 with a new class with the background or color (.m2color)

add a toggleClass to menu2 with a click handler

Snippet edited to make slideUp work as well when re-clicking opened menu or menu2:

$(document).ready(function() {
  $("#accordion > li > div").on("click", function() {
    $(this).next().slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
      $(".menu2").removeClass("m2color");
    }
  });
  $(".menu2").on("click", function() {
    $(this).toggleClass("m2color");
    $("#accordion > li > div").next().slideUp();
  })
});

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

.m2color {
  background: #b63b4d;
  color: #FFF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="accordion" class="accordion">
  <li>
    <div class="link">Menu 1</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
  <li>
    <ul class="link menu2">Menu 2</ul>
  </li>
  <li>
    <div class="link">Menu 3</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
</ul>

Original Snippet:

$(document).ready(function() {

  $("#accordion > li > div").click(function() {
    $("#submenu li").slideUp();
    if (!$(this).next().is(":visible")) {
      $(this).next().slideDown();
      //remove color when other menu option are clicked
      $(".menu2").removeClass("m2color");
    }
  });
  // you can remove the color by re-clicking on menu 2 as well
  $(".menu2").on("click", function() {
    $(this).toggleClass("m2color");
  })
});

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
  padding: 0px;
  display: none;
  font-size: 14px;
}

.submenu li {
  border-bottom: 1px solid #4b4a5e;
}

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color: #CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
  display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

/* new class*/

.m2color {
  background: #b63b4d;
  color: #FFF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="accordion" class="accordion">
  <li>
    <div class="link">Menu 1</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
  <li>
    <ul class="link menu2">Menu 2</ul>
  </li>
  <li>
    <div class="link">Menu 3</div>
    <ul class="submenu">
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
      <li><a href="#">submenu1</a></li>
    </ul>
  </li>
</ul>


问:
using vba i fetched 5000 records from db, how to loop to paste evrey 1000 records into a new worksheet?
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!</p>

```<code>Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub
</code>```

答:
CopyFromRecordset does not have the ability to do what you want to do.

You may want to look in to breaking your SQL into pieces using OFFSET-FETCH as shown here: http://www.dofactory.com/sql/order-by-offset-fetch

Body:
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!

Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub


问:
amazon payment gateway
Am doing one project ,

For that my client asked amazon payment gateway ,

So now i started exploring amazon payment gateway ,

This is the first time am looking the amazon payment gateway ,

I have registered in amazon payment gateway,

Please tell me  PHP CODE  snippet for amazon payment gateway ,

Thanks

答: For simple pay when account is created, user will be given a sandbox access in which you find the "Merchant code" at this URL : https://sandbox.simplepay.hu/admin/partner/account/id(partnerid) </p>

Title: amazon payment gateway


问:
What's the difference between traveling salesman and chinese traveling?
What's the difference between travelling salesman problem (TSP) and Chinese postman problem (CPP)?

For me, both wants go to a destination, and then back.

答:
The travelling salesman problem is about going to each city once and taking the shortest route.

The Chinese postman problem is about getting a path from each city to each other city.

E.g., with points A, B, C, and D, the travelling salesman could go A-B-C-D-A, but the Chinese postman would go need a route that had A-B and A-C and A-D, etc.

The travelling salesman route does not have a direct between each point (in the above example there is no A-C link).

Each city is a vertex and each inter-city link is an edge. So, I think I'm just restating Xodarap's answer.

ContentLicense: CC BY-SA 4.0


问:
Express JS node framework did not respond to post() request
I'm following a blog to build my first node API with express framework. But the POST request did not return a response.

```<code>const app = express();

require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

module.exports = function(app, db) {
  console.log('reached2');
  app.post('/notes', (req, res) => {
    // You'll create your note here.
    console.log('reached3');
    res.send('Hello');
    //res.end();;
  });
};
</code>```

Here are my console logs,

```<code>reached1
reached2
We are live on 8000
</code>```

Here are my dependencies,

```<code>"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.28"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
</code>```

Im using the postman client to POST.

I tried replacing the fat arrow operator with an anonymous function but still doesnt work.

Please point the problem in this code.

答:
If you want to keep your routes in a separate file (which is fairly standard practice), then you need to return a router and tell the express app to use it.

app.js

```<code>const express = require('express');
const routes = require('./routes')({});

const app = express();

app.use('/', routes);

app.listen(8080, () => {
    console.log('Listening on 8080');
})
</code>```

routes.js

```<code>const express = require('express');

module.exports = (db) => {

    const router = express.Router();

    router.post('/notes', (req, res) => {
        res.send('Hello!');
    })

    // all your other routes here!

    return router;

}
</code>```

Or, alternatively if you want to do it without using using express.Router(), you could pass the app.

app.js

```<code>const express = require('express');

const app = express();

require('./routes')(app, {});

app.listen(8080, () => {
    console.log('Listening on 8080');
})
</code>```

routes.js

```<code>module.exports = (app, db) => {

    app.post('/notes', (req, res) => {
        res.send('Hello!');
    })

}
</code>```

Body:
I'm following a blog to build my first node API with express framework. But the POST request did not return a response.

const app = express();

require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('We are live on ' + port);
});

module.exports = function(app, db) {
  console.log('reached2');
  app.post('/notes', (req, res) => {
    // You'll create your note here.
    console.log('reached3');
    res.send('Hello');
    //res.end();;
  });
};

Here are my console logs,

reached1
reached2
We are live on 8000

Here are my dependencies,

"dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "mongodb": "^2.2.28"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }

Im using the postman client to POST.

I tried replacing the fat arrow operator with an anonymous function but still doesnt work.

Please point the problem in this code.

Body:
If you want to keep your routes in a separate file (which is fairly standard practice), then you need to return a router and tell the express app to use it.

app.js

const express = require('express');
const routes = require('./routes')({});

const app = express();

app.use('/', routes);

app.listen(8080, () => {
    console.log('Listening on 8080');
})

routes.js

const express = require('express');

module.exports = (db) => {

    const router = express.Router();

    router.post('/notes', (req, res) => {
        res.send('Hello!');
    })

    // all your other routes here!

    return router;

}

Or, alternatively if you want to do it without using using express.Router(), you could pass the app.

app.js

const express = require('express');

const app = express();

require('./routes')(app, {});

app.listen(8080, () => {
    console.log('Listening on 8080');
})

routes.js

module.exports = (app, db) => {

    app.post('/notes', (req, res) => {
        res.send('Hello!');
    })

}


问:
How to convert string into an IP Address?
I am using a function to adding . after every three characters inside the string. But how can i remove "0" in front of number.

```<code>-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
    NSMutableString *macAddressWithColon = [NSMutableString new];
    for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
    {
        if (i > 0 && i % 3 == 0)
            [macAddressWithColon appendString:@"."];
        unichar c = [MacAddressWithoutColon characterAtIndex:i];
        [macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
    }
    return macAddressWithColon;
}
</code>```

If i have ip address 010.000.001.016
How can i set it up like 10.0.1.16? and if i have ip address 192.168.001.001? how to remove front 0's from IP address ?

答:
You can use string function and get your expected output with the help of componentsSeparatedByString and componentsJoinedByString functions.

Use below method for the same:

```<code>-(NSString*)removeZeroPrefix:(NSString*)aStrIP{

    NSMutableArray *subStringArray = [[NSMutableArray alloc] init];

    NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:@"."];

    for (NSString *aSingleString in arrayOfSubString)
    {
        [subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
    }

    return [subStringArray componentsJoinedByString:@"."];

}
</code>```

Usage :

```<code>[self removeZeroPrefix:@"010.000.001.016"];
[self removeZeroPrefix:@"192.168.001.001"];
</code>```

Output :

```<code>Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1
</code>```

hope this will helps!

Body:
I am using a function to adding . after every three characters inside the string. But how can i remove "0" in front of number.

-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
    NSMutableString *macAddressWithColon = [NSMutableString new];
    for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
    {
        if (i > 0 && i % 3 == 0)
            [macAddressWithColon appendString:@"."];
        unichar c = [MacAddressWithoutColon characterAtIndex:i];
        [macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
    }
    return macAddressWithColon;
}

If i have ip address 010.000.001.016
How can i set it up like 10.0.1.16? and if i have ip address 192.168.001.001? how to remove front 0's from IP address ?

Body:
You can use string function and get your expected output with the help of componentsSeparatedByString and componentsJoinedByString functions.

Use below method for the same:

-(NSString*)removeZeroPrefix:(NSString*)aStrIP{

    NSMutableArray *subStringArray = [[NSMutableArray alloc] init];

    NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:@"."];

    for (NSString *aSingleString in arrayOfSubString)
    {
        [subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
    }

    return [subStringArray componentsJoinedByString:@"."];

}

Usage :

[self removeZeroPrefix:@"010.000.001.016"];
[self removeZeroPrefix:@"192.168.001.001"];

Output :

Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1

hope this will helps!


答:
What I would suggest:

```<code>    NSString *ipAddress = @"010.000.001.016";
</code>```

Split string into array of substrings:

```<code>NSArray *ipAddressComponents = [myString componentsSeparatedByString:@"."];
</code>```

Run through the array with for loop and convert each to a int representation:

```<code>for(int i = 0; i < ipAddressComponents.count;i++)
{
    [ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:@"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}
</code>```

Join the array back into a string

```<code>NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:@"."];
</code>```

This should result into getting an IP address: 10.0.1.16

Title: How to convert string into an IP Address?

Body:
What I would suggest:

    NSString *ipAddress = @"010.000.001.016";

Split string into array of substrings:

NSArray *ipAddressComponents = [myString componentsSeparatedByString:@"."];

Run through the array with for loop and convert each to a int representation:

for(int i = 0; i < ipAddressComponents.count;i++)
{
    [ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:@"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}

Join the array back into a string

NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:@"."];

This should result into getting an IP address: 10.0.1.16


问:
Alternative to enquote_literal for string containing single quote
I am bound to use dbms_assert.enquote_literal to enquote string. The string is schema name which is unknown to me as it is coming as a parameter to my function. The only thing I know is that a schema name may contain single quote. For such strings enquote_literal fails with ORA-06502: PL/SQL: numeric or value error. Is there any alternative that I can use in place of enquote_literal that gives the same output as enquote_literal.

答:
Not a good solution, but an easy solution is

```<code>REPLACE(dbms_assert.enquote_literal(REPLACE(text,'''','''''')),
    '''''','''');
</code>```

Input Text

```<code>hello'world
</code>```

Output Text

```<code>'hello'world'
</code>```

If you don't need the quote to appear even once

```<code>dbms_assert.enquote_literalreplace(text,'''',''));
</code>```

Body:
Not a good solution, but an easy solution is

REPLACE(dbms_assert.enquote_literal(REPLACE(text,'''','''''')),
    '''''','''');

Input Text

hello'world

Output Text

'hello'world'

If you don't need the quote to appear even once

dbms_assert.enquote_literalreplace(text,'''',''));


问:
java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.ClassCastException: cannot be cast to android.widget.Button
I tried to get this code working using android studio but the app in the emulator crashes everytime I run it and displays an error which is "App has stopped". I looked at the logcat and got this error.

Logcat:

02-11 12:39:49.826 4852-4852/co5025.example.com.week10 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: co5025.example.com.week10, PID: 4852
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{co5025.example.com.week10/co5025.example.com.week10.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                          Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
                                                                             at co5025.example.com.week10.MainActivity.onCreate(MainActivity.java:42)
                                                                             at android.app.Activity.performCreate(Activity.java:6664)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

MainActivity.java

```<code>package co5025.example.com.week10;

            import android.app.FragmentManager;
            import android.content.Intent;
            import android.os.Bundle;
            import android.support.design.widget.FloatingActionButton;
            import android.support.design.widget.Snackbar;
            import android.support.v7.app.AppCompatActivity;
            import android.support.v7.widget.Toolbar;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.Button;
            import android.widget.EditText;
            import android.widget.TextView;
            import android.support.v4.app.FragmentManager.BackStackEntry;

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {
                EditText editUsername;
                EditText editPassword;
                TextView errorMessage;
                Button butLogin;
                private FragmentManager.BackStackEntry v;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                    setSupportActionBar(toolbar);

                    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
                    fab.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                        }
                    });
                    editPassword    =   (EditText)  findViewById(R.id.edit_password);
                    editUsername    =   (EditText)  findViewById(R.id.edit_username);
                    butLogin    =   (Button) findViewById(R.id.edit_username);
                    butLogin.setOnClickListener(this);

                    if (getIntent().getBooleanExtra("EXIT", false)) finish();
                }

                @Override
                public void onClick(View view) {
                    if  (checkPassword())   {
                        Intent  i;
                        switch  (v.getId()) {
                            case    R.id.but_login:
                                i   =   new Intent(this,    GameActivity.class);
                                startActivity(i);
                                break;
                        }
                    }else{
                        errorMessage    =   (TextView)  findViewById(R.id.error_message);
                        errorMessage.setText("Error: Incorrect Password/Username. Try again!");
                    }
                }

                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                    // Inflate the menu; this adds items to the action bar if it is present.
                    getMenuInflater().inflate(R.menu.menu_main, menu);
                    return true;
                }

                @Override
                public boolean onOptionsItemSelected(MenuItem item) {
                    // Handle action bar item clicks here. The action bar will
                    // automatically handle clicks on the Home/Up button, so long
                    // as you specify a parent activity in AndroidManifest.xml.
                    int id = item.getItemId();

                    //noinspection SimplifiableIfStatement
                    if (id == R.id.action_settings) {
                        return true;
                    }

                    return super.onOptionsItemSelected(item);
                }

                public  boolean checkPassword(){
                    if  (editUsername.getText().toString().equals("test")   &&
                            (editPassword.getText().toString().equals("1234")))
                        return  true;
                    else
                        return  false;
                }
            }
</code>```

答:
According to this:
java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button at android.app

You are casting Button butLogin to your EditText

editUsername    =   (EditText)  findViewById(R.id.edit_username);
butLogin    =   (Button) findViewById(R.id.edit_username);

Here you are casting same Id to editUsername and butLogin

Body:
I tried to get this code working using android studio but the app in the emulator crashes everytime I run it and displays an error which is "App has stopped". I looked at the logcat and got this error.

Logcat:

02-11 12:39:49.826 4852-4852/co5025.example.com.week10 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: co5025.example.com.week10, PID: 4852
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{co5025.example.com.week10/co5025.example.com.week10.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                          Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatEditText cannot be cast to android.widget.Button
                                                                             at co5025.example.com.week10.MainActivity.onCreate(MainActivity.java:42)
                                                                             at android.app.Activity.performCreate(Activity.java:6664)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

MainActivity.java

package co5025.example.com.week10;

            import android.app.FragmentManager;
            import android.content.Intent;
            import android.os.Bundle;
            import android.support.design.widget.FloatingActionButton;
            import android.support.design.widget.Snackbar;
            import android.support.v7.app.AppCompatActivity;
            import android.support.v7.widget.Toolbar;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.Button;
            import android.widget.EditText;
            import android.widget.TextView;
            import android.support.v4.app.FragmentManager.BackStackEntry;

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {
                EditText editUsername;
                EditText editPassword;
                TextView errorMessage;
                Button butLogin;
                private FragmentManager.BackStackEntry v;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                    setSupportActionBar(toolbar);

                    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
                    fab.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                        }
                    });
                    editPassword    =   (EditText)  findViewById(R.id.edit_password);
                    editUsername    =   (EditText)  findViewById(R.id.edit_username);
                    butLogin    =   (Button) findViewById(R.id.edit_username);
                    butLogin.setOnClickListener(this);

                    if (getIntent().getBooleanExtra("EXIT", false)) finish();
                }

                @Override
                public void onClick(View view) {
                    if  (checkPassword())   {
                        Intent  i;
                        switch  (v.getId()) {
                            case    R.id.but_login:
                                i   =   new Intent(this,    GameActivity.class);
                                startActivity(i);
                                break;
                        }
                    }else{
                        errorMessage    =   (TextView)  findViewById(R.id.error_message);
                        errorMessage.setText("Error: Incorrect Password/Username. Try again!");
                    }
                }

                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                    // Inflate the menu; this adds items to the action bar if it is present.
                    getMenuInflater().inflate(R.menu.menu_main, menu);
                    return true;
                }

                @Override
                public boolean onOptionsItemSelected(MenuItem item) {
                    // Handle action bar item clicks here. The action bar will
                    // automatically handle clicks on the Home/Up button, so long
                    // as you specify a parent activity in AndroidManifest.xml.
                    int id = item.getItemId();

                    //noinspection SimplifiableIfStatement
                    if (id == R.id.action_settings) {
                        return true;
                    }

                    return super.onOptionsItemSelected(item);
                }

                public  boolean checkPassword(){
                    if  (editUsername.getText().toString().equals("test")   &&
                            (editPassword.getText().toString().equals("1234")))
                        return  true;
                    else
                        return  false;
                }
            }


问:
find -exec cant find local function "find: Log: No such file or directory"
i have a piece of code that should print all files in specific dir. i use find exec for this:

```<code>find ${_di} -type f -print -exec Log "$(stat -c%y {}) - {}" \;
</code>```

Where log is function of mine defines in same file.
But id does not work and i get error message:

"find: Log: No such file or directory".

Why? What is wrong in this piece of code?

答:
You need to export the function, and then, as Nahuel says, run bash in the -exec:

```<code>$ export -f Log

$ find ${_di} -type f -exec bash -c 'Log "$(stat -c%y {}) - {}"' bash \;
</code>```

Body:
i have a piece of code that should print all files in specific dir. i use find exec for this:

find ${_di} -type f -print -exec Log "$(stat -c%y {}) - {}" \;

Where log is function of mine defines in same file.
But id does not work and i get error message:

"find: Log: No such file or directory".

Why? What is wrong in this piece of code?

Body:
You need to export the function, and then, as Nahuel says, run bash in the -exec:

$ export -f Log

$ find ${_di} -type f -exec bash -c 'Log "$(stat -c%y {}) - {}"' bash \;


问:
ggplot pie chart labeling
I am struggling with getting the pie chart labels correct. Looked around and thought that I could easily implement what mathematicalCoffee did. So far I have this code:

```<code>ltr = LETTERS[seq( from = 1, to = 26)]

wght = runif(length(ltr))
wght = wght/sum(wght)
wght = round(wght, digits = 2)

alloc = as.data.frame(cbind(ltr, wght))
alloc$wght = as.numeric(as.character(alloc$wght))

ggpie <- function (dat, by, totals) {
  ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) +
    geom_bar(stat='identity', color='black') +
    guides(fill=guide_legend(override.aes=list(colour=NA))) +
    coord_polar(theta='y') +
    theme(axis.ticks=element_blank(),
          axis.text.y=element_blank(),
          axis.text.x=element_text(colour='black'),
          axis.title=element_blank()) +
    ## scale_fill_brewer(palette = "GnBu") +
    scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=paste(dat[[by]], ":", dat[[totals]]))
}

AA = ggpie(alloc, by = "ltr", totals = "wght") +
  ggtitle("Letter weights")

AA
</code>```

The resulting pie chart:

Is there any way to generate something like this, for example:

Update for suggested dup - I think that thread is more about alternatives to pie charts and why pie charts are bad. I would like to stick to pie charts and want to find a solution to handling labels correctly/user-friendly.

答:
For pie charts plotly works a lot easier than ggplot. Perhaps something like this:

```<code>library(plotly)

p <- plot_ly(alloc, labels = ~ltr, values = ~wght, type = 'pie',textposition = 'outside',textinfo = 'label+percent') %>%
  layout(title = 'Letters',
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
</code>```

Title: ggplot pie chart labeling

Body:
I am struggling with getting the pie chart labels correct. Looked around and thought that I could easily implement what mathematicalCoffee did. So far I have this code:

ltr = LETTERS[seq( from = 1, to = 26)]

wght = runif(length(ltr))
wght = wght/sum(wght)
wght = round(wght, digits = 2)

alloc = as.data.frame(cbind(ltr, wght))
alloc$wght = as.numeric(as.character(alloc$wght))

ggpie <- function (dat, by, totals) {
  ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) +
    geom_bar(stat='identity', color='black') +
    guides(fill=guide_legend(override.aes=list(colour=NA))) +
    coord_polar(theta='y') +
    theme(axis.ticks=element_blank(),
          axis.text.y=element_blank(),
          axis.text.x=element_text(colour='black'),
          axis.title=element_blank()) +
    ## scale_fill_brewer(palette = "GnBu") +
    scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=paste(dat[[by]], ":", dat[[totals]]))
}

AA = ggpie(alloc, by = "ltr", totals = "wght") +
  ggtitle("Letter weights")

AA

The resulting pie chart:

Is there any way to generate something like this, for example:

Update for suggested dup - I think that thread is more about alternatives to pie charts and why pie charts are bad. I would like to stick to pie charts and want to find a solution to handling labels correctly/user-friendly.

Body:
For pie charts plotly works a lot easier than ggplot. Perhaps something like this:

library(plotly)

p <- plot_ly(alloc, labels = ~ltr, values = ~wght, type = 'pie',textposition = 'outside',textinfo = 'label+percent') %>%
  layout(title = 'Letters',
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))


问:
how to send email automatically using jsp/servlet at partcular time(10'clock in the morning) daily
I want to send email automatically using j2ee at specific time daily if tomcat server is in on mode by fetching data from database </p>

答:
You can try with cron job

Main.java

```<code>public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     YourTask yourTask= new YourTask();
enter code here
     // This task is scheduled to run every 5 seconds

     t.scheduleAtFixedRate(yourTask, 0, 5000);
   }

}
</code>```

YourTask

```<code>class YourTask extends TimerTask{

   public YourTask (){
     //Some stuffs
   }

   @Override
   public void run() {
//TODO
Your business logic
   }

}
</code>```

As shown in above code ,you can call your business logic of specific time duration.

Here i had made call to that specific business logic on interval of 5 seconds.

For Timer  timer and TimerTask timertask

Body:
You can try with cron job

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     YourTask yourTask= new YourTask();
enter code here
     // This task is scheduled to run every 5 seconds

     t.scheduleAtFixedRate(yourTask, 0, 5000);
   }

}

YourTask

class YourTask extends TimerTask{

   public YourTask (){
     //Some stuffs
   }

   @Override
   public void run() {
//TODO
Your business logic
   }

}

As shown in above code ,you can call your business logic of specific time duration.

Here i had made call to that specific business logic on interval of 5 seconds.

For Timer  timer and TimerTask timertask


问:
Spring Eureka Client does not see server port from configuration file
I have an application based on spring-boot which is deployed to jar. It has a form of  maven multi-module project and contains following parts:

web

service

repository

model

My web module needs all others to build itself and contains in its resource directory following file:

bootstrap.yml

The bootstrap.yml contains following configuration:

```<code>eureka:
  client:
    eureka-server-port: 8761
server:
  port: 8763
  context-path: /foo-service/rest
spring:
  application:
    name: foo-service
</code>```

So I am expecting that during wake up it will use port 8761 and register itself to Eureka service. Because of some reason when I debug at:

```<code>org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration#eurekaInstanceConfigBean
</code>```

the instance of EurekaInstanceConfigBean contains following values:

instanceId = 172.20.39.197:foo-service:8763

nonSecurePort = 8080

What is weird is nonSecurePort set on 8080 instead of 8763. In my other services (which works correctly) the nonSecurePort has the same value as last part of instanceId. Only in foo-service the value is different.

The reason of that is:

```<code>@Value("${server.port:${SERVER_PORT:${PORT:8080}}}")
int nonSecurePort;
</code>```

can't find the configuration and returns the default value. But why?
I have checked the foo.jar created by maven and the bootstrap.yml is there in correct place (BOOT-INF/classes/bootstrap.yml) with correct values...

Do anyone have any idea what may be wrong?

答:
I have the same problem.

Several boot applications built exactly the same way. Applications using @ImportResource register with an incorrect default port of 8080 with Eureka.

I could not move away from @ImportResource yet.

Adding the following to bootstrap.yml worked.

```<code>eureka:
  instance:
    non-secure-port: 8088
</code>```

Body:
I have an application based on spring-boot which is deployed to jar. It has a form of  maven multi-module project and contains following parts:

web

service

repository

model

My web module needs all others to build itself and contains in its resource directory following file:

bootstrap.yml

The bootstrap.yml contains following configuration:

eureka:
  client:
    eureka-server-port: 8761
server:
  port: 8763
  context-path: /foo-service/rest
spring:
  application:
    name: foo-service

So I am expecting that during wake up it will use port 8761 and register itself to Eureka service. Because of some reason when I debug at:

org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration#eurekaInstanceConfigBean

the instance of EurekaInstanceConfigBean contains following values:

instanceId = 172.20.39.197:foo-service:8763

nonSecurePort = 8080

What is weird is nonSecurePort set on 8080 instead of 8763. In my other services (which works correctly) the nonSecurePort has the same value as last part of instanceId. Only in foo-service the value is different.

The reason of that is:

@Value("${server.port:${SERVER_PORT:${PORT:8080}}}")
int nonSecurePort;

can't find the configuration and returns the default value. But why?
I have checked the foo.jar created by maven and the bootstrap.yml is there in correct place (BOOT-INF/classes/bootstrap.yml) with correct values...

Do anyone have any idea what may be wrong?

Body:
I have the same problem.

Several boot applications built exactly the same way. Applications using @ImportResource register with an incorrect default port of 8080 with Eureka.

I could not move away from @ImportResource yet.

Adding the following to bootstrap.yml worked.

eureka:
  instance:
    non-secure-port: 8088


问:
How can I use base::scale() on variables together with dplyr::filter()
I want to have one of the columns in a data frame scaled. But when I do so, I cannot used dplyr::filter() anymore, which is rather inconvenient. Is there an elegant way to solve this?

MWE:

```<code>df <- mtcars
df$cyl <- scale(df$cyl)
dplyr::filter(df, mpg >1)
</code>```

Error: Each variable must be a 1d atomic vector or list.
  Problem variables: 'cyl'

答:
scale() outputs a matrix (See help("scale"), Section Value).

You get:

```<code>str(df)
# 'data.frame': 32 obs. of  11 variables:
#  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
#  $ cyl : num [1:32, 1] -0.105 -0.105 -1.225 -0.105 1.015 ...
#   ..- attr(*, "scaled:center")= num 6.19
#   ..- attr(*, "scaled:scale")= num 1.79
#  $ disp: num  160 160 108 258 360 ...
# ...
</code>```

For probably good reason, dplyr::filter makes some sanity checks on the data frame passed to it, one is checking that all columns are 1d atomic vectors or lists, by far the most common cases of things one puts in columns.
For reference, see for instance this issue on github.

c() has the convenient "side effect" of implicitly converting to vectors. For more explicit and self-describing code, maybe prefer as.vector().

So df$cyl <- c(scale(df$cyl)) instead of df$cyl <- scale(df$cyl) solves it.

```<code>str(df)
# 'data.frame': 32 obs. of  11 variables:
#  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
#  $ cyl : num  -0.105 -0.105 -1.225 -0.105 1.015 ...
#  $ disp: num  160 160 108 258 360 ...
# ...
</code>```

Body:
I want to have one of the columns in a data frame scaled. But when I do so, I cannot used dplyr::filter() anymore, which is rather inconvenient. Is there an elegant way to solve this?

MWE:

df <- mtcars
df$cyl <- scale(df$cyl)
dplyr::filter(df, mpg >1)

Error: Each variable must be a 1d atomic vector or list.
  Problem variables: 'cyl'

Body:
scale() outputs a matrix (See help("scale"), Section Value).

You get:

str(df)
# 'data.frame': 32 obs. of  11 variables:
#  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
#  $ cyl : num [1:32, 1] -0.105 -0.105 -1.225 -0.105 1.015 ...
#   ..- attr(*, "scaled:center")= num 6.19
#   ..- attr(*, "scaled:scale")= num 1.79
#  $ disp: num  160 160 108 258 360 ...
# ...

For probably good reason, dplyr::filter makes some sanity checks on the data frame passed to it, one is checking that all columns are 1d atomic vectors or lists, by far the most common cases of things one puts in columns.
For reference, see for instance this issue on github.

c() has the convenient "side effect" of implicitly converting to vectors. For more explicit and self-describing code, maybe prefer as.vector().

So df$cyl <- c(scale(df$cyl)) instead of df$cyl <- scale(df$cyl) solves it.

str(df)
# 'data.frame': 32 obs. of  11 variables:
#  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
#  $ cyl : num  -0.105 -0.105 -1.225 -0.105 1.015 ...
#  $ disp: num  160 160 108 258 360 ...
# ...