问:
Selenium Webdrive find visible element
So i have this form for anti-spam. Because of that it creates for each input about 9 or so inputs. This inputs have and id of 'NameInput' + X where x is a number generated (from 1 to 9 -- depending on the number of inputs). I'm using php and I want to select the one input that is visible. I would use the id but each time the page is loaded, because of the random number each time the input's id visible is different.
I've googled it and try to find a code that selects the id (first part of it that is the same for all inputs) and the display style. Tried a lot of code snippets but no success. This is where I am now but i got this error.

An invalid or illegal selector

```<code>$this->_webDriver->findElement(WebDriverBy::cssSelector('[id^=NameInput]:not[style=display:none]'))
</code>```

Any help would be great!

答:
So this is what I ended up with:

```<code>$nameInputs = $this->_webDriver->findElements(WebDriverBy::cssSelector('input[id^="NameInput"]'));
    foreach ($nameInputs as $name) {
        if($name->getCSSValue('display') === 'block') {
            $name->sendKeys('Jellos');
</code>```

It might help someone!

Title: Selenium Webdrive find visible element

Body:
So i have this form for anti-spam. Because of that it creates for each input about 9 or so inputs. This inputs have and id of 'NameInput' + X where x is a number generated (from 1 to 9 -- depending on the number of inputs). I'm using php and I want to select the one input that is visible. I would use the id but each time the page is loaded, because of the random number each time the input's id visible is different.
I've googled it and try to find a code that selects the id (first part of it that is the same for all inputs) and the display style. Tried a lot of code snippets but no success. This is where I am now but i got this error.

An invalid or illegal selector

$this->_webDriver->findElement(WebDriverBy::cssSelector('[id^=NameInput]:not[style=display:none]'))

Any help would be great!

Body:
So this is what I ended up with:

$nameInputs = $this->_webDriver->findElements(WebDriverBy::cssSelector('input[id^="NameInput"]'));
    foreach ($nameInputs as $name) {
        if($name->getCSSValue('display') === 'block') {
            $name->sendKeys('Jellos');

It might help someone!


来源: stackexchange

问:
C Switch default case not triggering
I'm stuck at a pretty awkward thing. Here's the code:

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

void processCommand(){
    char *c = malloc(sizeof(char) * 128);

    scanf("%s", c);

    switch(*c){
    case '!':
        printf("Action");
        break;
    case '?':
        printf("Question");
        break;
    default:
        printf("Unknown Action");
        break;
    }
}
</code>```

So what I want is, if the first char of my input is something different than ! or ?, it should just say it's an unknown action. So it works for typing other characters, but everytime i type a whitespace / tab / nothing, it doesn't do anything ?

答:
As other users pointed out: scanf ignores whitespaces, fgets doesn't.</p>

```<code>void processCommand(){
    char *c = malloc(sizeof(char) * 128);
    fgets (c, sizeof(char) * 128, stdin);

    switch(*c){
        case '!':
            printf("Action");
            break;
        case '?':
            printf("Question");
            break;
        default:
            printf("Unknown Action");
            break;
        }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C Switch default case not triggering

Body:
I'm stuck at a pretty awkward thing. Here's the code:

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

void processCommand(){
    char *c = malloc(sizeof(char) * 128);

    scanf("%s", c);

    switch(*c){
    case '!':
        printf("Action");
        break;
    case '?':
        printf("Question");
        break;
    default:
        printf("Unknown Action");
        break;
    }
}

So what I want is, if the first char of my input is something different than ! or ?, it should just say it's an unknown action. So it works for typing other characters, but everytime i type a whitespace / tab / nothing, it doesn't do anything ?

Body:
As other users pointed out: scanf ignores whitespaces, fgets doesn't.

void processCommand(){
    char *c = malloc(sizeof(char) * 128);
    fgets (c, sizeof(char) * 128, stdin);

    switch(*c){
        case '!':
            printf("Action");
            break;
        case '?':
            printf("Question");
            break;
        default:
            printf("Unknown Action");
            break;
        }
}


问:
Sending data by websockets from parallel thread
Today i have been trying to create an asynchronous task between Javascript and Django.

To create websockets and manage them, I used third party API pusher (Please make sure that question is not specific for the pusher). This system worked well at first when it was used in the main thread:

```<code>import pusher
import time
from django.shortcuts import render

...
def myView(request):
    ...
    def sendData():
        time.sleep(10)
        pusher_client = pusher.Pusher(
          args='values',
        )
        pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'})
    ...
    return render('My.html', {'keys': 'values'})
</code>```

And this is the listener in the Javascript:

```<code>var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
  alert(data.message);
});
</code>```

Then i wanted to create a parallel thread, So the user wouldn't wait 10 seconds to receive parallel thread. Instead, The template would be displayed and user would get alerted in 10 seconds after the request.

So i added following code which would seperate two processes:

```<code>import pusher
import time
from django.shortcuts import render
from threading import Thread

...
def myView(request):
    ...
    def sendData():
        time.sleep(10)
        pusher_client = pusher.Pusher(
          keys='values',
        )
        pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'})

    th = Thread(target=sendData)
    th.daemon = True
    th.start()
    ...
    return render('My.html', {'keys': 'values'})
</code>```

After creating another thread for the function, The function itself would be executed, However, Data could not be transmitted from Javascript...

These is my event log when i did the action:

As you see, The last event is always occupied even after 10 seconds have passed.

What could be the problem? Is problem caused by using websockets on different threads? Is there any other solution to do this?

It seems like Thread is not working, Because, whenever i send the message from another computer node, Message is delivered in few seconds.

Thanks in advance.

答:
This was caused by the hosting service's prohibition on multithreading. The new thread was never started, and so the event was never sent to Pusher.

(I'm quoting @ShellRox in extended comment chat.)

Body:
Today i have been trying to create an asynchronous task between Javascript and Django.

To create websockets and manage them, I used third party API pusher (Please make sure that question is not specific for the pusher). This system worked well at first when it was used in the main thread:

import pusher
import time
from django.shortcuts import render

...
def myView(request):
    ...
    def sendData():
        time.sleep(10)
        pusher_client = pusher.Pusher(
          args='values',
        )
        pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'})
    ...
    return render('My.html', {'keys': 'values'})

And this is the listener in the Javascript:

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
  alert(data.message);
});

Then i wanted to create a parallel thread, So the user wouldn't wait 10 seconds to receive parallel thread. Instead, The template would be displayed and user would get alerted in 10 seconds after the request.

So i added following code which would seperate two processes:

import pusher
import time
from django.shortcuts import render
from threading import Thread

...
def myView(request):
    ...
    def sendData():
        time.sleep(10)
        pusher_client = pusher.Pusher(
          keys='values',
        )
        pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'})

    th = Thread(target=sendData)
    th.daemon = True
    th.start()
    ...
    return render('My.html', {'keys': 'values'})

After creating another thread for the function, The function itself would be executed, However, Data could not be transmitted from Javascript...

These is my event log when i did the action:

As you see, The last event is always occupied even after 10 seconds have passed.

What could be the problem? Is problem caused by using websockets on different threads? Is there any other solution to do this?

It seems like Thread is not working, Because, whenever i send the message from another computer node, Message is delivered in few seconds.

Thanks in advance.


问:
Toggle arrows at the end of the first line of text
How to add arrows at the end of the first line text? And I want it point down when collapse and point up when expand. Like shown as images below. Appreciate your help, thanks!

$(".expander").click(function() {
    if ($(this).hasClass("expander")) {
        $(this).removeClass("expander");
    }
    else {
         $(this).addClass("expander");
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expander {
    height: 1em;
    overflow: hidden;
    cursor: pointer;
}</code>```

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

```

Code taken from here

答:
You can use pseudo element to create the arrow and change it according to the class expander

See code snippet:

$(".expander").click(function() {
  if ($(this).hasClass("expander")) {
    $(this).removeClass("expander");
  } else {
    $(this).addClass("expander");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 0 10px;
}

.expander {
  height: 1em;
  overflow: hidden;
  cursor: pointer;
}

div::after {
  content: '';
  width: 0;
  height: 0;
  border: 8px solid;
  border-color: #000 transparent transparent transparent;
  position: absolute;
  right: 0px;
  top: 15px;
}

.expander::after {
  top: 10px;
  border-color: transparent transparent transparent #000;
}</code>```

  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
  one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
  et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
  1.10.32.

```

Body:
How to add arrows at the end of the first line text? And I want it point down when collapse and point up when expand. Like shown as images below. Appreciate your help, thanks!

$(".expander").click(function() {
    if ($(this).hasClass("expander")) {
        $(this).removeClass("expander");
    }
    else {
         $(this).addClass("expander");
    }
});

.expander {
    height: 1em;
    overflow: hidden;
    cursor: pointer;
}

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

Code taken from here

Body:
You can use pseudo element to create the arrow and change it according to the class expander

See code snippet:

$(".expander").click(function() {
  if ($(this).hasClass("expander")) {
    $(this).removeClass("expander");
  } else {
    $(this).addClass("expander");
  }
});

div {
  padding: 0 10px;
}

.expander {
  height: 1em;
  overflow: hidden;
  cursor: pointer;
}

div::after {
  content: '';
  width: 0;
  height: 0;
  border: 8px solid;
  border-color: #000 transparent transparent transparent;
  position: absolute;
  right: 0px;
  top: 15px;
}

.expander::after {
  top: 10px;
  border-color: transparent transparent transparent #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="expander">
  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
  one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
  et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
  1.10.32.
</div>


问:
Jenkins Frequent Disconnects - ClosedChannelException
For the last month or so, two of our windows slaves (connected via JNLP) have started to frequently disconnect. I am pretty sure that something changed in terms of our network, since this only affects one geographical location (and all the slaves in that location) and there was a distinct time when we started receiving the node offline emails, but so far our infrastructure team has drawn a blank.

The error I am seeing in the slave logs is:

```<code>JNLP agent connected from xx
Slave.jar version: 3.4.1
This is a Windows agent
Agent successfully connected and online
ERROR: Connection terminated
[8mha:////4EVWKVufSpoBsjG/AK97kvCQst6o1LLM9fjogkB0XVcIAAAAWB+LCAAAAAAAAP9b85aBtbiIQSmjNKU4P08vOT+vOD8nVc8DzHWtSE4tKMnMz/PLL0ldFVf2c+b/lb5MDAwVRQxSaBqcITRIIQMEMIIUFgAAckCEiWAAAAA=[0mjava.nio.channels.ClosedChannelException
    at org.jenkinsci.remoting.protocol.NetworkLayer.onRecvClosed(NetworkLayer.java:154)
    at org.jenkinsci.remoting.protocol.impl.NIONetworkLayer.ready(NIONetworkLayer.java:179)
    at org.jenkinsci.remoting.protocol.IOHub$OnReady.run(IOHub.java:721)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
</code>```

I have spent hours trying to figure out what is wrong. I am not sure what logger I can configure to try and diagnose this further, so if anyone can help me there it would be appreciated? Or indeed any other way of diagnosing what has gone awry.

We are running the latest LTS release 2.46.1 (but it was exhibiting this problem on an older LTS release, and I upgraded to see if the recent remoting changes helped, which unfortunately they didn't.)

I suspect the problem may be on the master side, since I can connect to another master from the same slave machine and don't see the disconnects.

Any help would be appreciated since I am all out of ideas.

thanks, Stu

答:
I had similar issue with AWS ECS slave agents, for some of failing builds advise in this article helped.
Try to add -Dhudson.remoting.Launcher.pingIntervalSec=-1 to slave JVM options and execute following in the master console

Jenkins.instance.injector.getInstance(hudson.slaves.ChannelPinger.class).@pingIntervalSeconds = -1
Jenkins.instance.injector.getInstance(hudson.slaves.ChannelPinger.class).@pingTimeoutSeconds = -1

Body:
For the last month or so, two of our windows slaves (connected via JNLP) have started to frequently disconnect. I am pretty sure that something changed in terms of our network, since this only affects one geographical location (and all the slaves in that location) and there was a distinct time when we started receiving the node offline emails, but so far our infrastructure team has drawn a blank.

The error I am seeing in the slave logs is:

JNLP agent connected from xx
Slave.jar version: 3.4.1
This is a Windows agent
Agent successfully connected and online
ERROR: Connection terminated
[8mha:////4EVWKVufSpoBsjG/AK97kvCQst6o1LLM9fjogkB0XVcIAAAAWB+LCAAAAAAAAP9b85aBtbiIQSmjNKU4P08vOT+vOD8nVc8DzHWtSE4tKMnMz/PLL0ldFVf2c+b/lb5MDAwVRQxSaBqcITRIIQMEMIIUFgAAckCEiWAAAAA=[0mjava.nio.channels.ClosedChannelException
    at org.jenkinsci.remoting.protocol.NetworkLayer.onRecvClosed(NetworkLayer.java:154)
    at org.jenkinsci.remoting.protocol.impl.NIONetworkLayer.ready(NIONetworkLayer.java:179)
    at org.jenkinsci.remoting.protocol.IOHub$OnReady.run(IOHub.java:721)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

I have spent hours trying to figure out what is wrong. I am not sure what logger I can configure to try and diagnose this further, so if anyone can help me there it would be appreciated? Or indeed any other way of diagnosing what has gone awry.

We are running the latest LTS release 2.46.1 (but it was exhibiting this problem on an older LTS release, and I upgraded to see if the recent remoting changes helped, which unfortunately they didn't.)

I suspect the problem may be on the master side, since I can connect to another master from the same slave machine and don't see the disconnects.

Any help would be appreciated since I am all out of ideas.

thanks, Stu


问:
android slide menu ..when am item is clicked in slide menu the control is not going to respective page
code for slide menu:</p>

```<code>   mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

       mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        /*getActionBar().setDisplayHomeAsUpEnabled(false);
        getActionBar().setHomeButtonEnabled(true);*/

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {

                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {

                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    selectItem(position);

}
//}

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);

       System.out.println("&&&&&position"+position);

        switch(position){
            case 0:
                startActivity(new Intent(home.this, ChangeActivity.class));
              //  finish();

            case 1:

                startActivity(new Intent(home.this, home.class));
                //finish();

            case 2:

                startActivity(new Intent(home.this, info_values.class));
               // finish();

            default:
                break;

        }
    }
</code>```

答:
You have to write break; statement after each case block. Like following

```<code>  switch(position){
        case 0:
            startActivity(new Intent(home.this, ChangeActivity.class));
          //  finish();
            break;

        case 1:
            startActivity(new Intent(home.this, home.class));
            //finish();
            break;

        case 2:
            startActivity(new Intent(home.this, info_values.class));
           // finish();
            break;

        default:
            break;

    }
</code>```

Body:
code for slide menu:

   mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

       mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        /*getActionBar().setDisplayHomeAsUpEnabled(false);
        getActionBar().setHomeButtonEnabled(true);*/

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {

                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {

                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    selectItem(position);

}
//}

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);

       System.out.println("&&&&&position"+position);

        switch(position){
            case 0:
                startActivity(new Intent(home.this, ChangeActivity.class));
              //  finish();

            case 1:

                startActivity(new Intent(home.this, home.class));
                //finish();

            case 2:

                startActivity(new Intent(home.this, info_values.class));
               // finish();

            default:
                break;

        }
    }

Body:
You have to write break; statement after each case block. Like following

  switch(position){
        case 0:
            startActivity(new Intent(home.this, ChangeActivity.class));
          //  finish();
            break;

        case 1:
            startActivity(new Intent(home.this, home.class));
            //finish();
            break;

        case 2:
            startActivity(new Intent(home.this, info_values.class));
           // finish();
            break;

        default:
            break;

    }


问:
Leaflet How to set center map when click marker
I follow this example http://jsfiddle.net/abenrob/ZkC5M/ , When i click marker I want map pan to marker and set position center screen my code is below but when i click map.setView(new L.LatLng(position), 5);
is not working.

```<code> function markerFunction(id){
        for (var i in markers){
            var markerID = markers[i].options.title;
            var position = markers[i].getLatLng();

            if (markerID == id){
                map.setView(new L.LatLng(position), 5);
                markers[i].openPopup();
            };
        }
    }
</code>```

Thank you,

答:
panTo() should work too:

```<code>marker.addEventListener("click", function (e){
  map.panTo(this.getLatLng());
});
</code>```

for your example, it looks like this:

```<code>for(i = 0; i < markers.length; i++){
    markers[i].addEventListener("click", function(e){
        map.panTo(this.getLatLng());
    });
}
</code>```

Body:
I follow this example http://jsfiddle.net/abenrob/ZkC5M/ , When i click marker I want map pan to marker and set position center screen my code is below but when i click map.setView(new L.LatLng(position), 5);
is not working.

 function markerFunction(id){
        for (var i in markers){
            var markerID = markers[i].options.title;
            var position = markers[i].getLatLng();

            if (markerID == id){
                map.setView(new L.LatLng(position), 5);
                markers[i].openPopup();
            };
        }
    }

Thank you,

Body:
panTo() should work too:

marker.addEventListener("click", function (e){
  map.panTo(this.getLatLng());
});

for your example, it looks like this:

for(i = 0; i < markers.length; i++){
    markers[i].addEventListener("click", function(e){
        map.panTo(this.getLatLng());
    });
}

ContentLicense: CC BY-SA 4.0


问:
Split Values and Units using Jquery, Javascript
I have the values be like 10 #/mm3, and i want to split those as 10 and #/mm3 by value and unit respectively using jquery or Javascript, i tried to split it in java but i need it in client side.</p>

```<code>10|mm
</code>```

答:
So what you need is a way to split by the X character, but retain that character when split. You can achieve this by replacing the X with ,X and then splitting by the ,.

var string = "7.24X10^6";
string = string.replace("X", ",X");
string = string.split(",");
console.log(string);```

Body:
I have the values be like 10 #/mm3, and i want to split those as 10 and #/mm3 by value and unit respectively using jquery or Javascript, i tried to split it in java but i need it in client side.

10|mm


问:
iOS: How to get a proper Month name from a number?
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

```<code>int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];
</code>```

is this the way to do it? It seems a bit wordy.

答:
You can change the dateFormat of the NSDateFormatter. So to simplify your code:

```<code>int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];

[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[dateFormatter release];
</code>```

You should also set the locale once you init the date formatter.

```<code>dateFormatter.locale = [NSLocale currentLocale]; // Or any other locale
</code>```

Hope this helps

Body:
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

is this the way to do it? It seems a bit wordy.

Body:
You can change the dateFormat of the NSDateFormatter. So to simplify your code:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];

[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[dateFormatter release];

You should also set the locale once you init the date formatter.

dateFormatter.locale = [NSLocale currentLocale]; // Or any other locale

Hope this helps

ContentLicense: CC BY-SA 2.5


答:
One approach:

$(".expander").click(function() {
  if ($(this).hasClass("expander")) {
    $(this).removeClass("expander");
    $(".panel").addClass("open");
  } else {
    $(this).addClass("expander");
    $(".panel").removeClass("open");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.panel {
  position: relative;
}

.expander {
  height: 1em;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  padding-right: 50px;
}

.panel:after {
  content: "V";
  position: absolute;
  top: 0;
  right: 0;
  font-family: sans-serif;
}

.panel.open:after {
  transform: rotate(180deg);
}</code>```

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
    one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
    et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
    1.10.32.

```

Title: Toggle arrows at the end of the first line of text

Body:
One approach:

$(".expander").click(function() {
  if ($(this).hasClass("expander")) {
    $(this).removeClass("expander");
    $(".panel").addClass("open");
  } else {
    $(this).addClass("expander");
    $(".panel").removeClass("open");
  }
});

.panel {
  position: relative;
}

.expander {
  height: 1em;
  overflow: hidden;
  cursor: pointer;
  position: relative;
  padding-right: 50px;
}

.panel:after {
  content: "V";
  position: absolute;
  top: 0;
  right: 0;
  font-family: sans-serif;
}

.panel.open:after {
  transform: rotate(180deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
  <div class="expander">
    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
    one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
    et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
    1.10.32.
  </div>
</div>


问:
Firebase UI 2.0.1 is not working when initializing or calling FirebaseAuth.getInstance() in Android
I am trying to solve the error below, since I updated to Firebase ui 2.0.1. I have set up the project really well since I have worked with previous versions Firebase for a long time.

The error appears when FirebaseAuth.getInstance() is called.

```<code>Error:(29, 22) error: cannot access zu class file for com.google.android.gms.internal.zu not found
</code>```

答: Firebase UI 2.0.1 is using Play services version 11.0.1. Make sure you don't use other versions (like in my case 11.0.2)</p>

Body:
I am trying to solve the error below, since I updated to Firebase ui 2.0.1. I have set up the project really well since I have worked with previous versions Firebase for a long time.

The error appears when FirebaseAuth.getInstance() is called.

Error:(29, 22) error: cannot access zu class file for com.google.android.gms.internal.zu not found


问:
What would be the Big O notation for this algorithm
Determine whether the string contains at least 1 repeatable character.

(Implying that string can contain only basic ASCII alphabet: 128 characters).

```<code>bool hasRepeatableChar(String str) {
    if (str.length() > 128) {
            return true;
    }
    str = str.sort();
    for (int i = 0; i < str.length()-1; i++) {
        if (str[i] == str[i+1]) {
            return true;
        }
    }
    return false;
}
</code>```

As I can see, it is:

O(n log n) for str.length() <= 128, where n - length of a string

O(1) for str.length() > 128

But what will be an amortized big O value?

P.S.

Instead of sorting it can also be done by using some kind of data structure (map, for example), it will reduce the amount of operations to O(n) but increase memory cost. Anyway, it isn't related to the question.

答: Strictly speaking, the time complexity of this algorithm is O(1), because the number of operations T(n) does not depend on the size of the input (for large enough n) and is bounded by some constant number of operations.

Body:
Determine whether the string contains at least 1 repeatable character.

(Implying that string can contain only basic ASCII alphabet: 128 characters).

bool hasRepeatableChar(String str) {
    if (str.length() > 128) {
            return true;
    }
    str = str.sort();
    for (int i = 0; i < str.length()-1; i++) {
        if (str[i] == str[i+1]) {
            return true;
        }
    }
    return false;
}

As I can see, it is:

O(n log n) for str.length() <= 128, where n - length of a string

O(1) for str.length() > 128

But what will be an amortized big O value?

P.S.

Instead of sorting it can also be done by using some kind of data structure (map, for example), it will reduce the amount of operations to O(n) but increase memory cost. Anyway, it isn't related to the question.


问:
How can we use validation laravel in jquery
How can i use validation laravel with jquery

i try this with laravel validation

```<code>$this->validate($request, [
            'branch' => 'required|not_in:---Select Branch---',
            'dep' => 'required|not_in:--- Select Department ---',
            'txt_phone' => 'required|numeric|min:8',
            'txt_ext' => 'required|min:3|max:5' ], [
            'txt_phone.min' => 'Phone at least 9 characters',
            'txt_phone.max' => 'Phone not be greater than 10 characters',
            'txt_phone.numeric' => 'Phone must be nummeric']);
</code>```

But it's validate in the server i want to validate it on client with jquery how can i??

答:
you can return

```<code>if ($validator->fails()) {
    return $validator->errors();
}
</code>```

for your return ajax

Body:
How can i use validation laravel with jquery

i try this with laravel validation

$this->validate($request, [
            'branch' => 'required|not_in:---Select Branch---',
            'dep' => 'required|not_in:--- Select Department ---',
            'txt_phone' => 'required|numeric|min:8',
            'txt_ext' => 'required|min:3|max:5' ], [
            'txt_phone.min' => 'Phone at least 9 characters',
            'txt_phone.max' => 'Phone not be greater than 10 characters',
            'txt_phone.numeric' => 'Phone must be nummeric']);

But it's validate in the server i want to validate it on client with jquery how can i??

Body:
you can return

if ($validator->fails()) {
    return $validator->errors();
}

for your return ajax


问:
Thread wait on file input pattern
What's the normal pattern for a thread to wait for file input in C# when it reaches end of file and
 needs to wait. Any particularly way of coding it, which is neat and elegant.

Thanks.
 Bob.

答:
I will be interested in seeing what the other answers are. I have not found an elegant solution. Here is what I have done in the past.

Have the reader try to open the file exclusively. This will fail if the file is open elsewhere.

Have a retry loop....sleep X milliseconds...retry Y times. Usually, I pull X & Y out into a configuration file.

Hope this helps.

Bob

Title: Thread wait on file input pattern


问:
opencv 3.2.0 java Face Recognition Ubuntu
i am using opencv 3.2.0 and im trying to get the face recognition up and running.

I am faced with the problem that the Face class in org.opencv.face.Face being empty. This is all contained in the file :

```<code> //
 // This file is auto-generated. Please don't modify it!
 //
 package org.opencv.face;
 public class Face {
 }
</code>```

From what i have read i need to add 'java' to the CMakeLists.txt of Face contrib module in order to add it to the final jar such as

```<code>ocv_define_module(face opencv_core opencv_imgproc opencv_objdetect WRAP python java)
</code>```

In order to tell the compiler to include the contrib modules i have to add

```<code> -D
 OPENCV_EXTRA_MODULES_PATH=$YOUR_OPENCV_CONTRIB_PATH/opencv_contrib-
 3.2.0/modules
</code>```

to the cmake command , and later make it , in general my commands are as follows

```<code>1: cmake
2: make -j5
</code>```

I get no errors when compiling and building and i get my jar,
which i use without issues for face detection and so forth.
The problem is that the Face class is empty and i cannot create a FaceRecognizer.
i was following this guide here
https://github.com/andreaiacono/OpenCVDemo   -  as of 01.06.2017
and in the org.opencv.demo.core.RecognizerFactory class he uses

```<code>return Face.createFisherFaceRecognizer();
</code>```

which as it seems i can not use.

I tried to search if the 3.2.0 libraries have a different way of creating a recognizer but google is not very helpful as there are just a handful of answers to any java opencv related issues.

What could be causing the Face class to be empty and/or are there any other ways to create recognizers in case that 3.2.0 indeed works differently ?

Thank you for the time

答:
I have found an answer to my previous question and i am posting it for all to see , i hope i could help some other lost soul like myself.

I have tested with version 3.1.0 and it would appear that the Face class is NOT empty. Proving that Face detection in 3.2.0 may not be implemented properly (as of the time of writing).

I faced issues with compiling properly due to usage of some libraries :

```<code> /usr/include/c++/6.1.1/cstdlib:75:25: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
</code>```

An answer i found to this issue was found in https://github.com/opencv/opencv/issues/6517#issuecomment-219219767

namely to include this in the cmake :

```<code>cmake -DENABLE_PRECOMPILED_HEADERS=OFF
</code>```

This allowed me to compile everything properly and i managed to get my face recognition code up and running :)

Good luck to all

Body:
i am using opencv 3.2.0 and im trying to get the face recognition up and running.

I am faced with the problem that the Face class in org.opencv.face.Face being empty. This is all contained in the file :

 //
 // This file is auto-generated. Please don't modify it!
 //
 package org.opencv.face;
 public class Face {
 }

From what i have read i need to add 'java' to the CMakeLists.txt of Face contrib module in order to add it to the final jar such as

ocv_define_module(face opencv_core opencv_imgproc opencv_objdetect WRAP python java)

In order to tell the compiler to include the contrib modules i have to add

 -D
 OPENCV_EXTRA_MODULES_PATH=$YOUR_OPENCV_CONTRIB_PATH/opencv_contrib-
 3.2.0/modules

to the cmake command , and later make it , in general my commands are as follows

1: cmake
2: make -j5

I get no errors when compiling and building and i get my jar,
which i use without issues for face detection and so forth.
The problem is that the Face class is empty and i cannot create a FaceRecognizer.
i was following this guide here
https://github.com/andreaiacono/OpenCVDemo   -  as of 01.06.2017
and in the org.opencv.demo.core.RecognizerFactory class he uses

return Face.createFisherFaceRecognizer();

which as it seems i can not use.

I tried to search if the 3.2.0 libraries have a different way of creating a recognizer but google is not very helpful as there are just a handful of answers to any java opencv related issues.

What could be causing the Face class to be empty and/or are there any other ways to create recognizers in case that 3.2.0 indeed works differently ?

Thank you for the time

Body:
I have found an answer to my previous question and i am posting it for all to see , i hope i could help some other lost soul like myself.

I have tested with version 3.1.0 and it would appear that the Face class is NOT empty. Proving that Face detection in 3.2.0 may not be implemented properly (as of the time of writing).

I faced issues with compiling properly due to usage of some libraries :

 /usr/include/c++/6.1.1/cstdlib:75:25: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>

An answer i found to this issue was found in https://github.com/opencv/opencv/issues/6517#issuecomment-219219767

namely to include this in the cmake :

cmake -DENABLE_PRECOMPILED_HEADERS=OFF

This allowed me to compile everything properly and i managed to get my face recognition code up and running :)

Good luck to all


问:
Extracting tables, lines, and coordinates from PDF using PDFSharp/C#
I have several reports saved as PDF which contains several tables in between texts and images. I'm not sure if these tables are really tables or just lines. I tried to open these files using LibreOffice Writer and they were only lines but I'm still not sure if it is Writer's behavior on handling PDF's tables or just lines only.

How to make sure that these tables are really tables and how to extract them? If they were only lines, how to extract these lines and texts with their coordinates?

I'm using PDFSharp. Thanks for any help.

答:
I know that this is an old question but someone could need it

"Quite obvious" introduction:

PDF files are stream of graphics object (for example lines) and text. When the PDF is rendered the human eye understand that there are tables because of lines and text between them.

The (my) solution

Starting from a PDF reader (iTextSharp) you need to:

1. read the lines (hopefully only vertical and horizontal lines);

2. join the lines (a line of a table could be several lines, for example one per cell);

3. understand where the tables are (sometimes making some hypothesis based on your needs);

4. optionally find the text outside the tables (better to keep all the text) and insert it in paragraphs;

5. Insert text inside the cells of the table

If you need something already written to start from (working for my pdfs) you can find something here https://github.com/bubibubi/ExtractTablesFromPdf

It uses the GPL version of iTextSharp.

In this project there is the code to extract lines, boxes, tables and tables content.


问:
Binwalk not extracting files from binary
I am using binwalk, its finding files but nothing is extracted afterwards
I have done this before and have not had issues. Are these not files?</p>

```<code>babak@G750JHA ~/Desktop $ binwalk -Me ./Cottonelle.bin

Scan Time:     2016-06-18 23:19:58
Target File:   /home/ubuntu/babak/Desktop/Cottonelle.bin
MD5 Checksum:  f330370ed549c30bb301b42e7363ce32
Signatures:    345

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
16560         0x40B0          PEM RSA private key
18608         0x48B0          PEM certificate
20484         0x5004          PEM certificate
32944         0x80B0          PEM RSA private key
34992         0x88B0          PEM certificate
36868         0x9004          PEM certificate
301529        0x499D9         Certificate in DER format (x509 v3), header length: 4, sequence length: 177
414737        0x65411         Boot section Start 0x42423242 End 0x0
414741        0x65415         Boot section Start 0x0 End 0x0
414911        0x654BF         Boot section Start 0x3C42 End 0x0
414915        0x654C3         Boot section Start 0x0 End 0x0
415370        0x6568A         Boot section Start 0x14 End 0x30000
518776        0x7EA78         PEM RSA private key
520488        0x7F128         PEM certificate
521984        0x7F700         PEM certificate
531224        0x81B18         HTML document header
532867        0x82183         HTML document footer
532876        0x8218C         HTML document header
533428        0x823B4         HTML document footer
533440        0x823C0         JPEG image data, JFIF standard 1.01
549524        0x86294         SHA256 hash constants, little endian
550196        0x86534         PEM RSA private key
550592        0x866C0         PEM certificate
788672        0xC08C0         Copyright string: "Copyright (c) 1996-2011 Express Logic Inc. * NetX Cortex-M3/GNU Version G5.4.5.0 SN: 23451-108-0509 *"
</code>```

答: It seems that the binary file is encrypted. Do reverse engineering to find the encryption algorithm. Then only you can do the decryption. You need to decrypt the firmware before running it through binwalk.</p>

Body:
I am using binwalk, its finding files but nothing is extracted afterwards
I have done this before and have not had issues. Are these not files?

babak@G750JHA ~/Desktop $ binwalk -Me ./Cottonelle.bin

Scan Time:     2016-06-18 23:19:58
Target File:   /home/ubuntu/babak/Desktop/Cottonelle.bin
MD5 Checksum:  f330370ed549c30bb301b42e7363ce32
Signatures:    345

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
16560         0x40B0          PEM RSA private key
18608         0x48B0          PEM certificate
20484         0x5004          PEM certificate
32944         0x80B0          PEM RSA private key
34992         0x88B0          PEM certificate
36868         0x9004          PEM certificate
301529        0x499D9         Certificate in DER format (x509 v3), header length: 4, sequence length: 177
414737        0x65411         Boot section Start 0x42423242 End 0x0
414741        0x65415         Boot section Start 0x0 End 0x0
414911        0x654BF         Boot section Start 0x3C42 End 0x0
414915        0x654C3         Boot section Start 0x0 End 0x0
415370        0x6568A         Boot section Start 0x14 End 0x30000
518776        0x7EA78         PEM RSA private key
520488        0x7F128         PEM certificate
521984        0x7F700         PEM certificate
531224        0x81B18         HTML document header
532867        0x82183         HTML document footer
532876        0x8218C         HTML document header
533428        0x823B4         HTML document footer
533440        0x823C0         JPEG image data, JFIF standard 1.01
549524        0x86294         SHA256 hash constants, little endian
550196        0x86534         PEM RSA private key
550592        0x866C0         PEM certificate
788672        0xC08C0         Copyright string: "Copyright (c) 1996-2011 Express Logic Inc. * NetX Cortex-M3/GNU Version G5.4.5.0 SN: 23451-108-0509 *"


答:
```<code>   SELECT MAINTABLE.*
   FROM TABLEX MAINTABLE INNER JOIN
    (
         SELECT PRICE , DATE(X_DATE) AS DATE , ID AS ID
         FROM TABLEX
         GROUP BY WEEK(X_DATE)
    ) INNERTABLE ON MAINTABLE.ID = INNERTABLE.ID AND MAINTABLE.X_DATE = INNERTABLE.DATE
</code>```

Try above query.

Title: MYSQL - Huge issue getting current item usign Group BY

Body:
I'm having a lot of trouble with mysql queries and Group BY :

select MIN(price) AS price , date(x_date) AS date , id AS id
from tableX
group by week(x_date)

This returns :

[{"price":900.42,"date":"2017-01-05","id":2366},
{"price":789.4,"date":"2017-01-08","id":2369},
{"price":820.53,"date":"2017-01-15","id":2376},
{"price":889.88,"date":"2017-01-22","id":2383},
{"price":917.14,"date":"2017-01-29","id":2390},
{"price":991.02,"date":"2017-02-05","id":2397},
{"price":998.18,"date":"2017-02-12","id":2404},
{"price":1055.62,"date":"2017-02-19","id":2411}

The prices are being grouped correctly by the minimum price for that week , however the date & id it is returning is wrong . I'm getting the first date & id of that week instead of the date where the minimum price occurred .

Full json :

select price AS price , date(x_date) AS date , id AS id
from tableX

[{"price":1067.84,"date":"2017-01-05","id":2366},
{"price":950.74,"date":"2017-01-06","id":2367},
{"price":900.42,"date":"2017-01-07","id":2368},
{"price":909.35,"date":"2017-01-08","id":2369},
{"price":906.43,"date":"2017-01-09","id":2370},
{"price":902.07,"date":"2017-01-10","id":2371},
{"price":840.38,"date":"2017-01-11","id":2372},
{"price":789.4,"date":"2017-01-12","id":2373},
{"price":814.48,"date":"2017-01-13","id":2374},
{"price":822.38,"date":"2017-01-14","id":2375},
{"price":820.53,"date":"2017-01-15","id":2376},
{"price":826.34,"date":"2017-01-16","id":2377},
{"price":867.36,"date":"2017-01-17","id":2378},
{"price":894.35,"date":"2017-01-18","id":2379},
{"price":891.13,"date":"2017-01-19","id":2380},
{"price":894.82,"date":"2017-01-20","id":2381},
{"price":905.82,"date":"2017-01-21","id":2382},
{"price":922.67,"date":"2017-01-22","id":2383},
{"price":919.01,"date":"2017-01-23","id":2384},
{"price":899.17,"date":"2017-01-24","id":2385},
{"price":889.88,"date":"2017-01-25","id":2386},
{"price":904.61,"date":"2017-01-26","id":2387},
{"price":916.83,"date":"2017-01-27","id":2388},
{"price":919.42,"date":"2017-01-28","id":2389},
{"price":917.16,"date":"2017-01-29","id":2390},
{"price":917.14,"date":"2017-01-30","id":2391},
{"price":943.95,"date":"2017-01-31","id":2392},
{"price":977.51,"date":"2017-02-01","id":2393},
{"price":997.57,"date":"2017-02-02","id":2394},
{"price":1012.95,"date":"2017-02-03","id":2395},
{"price":1025.88,"date":"2017-02-04","id":2396},
{"price":1023.82,"date":"2017-02-05","id":2397},
{"price":1019.3,"date":"2017-02-06","id":2398},
{"price":1038.57,"date":"2017-02-07","id":2399},
{"price":1053.44,"date":"2017-02-08","id":2400},
{"price":1021.64,"date":"2017-02-09","id":2401},
{"price":991.02,"date":"2017-02-10","id":2402},
{"price":1001.54,"date":"2017-02-11","id":2403},
{"price":1004.75,"date":"2017-02-12","id":2404},
{"price":998.18,"date":"2017-02-13","id":2405},
{"price":1003.06,"date":"2017-02-14","id":2406},
{"price":1009.18,"date":"2017-02-15","id":2407},
{"price":1021.6,"date":"2017-02-16","id":2408},
{"price":1043.6,"date":"2017-02-17","id":2409},
{"price":1055.76,"date":"2017-02-18","id":2410},
{"price":1055.62,"date":"2017-02-19","id":2411},
{"price":1068.03,"date":"2017-02-20","id":2412},
{"price":1103.45,"date":"2017-02-21","id":2413},
{"price":1122.93,"date":"2017-02-22","id":2414},
{"price":1150.29,"date":"2017-02-23","id":2415},
{"price":1179.65,"date":"2017-02-24","id":2416},
{"price":1166.25,"date":"2017-02-25","id":2417},

Any pointers would be highly appreciated.

Body:
   SELECT MAINTABLE.*
   FROM TABLEX MAINTABLE INNER JOIN
    (
         SELECT PRICE , DATE(X_DATE) AS DATE , ID AS ID
         FROM TABLEX
         GROUP BY WEEK(X_DATE)
    ) INNERTABLE ON MAINTABLE.ID = INNERTABLE.ID AND MAINTABLE.X_DATE = INNERTABLE.DATE

Try above query.


问:
docker-ce 17.06.0-ce failed to pull from private registry mirror
After I upgrade docker-ce to latest 17.06.0-ce, I can not pull from my private registry...

before upgrade, I can docker pull tae/uc, which is my private image on my private registry, which is configured in /etc/docker/daemon.json

{   "registry-mirrors": ["https://admin:password@registry.local:5005"] }

after upgrade, I failed to pull without specifying the registry...

The only way I can pull is like docker pull registry.local:5005/tae/uc,
which is very annoying.

Any idea ?

答:
I would guess that your registry is only providing registry API v1 and Docker-ce 17.06 dropped support of it:

Deprecation

Disable legacy registry (v1) by default #33629

Upgrade your registry or try to re-enable legacy registry by adding "disable-legacy-registry": false in your daemon.json


问:
how to convert datetime to unix timestamp in c?
the scenario is: I get datetime in format "YYYY-MM-DD HH:MM:SS" with libexif. To minimize the saving cost, I wanna convert the datetime to unix timestamp or alike which only cost 64bit or 32bit. Is there any explicit way with c?</p>

答:
Here's a ready snippet when strptime is not available:

```<code>#include <stddef.h>
#include <time.h>
#include <stdio.h>

time_t string_to_seconds(const char *timestamp_str)
{
    struct tm tm;
    time_t seconds;
    int r;

    if (timestamp_str == NULL) {
        printf("null argument\n");
        return (time_t)-1;
    }
    r = sscanf(timestamp_str, "%d-%d-%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
    if (r != 6) {
        printf("expected %d numbers scanned in %s\n", r, timestamp_str);
        return (time_t)-1;
    }

    tm.tm_year -= 1900;
    tm.tm_mon -= 1;
    tm.tm_isdst = 0;
    seconds = mktime(&tm);
    if (seconds == (time_t)-1) {
        printf("reading time from %s failed\n", timestamp_str);
    }

    return seconds;
}
</code>```

Adjust youself a string in sscanf to what you need. To ignore time zone and convert always as GMT/UTC substract a timezone (or _timezone) from seconds (timezone global is defined in time.h. DST is already ignored by zeroing tm_isdst field of tm.

Body:
Here's a ready snippet when strptime is not available:

#include <stddef.h>
#include <time.h>
#include <stdio.h>

time_t string_to_seconds(const char *timestamp_str)
{
    struct tm tm;
    time_t seconds;
    int r;

    if (timestamp_str == NULL) {
        printf("null argument\n");
        return (time_t)-1;
    }
    r = sscanf(timestamp_str, "%d-%d-%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
    if (r != 6) {
        printf("expected %d numbers scanned in %s\n", r, timestamp_str);
        return (time_t)-1;
    }

    tm.tm_year -= 1900;
    tm.tm_mon -= 1;
    tm.tm_isdst = 0;
    seconds = mktime(&tm);
    if (seconds == (time_t)-1) {
        printf("reading time from %s failed\n", timestamp_str);
    }

    return seconds;
}

Adjust youself a string in sscanf to what you need. To ignore time zone and convert always as GMT/UTC substract a timezone (or _timezone) from seconds (timezone global is defined in time.h. DST is already ignored by zeroing tm_isdst field of tm.


问:
convert ANSI C's asctime() format using std::get_time
I want to convert string in ANSI C' format to std::tm object.

Example

Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

More info here here.

My code:

```<code>#include <string>
#include <ctime>
#include <iomanip>
#include <locale>
bool parseAscTimeDate(std::tm& tm, const std::string& str) {
    std::istringstream ss(str);
    //ss.imbue(std::locale("en_US.UTF8")); //try timezone?
    ss >> std::get_time(&tm, "%a %b  %d %H:%M:%S %Y");
    return !ss.fail();
}
</code>```

So why this fail?

```<code>   /* ANSI C's asctime format */
   std::tm tm;
   if (parseAscTimeDate(tm, "Sun Nov  6 08:49:37 1994"))
       std::cout << "Ok!" << std::endl;
   else
       std::cout << "Wrong!" << std::endl;
</code>```

additional info

I can't use strptime because there is a bug in musl libc.

I have tried to set some timezone but:

It need not set tzname, timezone, and daylight.

From here

std::get_time example that also fails?

答:
It looks like %d format requires two digits for the day of the month, contrary to description on std::get_time:

d: parses the day of the month as a decimal number (range [01,31]), leading zeroes permitted but not required.

It is a reported bug in GNU C++ standard library: set::get_time() requires leading 0s for %H and friends.

Body:
I want to convert string in ANSI C' format to std::tm object.

Example

Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

More info here here.

My code:

#include <string>
#include <ctime>
#include <iomanip>
#include <locale>
bool parseAscTimeDate(std::tm& tm, const std::string& str) {
    std::istringstream ss(str);
    //ss.imbue(std::locale("en_US.UTF8")); //try timezone?
    ss >> std::get_time(&tm, "%a %b  %d %H:%M:%S %Y");
    return !ss.fail();
}

So why this fail?

   /* ANSI C's asctime format */
   std::tm tm;
   if (parseAscTimeDate(tm, "Sun Nov  6 08:49:37 1994"))
       std::cout << "Ok!" << std::endl;
   else
       std::cout << "Wrong!" << std::endl;

additional info

I can't use strptime because there is a bug in musl libc.

I have tried to set some timezone but:

It need not set tzname, timezone, and daylight.

From here

std::get_time example that also fails?


问:
Android Project not resolve gradle
I am using android studio and i updated it from 2.3 to 2.3.3 and after when i am trying to open a existing project it is not gradlling. Here is my Application base build gradle file where i use dependencies like this...

```<code>dependencies {
     classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
}
</code>```

In my gradle-wrapper.properties i have mention like this...

```<code>#Mon Jul 03 12:12:51 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
</code>```

In My file>setting>gradle....

答:
You can specify the Gradle version in either the File > Project Structure > Project menu in Android Studio, or by editing the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file. The following example sets the Gradle version to 3.3 in the gradle-wrapper.properties file.

```<code>distributionUrl = https\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

More information on gradle plugin:

https://developer.android.com/studio/releases/gradle-plugin.html

Title: Android Project not resolve gradle

Body:
I am using android studio and i updated it from 2.3 to 2.3.3 and after when i am trying to open a existing project it is not gradlling. Here is my Application base build gradle file where i use dependencies like this...

dependencies {
     classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
}

In my gradle-wrapper.properties i have mention like this...

#Mon Jul 03 12:12:51 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

In My file>setting>gradle....

Body:
You can specify the Gradle version in either the File > Project Structure > Project menu in Android Studio, or by editing the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file. The following example sets the Gradle version to 3.3 in the gradle-wrapper.properties file.

distributionUrl = https\://services.gradle.org/distributions/gradle-3.3-all.zip

More information on gradle plugin:

https://developer.android.com/studio/releases/gradle-plugin.html


问:
linux: disable using loopback and send data via wire between 2 eth cards of one comp
I have a comp with 2 eth cards, connected with patch-cord (direct eth. cable from 1st to 2nd).

The linux is installed, I want to send data from 1st network card to 2nd. And I want to force the packet to pass via cable. I can set up any ip on cards.

With ping I get counters on cards constant.

Is it possible with tcp/ip sockets?

PS. I need to write a program. which will send packets via eth, so stackoverflow-related question. There can be some OS-dependent way, they will help me too

答:
Have a look in local routing table. With iproute2 tools installed do ip route show table local. As you can see, all packets destinated to your local IPs would never go thru NICs since they are marked as local.

To force packets go via ethernet card remove the appropriate route (i.e. ip route delete 192.168.122.1 dev eth0 table local). To restore this route just set the interface down and up: the kernel would do the work to insert these routes.


问:
Mule InstallException: Config for app not found
```<code>    <?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
    xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:apikit="http://www.mulesoft.org/schema/mule/apikit"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/apikit http://www.mulesoft.org/schema/mule/apikit/current/mule-apikit.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    <context:property-placeholder location="dev.properties" />
</code>```

And dev.properties is in /src/main/resources

Works in Studio but not in Mule stand alone

答:
After deployment in standalone, cross check in your server dev.properties file present in /opt/{mule.}/apps/{your apps}/classes/properties/dev.properties.

or If project maintained all the properties in config folder cross check in the following location /conf/dev.properties

make sure defined envt in either in mule-app.properties or passing in runtime.

Refer:
https://docs.mulesoft.com/mule-user-guide/v/3.6/deploying-to-multiple-environments

Body:
    <?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
    xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:apikit="http://www.mulesoft.org/schema/mule/apikit"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/apikit http://www.mulesoft.org/schema/mule/apikit/current/mule-apikit.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    <context:property-placeholder location="dev.properties" />

And dev.properties is in /src/main/resources

Works in Studio but not in Mule stand alone


问:
Ignore only certain CSS classes in Resharper
With Resharper 2016.3, the mechanism to identify unused CSS classes has been improved. This is great, but it comes with a downside:

We use CSS classes with a special prefix (js-) to mark elements that we need to find from javascript, e.g. from Selenium tests. These classes are now marked as "unknown", because there is no entry for them in the CSS file (obviously).

Is it possible to exclude CSS classes with a specific prefix from the "unknown CSS class" check in Resharper? If yes, how?

答:
Does not seem to be possible. We ended up using data attributes instead of classes to be able to find elements from Selenium tests. So instead of doing

```<code><div class="js-something"></div>
</code>```

we use now

```<code><div data-js-xref="something"></div>
</code>```

As a consequence, we use only class names that really exist, solving the Resharper problem in the process.

Body:
Does not seem to be possible. We ended up using data attributes instead of classes to be able to find elements from Selenium tests. So instead of doing

<div class="js-something"></div>

we use now

<div data-js-xref="something"></div>

As a consequence, we use only class names that really exist, solving the Resharper problem in the process.


问:
Android - Speech Recognizer is not stable
I try to use speech to text on android. I write a simple code and try on two devices(Huawei Android 6 api-level 23, Samsung Android 6 api-level 23).

My example is taken from this link

Permissions taken from user on runtime :

```<code><uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

There many different behaviour between two devices. Huawei device calls onError callback on silence after 5 seconds. But on samsung device, it doesn't call onError in silence. Also it doesn't call onEndOfSpeech.So I try to terminate the recognizer. If I stop manually using recognizer.stoplistening();, it calls onError many times.

Is there any wrong settings in this example? How can I develop more stable app for speech to text?

答: Speech Recognizer has a very particular behavior, maybe samsung detects  detects more noise with its microphone than the huawei. SpeechReconizer decide for itself when you have finished speaking to finalize listening and the setting to modify the silent time does not work. Its a bug from 2011 and google did not want to repair it.</p>

Body:
I try to use speech to text on android. I write a simple code and try on two devices(Huawei Android 6 api-level 23, Samsung Android 6 api-level 23).

My example is taken from this link

Permissions taken from user on runtime :

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

There many different behaviour between two devices. Huawei device calls onError callback on silence after 5 seconds. But on samsung device, it doesn't call onError in silence. Also it doesn't call onEndOfSpeech.So I try to terminate the recognizer. If I stop manually using recognizer.stoplistening();, it calls onError many times.

Is there any wrong settings in this example? How can I develop more stable app for speech to text?


问:
Select first letter from firstname only
I have been battling with this for a while now can anyone offer a solution to this.
I want to only show results where the first letter of firstname is "blah".

```<code>$n=$_GET['n'];

("SELECT * FROM my_list
                    WHERE setid = '16-17'
                    and firstname like '$n%'
                    order by studentid asc")
</code>```

The above is what is have so far but shows no results at all.

thanks all

答:
Maybe use mysql's LEFT to get the first character.

```<code>SELECT
  *
FROM my_list
WHERE
  setid = '16-17'
  AND LEFT(firstname, 1) = 'x'
ORDER BY
  studentid ASC
</code>```

Will return all firstnames starting with x.

Title: Select first letter from firstname only

Body:
I have been battling with this for a while now can anyone offer a solution to this.
I want to only show results where the first letter of firstname is "blah".

$n=$_GET['n'];

("SELECT * FROM my_list
                    WHERE setid = '16-17'
                    and firstname like '$n%'
                    order by studentid asc")

The above is what is have so far but shows no results at all.

thanks all

Body:
Maybe use mysql's LEFT to get the first character.

SELECT
  *
FROM my_list
WHERE
  setid = '16-17'
  AND LEFT(firstname, 1) = 'x'
ORDER BY
  studentid ASC

Will return all firstnames starting with x.


问:
Python - How to pass a directory as MapReduce input
I've written a simple MapReduce example in Python. If the input was a file, for example text file, for running the code we simply use the following pattern: cat <data> | map | sort | reduce, for example in my case it is: cat data | ./mapper.py | sort | ./reducer.py and all things work right.

But I changed my mapper and reducer to read data from a directory that contains .gz files. So I should pass the path of the directory as input. I test the following terminal command cat dat/ | ./mapper.py | sort | ./reducer.py while the directory containing data is dat/, but I faced error:

```<code>cat: dat/: Is a directory
Traceback (most recent call last):
  File "./mapper.py", line 9, in <module>
    for filename in glob.glob(sys.stdin + '*.gz'):
TypeError: unsupported operand type(s) for +: 'file' and 'str'
</code>```

How can I pass a directory as input to Mapreduce in Python?

The following is my code:

mapper.py

```<code>#!/usr/bin/env python
import sys
#import timeit
import glob
import gzip

QUALITY = '01459'
MISSING = '+9999'
for filename in glob.glob(sys.stdin + '*.gz'):
    f = gzip.open(filename, 'r')
    for line in f:
        val = line.strip()
        (year, temp, q) = (val[15:19], val[87:92], val[92:93])
        if temp != MISSING and q in QUALITY:
            print " %s\t%s" % (year, temp)
</code>```

reducer.py

```<code>#!/usr/bin/env python
import sys

max_val = -sys.maxint
key = ''
for line in sys.stdin:
    (key, val) = line.strip().split('\t')
    max_val = max(max_val, int(val))
print "The last IF %s\t%s" % (key, max_val)
</code>```

答:
To get path of current working directory use:

```<code>import os
path = os.getcwd()
</code>```

You can get all the files from this file:

```<code>filenames = os.listdir(path)
# filter files that doesn't have .gz filetype
filenames = [file_name for file_name in filenames if file_name.endswith('.gz')]
</code>```

You can simply iterate over the files with:

```<code>for filename in filenames:
    f = gzip.open(path+filename, 'r')
</code>```

Body:
I've written a simple MapReduce example in Python. If the input was a file, for example text file, for running the code we simply use the following pattern: cat <data> | map | sort | reduce, for example in my case it is: cat data | ./mapper.py | sort | ./reducer.py and all things work right.

But I changed my mapper and reducer to read data from a directory that contains .gz files. So I should pass the path of the directory as input. I test the following terminal command cat dat/ | ./mapper.py | sort | ./reducer.py while the directory containing data is dat/, but I faced error:

cat: dat/: Is a directory
Traceback (most recent call last):
  File "./mapper.py", line 9, in <module>
    for filename in glob.glob(sys.stdin + '*.gz'):
TypeError: unsupported operand type(s) for +: 'file' and 'str'

How can I pass a directory as input to Mapreduce in Python?

The following is my code:

mapper.py

#!/usr/bin/env python
import sys
#import timeit
import glob
import gzip

QUALITY = '01459'
MISSING = '+9999'
for filename in glob.glob(sys.stdin + '*.gz'):
    f = gzip.open(filename, 'r')
    for line in f:
        val = line.strip()
        (year, temp, q) = (val[15:19], val[87:92], val[92:93])
        if temp != MISSING and q in QUALITY:
            print " %s\t%s" % (year, temp)

reducer.py

#!/usr/bin/env python
import sys

max_val = -sys.maxint
key = ''
for line in sys.stdin:
    (key, val) = line.strip().split('\t')
    max_val = max(max_val, int(val))
print "The last IF %s\t%s" % (key, max_val)

Body:
To get path of current working directory use:

import os
path = os.getcwd()

You can get all the files from this file:

filenames = os.listdir(path)
# filter files that doesn't have .gz filetype
filenames = [file_name for file_name in filenames if file_name.endswith('.gz')]

You can simply iterate over the files with:

for filename in filenames:
    f = gzip.open(path+filename, 'r')


问:
Easy way of handling different user / pass for DB on dev. machine vs production server
I usually have a config-file with some global variables for database connectivity settings (such as db host, db name, user, pass).

I also really like to be able to just drag and drop all files from my dev machine to the production server. However, development db host etc may be different from the one on the production server.

Is there an easy way of, in PHP, saying something like "if I'm on the dev-machine, use these values"? (I'd prefer to avoid hacks based on host IP / name.) I'm thinking of something like perhaps setting something in php.ini or httpd.conf so that for instance $DEV_MACHINE, is set to true on the dev machine.

答:
You can always use the URL. The dev url and the prod url should be different. And should be pretty stable.

But the ideal way is to keep the creds separated. You don't want the prod creds getting stolen if the dev server is hacked. So it is really best to suck it up and just keep them separate.


问:
"undefined reference" errors while using tidy library, especially "tidy.h"
I'm currently using a script which validates an invalid XML file or string using tidy library.

A sample code to test it's running:

```<code>#include <tidy.h>
#include <tidybuffio.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char **argv )
{
  const char* input = "<title>Foo</title><p>Foo!";
  TidyBuffer output = {0};
  TidyBuffer errbuf = {0};
  int rc = -1;
  Bool ok;

  TidyDoc tdoc = tidyCreate();                     // Initialize "document"
  printf( "Tidying:\t%s\n", input );

  ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes );  // Convert to XHTML
  if ( ok )
    rc = tidySetErrorBuffer( tdoc, &errbuf );      // Capture diagnostics
  if ( rc >= 0 )
    rc = tidyParseString( tdoc, input );           // Parse the input
  if ( rc >= 0 )
    rc = tidyCleanAndRepair( tdoc );               // Tidy it up!
  if ( rc >= 0 )
    rc = tidyRunDiagnostics( tdoc );               // Kvetch
  if ( rc > 1 )                                    // If error, force output.
    rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 );
  if ( rc >= 0 )
    rc = tidySaveBuffer( tdoc, &output );          // Pretty Print

  if ( rc >= 0 )
  {
    if ( rc > 0 )
      printf( "\nDiagnostics:\n\n%s", errbuf.bp );
    printf( "\nAnd here is the result:\n\n%s", output.bp );
  }
  else
    printf( "A severe error (%d) occurred.\n", rc );

  tidyBufFree( &output );
  tidyBufFree( &errbuf );
  tidyRelease( tdoc );
  return rc;
}
</code>```

on running

gcc -I/usr/include/tidy tidy_example.c

I get this output on my terminal:

/tmp/cclFfP4I.o: In function main':
  tidy_exa.c:(.text+0x6e): undefined reference totidyCreate'
  tidy_exa.c:(.text+0x9e): undefined reference to tidyOptSetBool'
  tidy_exa.c:(.text+0xba): undefined reference totidySetErrorBuffer'
  tidy_exa.c:(.text+0xd6): undefined reference to tidyParseString'
  tidy_exa.c:(.text+0xeb): undefined reference totidyCleanAndRepair'
  tidy_exa.c:(.text+0x100): undefined reference to tidyRunDiagnostics'
  tidy_exa.c:(.text+0x11f): undefined reference totidyOptSetBool'
  tidy_exa.c:(.text+0x149): undefined reference to tidySaveBuffer'
  tidy_exa.c:(.text+0x1a6): undefined reference totidyBufFree'
  tidy_exa.c:(.text+0x1b2): undefined reference to tidyBufFree'
  tidy_exa.c:(.text+0x1be): undefined reference totidyRelease'
  collect2: error: ld returned 1 exit status

Any Idea as to how to resolve this issue, or any other library to do the same thing on a file or a string (invalid XML) in c/c++.

Any suggestions will also be welcomed.

答:
You forgot to link the lib using -l option.

For example

```<code>gcc -I/usr/include/tidy -ltidy tidy_example.c -o example
</code>```

If you also need to specify a specific folder for libs you must add -L option like

```<code>gcc -I/usr/include/tidy -L/usr/local/lib/tidy -ltidy tidy_example.c -o example
</code>```

Body:
I'm currently using a script which validates an invalid XML file or string using tidy library.

A sample code to test it's running:

#include <tidy.h>
#include <tidybuffio.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char **argv )
{
  const char* input = "<title>Foo</title>
Foo!";
  TidyBuffer output = {0};
  TidyBuffer errbuf = {0};
  int rc = -1;
  Bool ok;

  TidyDoc tdoc = tidyCreate();                     // Initialize "document"
  printf( "Tidying:\t%s\n", input );

  ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes );  // Convert to XHTML
  if ( ok )
    rc = tidySetErrorBuffer( tdoc, &errbuf );      // Capture diagnostics
  if ( rc >= 0 )
    rc = tidyParseString( tdoc, input );           // Parse the input
  if ( rc >= 0 )
    rc = tidyCleanAndRepair( tdoc );               // Tidy it up!
  if ( rc >= 0 )
    rc = tidyRunDiagnostics( tdoc );               // Kvetch
  if ( rc > 1 )                                    // If error, force output.
    rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 );
  if ( rc >= 0 )
    rc = tidySaveBuffer( tdoc, &output );          // Pretty Print

  if ( rc >= 0 )
  {
    if ( rc > 0 )
      printf( "\nDiagnostics:\n\n%s", errbuf.bp );
    printf( "\nAnd here is the result:\n\n%s", output.bp );
  }
  else
    printf( "A severe error (%d) occurred.\n", rc );

  tidyBufFree( &output );
  tidyBufFree( &errbuf );
  tidyRelease( tdoc );
  return rc;
}

on running

gcc -I/usr/include/tidy tidy_example.c

I get this output on my terminal:

/tmp/cclFfP4I.o: In function main':
  tidy_exa.c:(.text+0x6e): undefined reference totidyCreate'
  tidy_exa.c:(.text+0x9e): undefined reference to tidyOptSetBool'
  tidy_exa.c:(.text+0xba): undefined reference totidySetErrorBuffer'
  tidy_exa.c:(.text+0xd6): undefined reference to tidyParseString'
  tidy_exa.c:(.text+0xeb): undefined reference totidyCleanAndRepair'
  tidy_exa.c:(.text+0x100): undefined reference to tidyRunDiagnostics'
  tidy_exa.c:(.text+0x11f): undefined reference totidyOptSetBool'
  tidy_exa.c:(.text+0x149): undefined reference to tidySaveBuffer'
  tidy_exa.c:(.text+0x1a6): undefined reference totidyBufFree'
  tidy_exa.c:(.text+0x1b2): undefined reference to tidyBufFree'
  tidy_exa.c:(.text+0x1be): undefined reference totidyRelease'
  collect2: error: ld returned 1 exit status

Any Idea as to how to resolve this issue, or any other library to do the same thing on a file or a string (invalid XML) in c/c++.

Any suggestions will also be welcomed.

Body:
You forgot to link the lib using -l option.

For example

gcc -I/usr/include/tidy -ltidy tidy_example.c -o example

If you also need to specify a specific folder for libs you must add -L option like

gcc -I/usr/include/tidy -L/usr/local/lib/tidy -ltidy tidy_example.c -o example


问:
vue.js How to call a function inside a for loop and pass the current item?
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

```<code><template v-for="issue in search_results.issues">
  <tr v-if="testIssue(issue)">
     ....
  </tr>
</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});
</code>```

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

答:
Your scenario works with a similar example in this fiddle.

But you can try it this way also:

You can create a custom directive named v-hide and pass issue to it as its value.

Then in the directive you can test for testIssue() and set the particular element's display to none

```<code><template v-for="issue in search_results.issues">
  <tr v-hide="issue">
     ....
  </tr>
</template>

var releaseApp = new Vue({
  el: '#release-app',
  directive:{
    hide: {
        bind(el, binding, Vnode){
            var vm = Vnode.context;
            var issue = binding.value;
            if(vm.testIssue(issue)){
                el.style.display = 'none';
            }
        }
    }
  },
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});

</code>```

Body:
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

<template v-for="issue in search_results.issues">

     ....

</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

Body:
Your scenario works with a similar example in this fiddle.

But you can try it this way also:

You can create a custom directive named v-hide and pass issue to it as its value.

Then in the directive you can test for testIssue() and set the particular element's display to none

<template v-for="issue in search_results.issues">
  <tr v-hide="issue">
     ....
  </tr>
</template>

var releaseApp = new Vue({
  el: '#release-app',
  directive:{
    hide: {
        bind(el, binding, Vnode){
            var vm = Vnode.context;
            var issue = binding.value;
            if(vm.testIssue(issue)){
                el.style.display = 'none';
            }
        }
    }
  },
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});


问:
WP7 dynamic controls
Is it possible to generate dynamic WP7 controls in code behind (.cs)  using  .xaml template (like inflating in Android) ,
 or should I generate it all manually? For example I need dynamic tabs (PivotItems)</p>

答:
It is possible to do so - but definitely not recommended.

I am not sure why you would want to have more than three pivot items in any application anyway. Simply have three and reuse them as they wrap around. You only need to change the data in the pivotItems on a page transition, not create more and more of them.

Title: WP7 dynamic controls


问:
send Ajax call and form_tag in rails
I have a problem with my ajax call in rails when I use form_tag or form_for

my form_tag looks like:

```<code>` <%= form_tag(type_name_Tous_path, :method => "get") do %>
        <%= text_field_tag :key,params[:key]" %>
        <%= text_field_tag :lieu,params[:lieu]" %>
        <%= select_tag :nom, options_from_collection_for_select(TypeName.all, :id, :nom, params[:nom]),id:"select_categori"%></span>
        <button id="input_btn"><%= submit_tag "Chercher"%></button>
        <ul id="sous_select">
          <% @tag %>
        </ul>
    <% end %>`
</code>```

my ajax call looks like:

```<code> ` $(function(){
      $(".selectable").selectable({
          selected: function(event, ui){
              var selected=$("li[class$='ui-selected']").val();
              $('#input_btn').click(function(){
                  alert(selected);
                  if(selected != null){
                      $.ajax({
                          url:'/type_name/Tous',
                          type:'Get',
                          data:{my_ta:selected},
                          success:function(data){
                              alert(data)
                          },
                          error:function(data){
                              alert("erreur"+data)
                          }
                      })
                  }else{
                      console.log('pas de selection proposé')
                  }})}});});`
</code>```

And in my controller when I make a puts "ok ok #{params[:my_ta]}" I have two answers , the first one , with the good answer exemple "ok ok 9" and after the second answer is like "ok ok" , it's because I call twice type_name route?

答:
Rails can help you with this!

If you use form_with instead of your form_tag, Rails will automatically assume that your form will be using an ajax call.

So now you will have a corresponding action in your controller where you're pointing your route to have it.
For example, if your route were something like this:

```<code>#routes.rb
...
# Bad practice to use capital letters in snake case,
# only_small_letters_will_do
get 'type_name' => 'your_controller#type_name', as: "type_name_tous"
</code>```

Now your action type_name will have your forms params on submit.

I would recommend putting a byebug in your new type_name action and do a  submit to see how your params are doing :)

The values are there, so you don't have to do a

```<code>var selected=$("li[class$='ui-selected']").val();
</code>```

Read more about handling javascript in Rails

Title: send Ajax call and form_tag in rails

Body:
I have a problem with my ajax call in rails when I use form_tag or form_for

my form_tag looks like:

` <%= form_tag(type_name_Tous_path, :method => "get") do %>
        <%= text_field_tag :key,params[:key]" %>
        <%= text_field_tag :lieu,params[:lieu]" %>
        <%= select_tag :nom, options_from_collection_for_select(TypeName.all, :id, :nom, params[:nom]),id:"select_categori"%>
        <button id="input_btn"><%= submit_tag "Chercher"%></button>

          <% @tag %>

    <% end %>`

my ajax call looks like:

 ` $(function(){
      $(".selectable").selectable({
          selected: function(event, ui){
              var selected=$("li[class$='ui-selected']").val();
              $('#input_btn').click(function(){
                  alert(selected);
                  if(selected != null){
                      $.ajax({
                          url:'/type_name/Tous',
                          type:'Get',
                          data:{my_ta:selected},
                          success:function(data){
                              alert(data)
                          },
                          error:function(data){
                              alert("erreur"+data)
                          }
                      })
                  }else{
                      console.log('pas de selection proposé')
                  }})}});});`

And in my controller when I make a puts "ok ok #{params[:my_ta]}" I have two answers , the first one , with the good answer exemple "ok ok 9" and after the second answer is like "ok ok" , it's because I call twice type_name route?

Body:
Rails can help you with this!

If you use form_with instead of your form_tag, Rails will automatically assume that your form will be using an ajax call.

So now you will have a corresponding action in your controller where you're pointing your route to have it.
For example, if your route were something like this:

#routes.rb
...
# Bad practice to use capital letters in snake case,
# only_small_letters_will_do
get 'type_name' => 'your_controller#type_name', as: "type_name_tous"

Now your action type_name will have your forms params on submit.

I would recommend putting a byebug in your new type_name action and do a  submit to see how your params are doing :)

The values are there, so you don't have to do a

var selected=$("li[class$='ui-selected']").val();

Read more about handling javascript in Rails


问:
How to pass parameters to a controller (testing)
I'm testing with PHPUnit a controller which has at least one parameter:

```<code>public function testSomething($a,$b='')
{
}
</code>```

Im trying to test it this way:

```<code>$params = array('a'=>'foo','b'=>'bar');
$output = $this->request('POST', ['MyController','Something'], $params);
</code>```

But I'm getting:

ArgumentCountError: Too few arguments to function MyController::Something

How can I pass those parameters?

Note: I used a library for integrating PHPUnit to Codeigniter:

```<code>"require-dev": {
        "kenjis/ci-phpunit-test": "^0.15.0"
    }
</code>```

答:
you can use flash_ which is in the CodeIgniter.Try the below one:

```<code>$params = array('a'=>'foo','b'=>'bar');
$this->session->set_flashdata('params ', $params);
$output = $this->request('POST', ['MyController','Something']);
</code>```

Controller:

In Controller you can get the values from flashdata function.

```<code>$this->session->flashdata('params');
</code>```

or

```<code>$a='foo';$b='bar';
$output = $this->request('POST', ['MyController','Something',$a,$b]);
</code>```

Body:
I'm testing with PHPUnit a controller which has at least one parameter:

public function testSomething($a,$b='')
{
}

Im trying to test it this way:

$params = array('a'=>'foo','b'=>'bar');
$output = $this->request('POST', ['MyController','Something'], $params);

But I'm getting:

ArgumentCountError: Too few arguments to function MyController::Something

How can I pass those parameters?

Note: I used a library for integrating PHPUnit to Codeigniter:

"require-dev": {
        "kenjis/ci-phpunit-test": "^0.15.0"
    }

Body:
you can use flash_ which is in the CodeIgniter.Try the below one:

$params = array('a'=>'foo','b'=>'bar');
$this->session->set_flashdata('params ', $params);
$output = $this->request('POST', ['MyController','Something']);

Controller:

In Controller you can get the values from flashdata function.

$this->session->flashdata('params');

or

$a='foo';$b='bar';
$output = $this->request('POST', ['MyController','Something',$a,$b]);


问:
html or handlebars encoding issue when trying to send email from Mandrill
I want to use mandrill as mail sending provider, and looks like it support templates with handlebars.js template syntax. And in simpliest case it works fine and send email is required, so something like that sends ok:

```<code><body>
<p>{{EmailBody}}</p>
</body>
</code>```

However, when I trying to add link on the page and populate it's address with some value, all is broken due to some encoding issue.

So, I want something like that:

```<code><body>
    <a href="{{Address}}">Link</a>
</body>
</code>```

but instead of correctly parsing this it's on saving convert code to something like:

```<code><body>
    <a href="%7B%7BAddress%7D%7D">Link</a>
</body>
</code>```

which of course not working. I also try to use single quotes instead of double one, but when saving template it's still change it to double quotes and again encode {{}} symbols.

So, how could I fix this problem?

答:
I'd suggest trying two things:

Check that "Address" exists by compiling it outside of Mandrill. It possible that it may be within an array or, if referenced as a partial, may need to be declared as {{> Address}}

Make sure that Handlebars is selected as your Merge Language in Mandrill as described at the bottom of here - https://mandrill.zendesk.com/hc/en-us/articles/205582537-Using-Handlebars-for-Dynamic-Content

Body:
I want to use mandrill as mail sending provider, and looks like it support templates with handlebars.js template syntax. And in simpliest case it works fine and send email is required, so something like that sends ok:

{{EmailBody}}

However, when I trying to add link on the page and populate it's address with some value, all is broken due to some encoding issue.

So, I want something like that:

    Link

but instead of correctly parsing this it's on saving convert code to something like:

    Link

which of course not working. I also try to use single quotes instead of double one, but when saving template it's still change it to double quotes and again encode {{}} symbols.

So, how could I fix this problem?