问:
CSV file with japanese characters not opening properly in Excel 2007
I have a simple JSP to download a csv file containing Japanese characters. Downloaded file opens correctly in notepad++ and shows right characters but when I try to open same file in Excel 2007, It shows some different characters, probably in some other encoding.

My JSP looks like this.

```<code><%@ page language="java" contentType="text/csv; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/csv; charset=UTF-8");
    response.addHeader("Content-Disposition", "attachment; filename= " + "Test.csv");
    OutputStream output = response.getOutputStream();
    System.out.println("Chaaracter encoding : " + response.getCharacterEncoding());
    Writer writer = new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));

    String japanese = "注目のキーワード";
    InputStream in = new ByteArrayInputStream(japanese.getBytes("UTF-8"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    String line = null;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.write(System.getProperty("line.separator"));
    }
    reader.close();
    writer.flush();
    writer.close();
%>
</code>```

This string in Excel 2007 looks like this : æ³¨ç›®ã®ã‚ãƒ¼ãƒ¯ãƒ¼ãƒ‰

Could any one please help me here. User should be able to directly open file in Excel when he clicks on download link(above jsp).

Any help would be appreciated.

Thanks
Jitendra

答: I have already answered similar question. Please read here: setting a UTF-8 in java and csv file. Generally the problem can be solved by putting "magic" code (know as Byte Order Mark) in the beginning of the file. </p>

Body:
I have a simple JSP to download a csv file containing Japanese characters. Downloaded file opens correctly in notepad++ and shows right characters but when I try to open same file in Excel 2007, It shows some different characters, probably in some other encoding.

My JSP looks like this.

<%@ page language="java" contentType="text/csv; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/csv; charset=UTF-8");
    response.addHeader("Content-Disposition", "attachment; filename= " + "Test.csv");
    OutputStream output = response.getOutputStream();
    System.out.println("Chaaracter encoding : " + response.getCharacterEncoding());
    Writer writer = new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));

    String japanese = "注目のキーワード";
    InputStream in = new ByteArrayInputStream(japanese.getBytes("UTF-8"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    String line = null;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.write(System.getProperty("line.separator"));
    }
    reader.close();
    writer.flush();
    writer.close();
%>

This string in Excel 2007 looks like this : æ³¨ç›®ã®ã‚ãƒ¼ãƒ¯ãƒ¼ãƒ‰

Could any one please help me here. User should be able to directly open file in Excel when he clicks on download link(above jsp).

Any help would be appreciated.

Thanks
Jitendra


来源: stackexchange

问:
CSS produces a strange space
I use markdown with css, output html sometimes.

But when display in browser, a space prefix to my code segment, only first line. In the pic below, it just before "gconftool".

If I disable css, here is no space anymore. So it really comes from css. Of course I checked html, no space character here.

Below is my css.

```<code>pre {
    display:block;
/*    overflow:auto;*/
    width: 90%;
    margin-left: 5%;
    background-color:#333;
    padding: 0.1em 0.5em 0.1em 0.5em;
    word-wrap: break-word;
/*    border-color: #080;*/
/*    border-style:dotted none;*/
    border-left:0.5em solid #080;
}
code {
    background-color:#333;
    color: #eee;
    font-family: 'Courier 10 Pitch',"Courier New",Monospace;
    text-shadow: none;
}
</code>```

So how can I get rid of this space.

append:
I had solved it. thanks jsfiddle.net, thanks all.

答:
You have a margin and padding here:

```<code>em,strong,code {
    margin: 0px 0.2em 0px 0.2em;
    padding: 0px 0.4em 0px 0.4em;
    font-weight:bold;
    font-style: normal;
}
</code>```

Are they there for any need? Because when I remove those two your spacing is gone. Below a fiddle.

https://jsfiddle.net/Ly0429yr/2/

ContentLicense: CC BY-SA 3.0

Title: CSS produces a strange space

Body:
I use markdown with css, output html sometimes.

But when display in browser, a space prefix to my code segment, only first line. In the pic below, it just before "gconftool".

If I disable css, here is no space anymore. So it really comes from css. Of course I checked html, no space character here.

Below is my css.

pre {
    display:block;
/*    overflow:auto;*/
    width: 90%;
    margin-left: 5%;
    background-color:#333;
    padding: 0.1em 0.5em 0.1em 0.5em;
    word-wrap: break-word;
/*    border-color: #080;*/
/*    border-style:dotted none;*/
    border-left:0.5em solid #080;
}
code {
    background-color:#333;
    color: #eee;
    font-family: 'Courier 10 Pitch',"Courier New",Monospace;
    text-shadow: none;
}

So how can I get rid of this space.

append:
I had solved it. thanks jsfiddle.net, thanks all.

Body:
You have a margin and padding here:

em,strong,code {
    margin: 0px 0.2em 0px 0.2em;
    padding: 0px 0.4em 0px 0.4em;
    font-weight:bold;
    font-style: normal;
}

Are they there for any need? Because when I remove those two your spacing is gone. Below a fiddle.

https://jsfiddle.net/Ly0429yr/2/


问:
If any input field value entered zero then disable else enable
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

答:
$(document).ready(
           function() {

          $('input').change(function()  {

          // $("input").each(function() {

            if($(this).val()==0)
            {
               $("#submitBtn").attr("disabled","disabled");
            console.log("Disable");
            }
           else{
                    $("#submitBtn").removeAttr("disabled","disabled");
             console.log("Enable");
           }

           //  });

           });
              });
           ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
        <button id="submitBtn" >Submit</button></code>```

Body:
$(document).ready(
           function() {

          $('input').change(function()  {

          // $("input").each(function() {

            if($(this).val()==0)
            {
               $("#submitBtn").attr("disabled","disabled");
            console.log("Disable");
            }
           else{
                    $("#submitBtn").removeAttr("disabled","disabled");
             console.log("Enable");
           }

           //  });

           });
              });

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
        <button id="submitBtn" >Submit</button>


问:
Macro to delete only values of 0.00 and not 150.00, etc
I created a macro to search a column and delete the entire row if the value is 0.00. The problem is it also deletes all rows that contain that string i.e 140.00, 150.00, etc... so i'm losing good data. Not sure how to fix?

My Macro:

```<code>Dim c As Range
Dim SrchRng

Set SrchRng = ActiveSheet.Range("J5", ActiveSheet.Range("J65536").End(xlUp))
Do
    Set c = SrchRng.Find("0.00", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing
</code>```

Thanks for any help

答:
you can delete wanted rows in one shot:</p>

```<code>With Range("J4", Cells(Rows.Count, "J").End(xlUp)) '<--| assuming "J4" cell is the "header" of data in cells from "J5" down to last column J not empty cell
    .AutoFilter Field:=1, Criteria1:="0.00" '<--| filtre cells whose content is "0.00"
    If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete '<--| if any cell found other than header then delete corresponding rows (skipping headers)
    .Parent.AutoFilterMode = False
End With
</code>```

Body:
I created a macro to search a column and delete the entire row if the value is 0.00. The problem is it also deletes all rows that contain that string i.e 140.00, 150.00, etc... so i'm losing good data. Not sure how to fix?

My Macro:

Dim c As Range
Dim SrchRng

Set SrchRng = ActiveSheet.Range("J5", ActiveSheet.Range("J65536").End(xlUp))
Do
    Set c = SrchRng.Find("0.00", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing

Thanks for any help

Body:
you can delete wanted rows in one shot:

With Range("J4", Cells(Rows.Count, "J").End(xlUp)) '<--| assuming "J4" cell is the "header" of data in cells from "J5" down to last column J not empty cell
    .AutoFilter Field:=1, Criteria1:="0.00" '<--| filtre cells whose content is "0.00"
    If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete '<--| if any cell found other than header then delete corresponding rows (skipping headers)
    .Parent.AutoFilterMode = False
End With


问:
How is HttpResponseRedirectBase class being called when I call HttpResponseRedirect
I am trying to figure out how HttpResponseRedirectBase is being called when I call this

```<code>return HttpResponseRedirect(next_page, context)
</code>```

I believe this question has more to do with python than Django but I cannot find the answer to this question.I understand that in python the derived class needs to explicitly call the __init__ of the base class in order to initialize it.So far this is what I have seen

```<code>class HttpResponseRedirect(HttpResponseRedirectBase):
    status_code = 302
</code>```

Now my question is how is the initializer of  HttpResponseRedirectBase being called here ? I tried simulating the above situation

```<code>class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"

class bar(foo):
  status_code = 302

b = bar(23)
</code>```

I am not sure how init of foo will be called in this case ? In this case I get the error

```<code>Traceback (most recent call last):
  File "python", line 5, in <module>
TypeError: Error when calling the metaclass bases
    function() argument 1 must be code, not str
</code>```

Any help clearing this out would be appreciated.

答:
You are trying to inherit a function

```<code>class bar(foo):
</code>```

Where foo is function.Did you mean

```<code>class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"
</code>```

Body:
I am trying to figure out how HttpResponseRedirectBase is being called when I call this

return HttpResponseRedirect(next_page, context)

I believe this question has more to do with python than Django but I cannot find the answer to this question.I understand that in python the derived class needs to explicitly call the __init__ of the base class in order to initialize it.So far this is what I have seen

class HttpResponseRedirect(HttpResponseRedirectBase):
    status_code = 302

Now my question is how is the initializer of  HttpResponseRedirectBase being called here ? I tried simulating the above situation

class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"

class bar(foo):
  status_code = 302

b = bar(23)

I am not sure how init of foo will be called in this case ? In this case I get the error

Traceback (most recent call last):
  File "python", line 5, in <module>
TypeError: Error when calling the metaclass bases
    function() argument 1 must be code, not str

Any help clearing this out would be appreciated.

Body:
You are trying to inherit a function

class bar(foo):

Where foo is function.Did you mean

class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"


问:
Alternatives to the Turing Test
So we learned a bit about the Turing Test in my AI class.  This got me thinking about it.  I can see a few limitations with it:

It's limited to a certain context.  What if I'm not designing an AI to converse with humans?

It favors acting humanly over acting rationally.  For example, if I'm designing an AI to control nuclear missiles, do I really want it to act human?  Granted, this is an extreme example, but you get the idea.

It could be influenced by factors that don't indicate that the computer can think humanly.  For example, suppose I ask what 2334 * 321 is.  I could tell if the device is a computer because it will probably answer me fairly quickly while a human would have to figure it out.  The solution?  Make the computer pause.

Now, I'm sure that the Turing Test still has its place in determining machine intelligence.  But I see it as being fairly limited in scope.  Are there any alternatives?  For that matter, am I wrong as to what I perceive to be its limitations?

EDIT:  Let me be clear:  I'm not suggesting that the Turing Test should be abandoned.  I'm just curious if there are any other tests that overcome its limitations (probably trading them for other limitations).

答:
Depends on how you define a conversation.

The question-and-answer context used in Turing's thought experiment might seem limited and contrived.  But what if you switched it to a medical diagnostic session or a financial portfolio optimization problem?  Those feel less like a Q&A session, but it would still be difficult to get a machine to be indistinguishable from a human.

What about natural language processing?  Still not a solved problem, because natural grammars aren't context-free.

I think the Turing test still holds up as a way of thinking about the problem.

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 2.5

Title: Alternatives to the Turing Test

LastEditorDisplayName: Rob


问:
How to split lines from Windows text file (/r/n separation)
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

```<code>string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array
</code>```

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

答: You may find it much easier to simply use File.ReadAllLines() or File.ReadLines()</p>

Body:
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.


问:
How to make my Discord bot come online
So I've been having trouble with my Discord bot on Visual Studio 2015, C#. I've just started out literally 5 minutes ago and I've come across a problem that I've looked at but just can't seem to find out the problem with. It's saying that

```<code>await discord.Connect("code here")
</code>```

should be a Username and password, or a token

But when I put my token in it says it needs two arguments.

Here is my code:

I've also tried putting

```<code>await discord.Connect("Client ID", "Secret");
</code>```

But it's just not working. Sorry if I'm not giving enough information, or if mine just isn't good enough, but please. What am I doing wrong?

答:
The method you are using is no longer working.

In 1.0 you should be using like this:

```<code>string token = "YOUR TOKEN";
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
</code>```

Title: How to make my Discord bot come online

Body:
So I've been having trouble with my Discord bot on Visual Studio 2015, C#. I've just started out literally 5 minutes ago and I've come across a problem that I've looked at but just can't seem to find out the problem with. It's saying that

await discord.Connect("code here")

should be a Username and password, or a token

But when I put my token in it says it needs two arguments.

Here is my code:

I've also tried putting

await discord.Connect("Client ID", "Secret");

But it's just not working. Sorry if I'm not giving enough information, or if mine just isn't good enough, but please. What am I doing wrong?

Body:
The method you are using is no longer working.

In 1.0 you should be using like this:

string token = "YOUR TOKEN";
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();


问:
How to round to the closest whole number without using known functions in c?
like 52.7-->53, 5.5-->6, 3.2->3</p>

答:
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:

```<code>((int)(num + ((num > 0)? +0.5 : -0.5)))
</code>```

Body: like 52.7-->53, 5.5-->6, 3.2->3

Body:
To handle negative numbers properly (-52.7 ==> -53 (away from zero)), you must check if the initial value is negative:

((int)(num + ((num > 0)? +0.5 : -0.5)))


问:
Performance of update vs if exists then update
I am wondering if there is a performance difference for sql between

```<code>update dbo.table
set x = 1
where x is null
</code>```

and

```<code>if exists (select 1
           from dbo.table t
           where t.x is null)
begin
    update dbo.table
    set x = 1
    where x is null
end
</code>```

in case there are no null values found for x.

I wasn't able to find an answer for this so I hope anyone can clear this up for me. Thanks in advance.

答: The first one is correct. The where conditions in if exists and update statements in the second code snippet are the same: from dbo.table t where t.x is null so I do not expect any significant speed difference in case there are no null values found for x.

Body:
I am wondering if there is a performance difference for sql between

update dbo.table
set x = 1
where x is null

and

if exists (select 1
           from dbo.table t
           where t.x is null)
begin
    update dbo.table
    set x = 1
    where x is null
end

in case there are no null values found for x.

I wasn't able to find an answer for this so I hope anyone can clear this up for me. Thanks in advance.


问:
How does one write a good unit test without mocking everything?
I have read that mocking everything is bad.

Test Smell: Everything is mocked

Mock Everything Is a Good Way to Sink

I have also read that unit tests look at a single component whilst Integration tests test an entire system working together.

Writing Great Unit Tests: Best and Worst Practices

This confuses me. As I understand it, to write a proper unit test one needs to isolate a single component by mocking everything but the S.U.T. If one uses real objects throughout the test, doesn't that test become an integration test?

How does one write a good (isolated) unit test without mocking everything?

答:
Mocking model is a bad smell. You should mock only dependencies that participate to the logic of the tested method, not the data.
 But even with this simple rule, things are not always obvious.

In some cases, unit testing a method is straight as the method has its own logic rules and has also one or two invocations to a distinct external dependency to perform to complete its logic.
In this case mocking seems natural.

In some other cases, unit testing is less obvious as the method to test has very few logic rules. It does in its implementation mainly calls to external dependencies. In this case mocking seems really unnatural as the essential of the test could be mocking.
Testing the flow invocations with mocking each call is testing a white box. It s brittle as it doesn't test the method logic behavior.It proves only one thing  : that your code does what it does.

In this case, I think that integration tests should be favored over unit tests.


问:
What is the purpose of the IPython.display.display_markdown() function?
I frequently need to produce Markdown formatted output in Jupyter notebook. The way I do it is:

```<code>from IPython.display import display, Markdown
display(Markdown('# This is a Title'))
</code>```

This will produce a beautiful formatted output. However there also exists a function called display_markdown() that I would expect to do the same. But apparently it doesn't do anything at all. What is it supposed to do?

答: You need to set raw=True since it is a raw markdown:

Body:
I frequently need to produce Markdown formatted output in Jupyter notebook. The way I do it is:

from IPython.display import display, Markdown
display(Markdown('# This is a Title'))

This will produce a beautiful formatted output. However there also exists a function called display_markdown() that I would expect to do the same. But apparently it doesn't do anything at all. What is it supposed to do?


问:
i want to add two row's value in single row
I want to add two city_name's value (HYD + HYDTC) in HYD

```
CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         20
  HYDTC       30
  MUM         10
```

I want to output in this way:-

```
CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         50
  MUM         10
```

答:
If you want to consolidate rows based on the first three characters, then you can use the following query:

```<code>SELECT LEFT(CITY_NAME, 3) AS CITY_NAME, SUM(VALUE) AS VALUE
FROM mytable
GROUP BY LEFT(CITY_NAME, 3)
</code>```

Body:
I want to add two city_name's value (HYD + HYDTC) in HYD

CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         20
  HYDTC       30
  MUM         10

I want to output in this way:-

CITY_NAME    VALUE
  CCU         10
  CHI         12
  DEL         15
  HYD         50
  MUM         10

Body:
If you want to consolidate rows based on the first three characters, then you can use the following query:

SELECT LEFT(CITY_NAME, 3) AS CITY_NAME, SUM(VALUE) AS VALUE
FROM mytable
GROUP BY LEFT(CITY_NAME, 3)


问:
Error compiling Gradle from Android application: The SDK Build Tools revision (24.0.3) is too low for project
```<code>apply plugin: 'com.android.application'

android {
     compileSdkVersion 19
     buildToolsVersion '24.0.3'

defaultConfig {
    applicationId "com.android.projectz.teamrocket.thebusapp"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "0.7alpha-sa3cvc6"
    vectorDrawables.useSupportLibrary = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:recyclerview-v7:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'com.github.paolorotolo:appintro:4.1.0'
    compile 'com.afollestad.material-dialogs:core:0.9.2.3'
    compile 'com.afollestad.material-dialogs:commons:0.9.1.0'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
}
</code>```

This is the error from the "console" :

```<code>Error:The SDK Build Tools revision (24.0.3) is too low for project ':app'. Minimum required is 25.0.0
</code>```

I don't know why, I had updated my Android Studio (from 2.2 to 2.3), also I had installed all the needed packages, all the necessary package (SDK and other). Before I upgraded my Android Studio, the configuration worked fine.

答:
Error:The SDK Build Tools revision (24.0.3) is too low for project

Update the buildToolsVersion 25.0.2 but your real issue is here:

```<code>compileSdkVersion 19
</code>```

Since you are using the support libraries v24, you have to compile with API 24+.

Also, it is strongly recommended that you always compile with the latest SDK.

Body:
apply plugin: 'com.android.application'

android {
     compileSdkVersion 19
     buildToolsVersion '24.0.3'

defaultConfig {
    applicationId "com.android.projectz.teamrocket.thebusapp"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "0.7alpha-sa3cvc6"
    vectorDrawables.useSupportLibrary = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile files('libs/commons-net-3.5.jar')
    compile 'com.android.support:recyclerview-v7:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'com.github.paolorotolo:appintro:4.1.0'
    compile 'com.afollestad.material-dialogs:core:0.9.2.3'
    compile 'com.afollestad.material-dialogs:commons:0.9.1.0'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'org.apache.commons:commons-io:1.3.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
}

This is the error from the "console" :

Error:The SDK Build Tools revision (24.0.3) is too low for project ':app'. Minimum required is 25.0.0

I don't know why, I had updated my Android Studio (from 2.2 to 2.3), also I had installed all the needed packages, all the necessary package (SDK and other). Before I upgraded my Android Studio, the configuration worked fine.

Body:
Error:The SDK Build Tools revision (24.0.3) is too low for project

Update the buildToolsVersion 25.0.2 but your real issue is here:

compileSdkVersion 19

Since you are using the support libraries v24, you have to compile with API 24+.

Also, it is strongly recommended that you always compile with the latest SDK.


问:
Get the Last Inserted Id Using Laravel Eloquent
I'm currently using the below code to insert data in a table:

<?php

public function saveDetailsCompany()
{
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}
```

I want to return the last ID inserted but I don't know how to get it.

Kind regards!

答:
After

```<code>$data->save()
</code>```

$data->id will give you the inserted id,

Note: If your autoincrement column name is sno then you should use
$data->sno and not $data->id

ContentLicense: CC BY-SA 4.0

Body:
I'm currently using the below code to insert data in a table:

<?php

public function saveDetailsCompany()
{
    $post = Input::All();

    $data = new Company;
    $data->nombre = $post['name'];
    $data->direccion = $post['address'];
    $data->telefono = $post['phone'];
    $data->email = $post['email'];
    $data->giro = $post['type'];
    $data->fecha_registro = date("Y-m-d H:i:s");
    $data->fecha_modificacion = date("Y-m-d H:i:s");

    if ($data->save()) {
        return Response::json(array('success' => true), 200);
    }
}

I want to return the last ID inserted but I don't know how to get it.

Kind regards!

Body:
After

$data->save()

$data->id will give you the inserted id,

Note: If your autoincrement column name is sno then you should use
$data->sno and not $data->id


问:
Implicit conversion warning in VB.Net
The first, my code as below:

```<code>    Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            m_selectEvents = eventType  ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            m_mouseEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassMouseEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            m_triadEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassTriadEvents'.
        End If

    End If
</code>```

Because of the warning display after the compiler, I modified it as shown below but still displayed a warning.

At the second If statement, i think type of eventType is Object. Is that different? My code where is wrong Please tell me how hide warnings ?

Thanks in advance.

```<code>    Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            'm_selectEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassSelectEvents)
            m_selectEvents = DirectCast(eventType, ClassSelectEvents)
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            'm_mouseEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassMouseEvents)  ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassMouseEvents)    ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            'm_triadEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassTriadEvents)  ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassTriadEvents)    ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
        End If

    End If
</code>```

答:
You are assigning to m_selectEvents in all three If blocks when the last two should be m_mouseEvents and m_triadEvents.

By the way, there's no point using TryCast there because your If statement has already guaranteed that the cast will work.  You should just use DirectCast.  If you wanted to use TryCast then you'd do it like this:

```<code>m_selectEvents = TryCast(eventType, ClassSelectEvents)

If m_selectEvents Is Nothing Then
    m_mouseEvents = DirectCast(eventType, ClassMouseEvents)

    If m_mouseEvents Is Nothing Then
        m_triadEvents = DirectCast(eventType, ClassTriadEvents)
    End If
End If
</code>```

TryCast will return Nothing if the cast fails so you test for Nothing after trying to cast.  If you're not testing for Nothing after using TryCast then you almost certainly shouldn't be using TryCast to begin with.
 EDIT: Hmmm... I see that you changed TryCast to DirectCast after/while I posted my answer. Hopefully my explanation helped some anyway.

Title: Implicit conversion warning in VB.Net

Body:
The first, my code as below:

    Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            m_selectEvents = eventType  ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            m_mouseEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassMouseEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            m_triadEvents = eventType   ' Warning BC 42016: Implicit type conversion from 'Object' to 'ClassTriadEvents'.
        End If

    End If

Because of the warning display after the compiler, I modified it as shown below but still displayed a warning.

At the second If statement, i think type of eventType is Object. Is that different? My code where is wrong Please tell me how hide warnings ?

Thanks in advance.

    Dim eventType As Object = Nothing

    eventType = GetEventType()

    If Not (eventType Is Nothing) Then

        If TypeOf eventType Is ClassSelectEvents Then
            'm_selectEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassSelectEvents)
            m_selectEvents = DirectCast(eventType, ClassSelectEvents)
        End If

        If TypeOf eventType Is ClassMouseEvents Then
            'm_mouseEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassMouseEvents)  ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassMouseEvents)    ' Warning BC42016: Implicit type conversion from 'ClassMouseEvents' to 'ClassSelectEvents'.
        End If

        If TypeOf eventType Is ClassTriadEvents Then
            'm_triadEvents = eventType
            'm_selectEvents = TryCast(eventType, ClassTriadEvents)  ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
            m_selectEvents = DirectCast(eventType, ClassTriadEvents)    ' Warning BC42016: Implicit type conversion from 'ClassTriadEvents' to 'ClassSelectEvents'.
        End If

    End If

Body:
You are assigning to m_selectEvents in all three If blocks when the last two should be m_mouseEvents and m_triadEvents.

By the way, there's no point using TryCast there because your If statement has already guaranteed that the cast will work.  You should just use DirectCast.  If you wanted to use TryCast then you'd do it like this:

m_selectEvents = TryCast(eventType, ClassSelectEvents)

If m_selectEvents Is Nothing Then
    m_mouseEvents = DirectCast(eventType, ClassMouseEvents)

    If m_mouseEvents Is Nothing Then
        m_triadEvents = DirectCast(eventType, ClassTriadEvents)
    End If
End If

TryCast will return Nothing if the cast fails so you test for Nothing after trying to cast.  If you're not testing for Nothing after using TryCast then you almost certainly shouldn't be using TryCast to begin with.
 EDIT: Hmmm... I see that you changed TryCast to DirectCast after/while I posted my answer. Hopefully my explanation helped some anyway.


问:
How to use iOS 10.3 devices with Xcode 8.2.1
This iPad mini 2 (Model A1490) is running iOS 10.3 (14E277), which may not be supported by this version of Xcode.

my xcode version 8.2.1
my Device ios version 10.2

答:
According to the message it feedbacks to you, I believe your device iOS version is 10.3. And you have to update your Xcode to 8.3 since it provides the necessary SDKs for iOS 10.3 (see more detail from Apple).

I think what you can do is:

Double check your device iOS version

If it is iOS 10.3, update your Xcode from App Store (Notice that it requires your Mac running macOS 10.12 or later). Or if you have to test your project on iOS 10.2, just find a way to downgrade it (Downgrade iOS 10.3 to the previous iOS version).

Hope this helps.


问:
Can't access JSON attribute.
```<code>alert(fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response) {
        return response.json()['description']
    }))
</code>```

I was expecting Your app fetched this from a remote endpoint! but apparently, this is just an Object?

According to the other answers I've checked, like this one, this should work perfectly.

答:
You can access the description as shown below.

To save the value and use it later, you can use states (aka Component States).

```<code>.then(function(response) {
    var resJson = response.json();
    var des = resJson['description'];
    this.setState(
         {
             description: des
         }
    )

    }))
</code>```

You can define your states in the React Component like so:

```<code>class MyClass extends Component {

    state = {
        description: ""
    }
</code>```

And retreive the state like so:

```<code>var currentState = this.state.description;
</code>```

Title: Can't access JSON attribute.

Body:
alert(fetch('https://facebook.github.io/react-native/movies.json')
    .then(function(response) {
        return response.json()['description']
    }))

I was expecting Your app fetched this from a remote endpoint! but apparently, this is just an Object?

According to the other answers I've checked, like this one, this should work perfectly.

Body:
You can access the description as shown below.

To save the value and use it later, you can use states (aka Component States).

.then(function(response) {
    var resJson = response.json();
    var des = resJson['description'];
    this.setState(
         {
             description: des
         }
    )

    }))

You can define your states in the React Component like so:

class MyClass extends Component {

    state = {
        description: ""
    }

And retreive the state like so:

var currentState = this.state.description;


问:
Calling a function with an array of parameters in Dart
I'm trying to call a function in dart with a set of parameters that is provided in an array. I want to be able to pass the parameters to the function without knowing how many parameters there will be.

Ex:

```<code>someFunc(var a, var b, var c) {...}
paramArray = [1,2,3];

callFunction(var func, var params) {
  //Here is a sloppy workaround to what I want the functionality to be
  switch(params.length) {
  case 0:
      func()
      break;
    case 1:
      func(params[0])
      break;
    case 2:
      func(params[0], params[1])
      break;
    ...
  }
}

callFunction(someFunc, paramArray);
</code>```

Does there exist a cleaner way to do this in dart without changing the signature of someFunc?

答:
The Function.apply method does precisely what you want.
You can do Function.apply(func, params) and it will call func if the parameters match (and throw if they don't).

Body:
I'm trying to call a function in dart with a set of parameters that is provided in an array. I want to be able to pass the parameters to the function without knowing how many parameters there will be.

Ex:

someFunc(var a, var b, var c) {...}
paramArray = [1,2,3];

callFunction(var func, var params) {
  //Here is a sloppy workaround to what I want the functionality to be
  switch(params.length) {
  case 0:
      func()
      break;
    case 1:
      func(params[0])
      break;
    case 2:
      func(params[0], params[1])
      break;
    ...
  }
}

callFunction(someFunc, paramArray);

Does there exist a cleaner way to do this in dart without changing the signature of someFunc?


问:
Remove duplicate rows from joined table
I have following sql query

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Which provide following result

```<code>School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1
</code>```

My question is how to remove those duplicates and get only following.

```<code> School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1
</code>```

I tried with

```<code>   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School
</code>```

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

答: Using the DISTINCT keyword will make sql use sets instead of multisets. So values only appear once </p>

Title: Remove duplicate rows from joined table

Body:
I have following sql query

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.

 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with

   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."


问:
Hive on S3 multi aws users and Spark
This is my scenario

I am a  spark and aws enthusiast and I am itching to understand more about the technology.

Case 1:  My spark application runs on an EMR cluster and the spark application
read from a hive on s3 table and write into a hive table on s3. In this case , the S3 buckets belong to the same user usera  so I added  fs.s3.awsAccessKeyId  and fs.s3.awsSecretAccessKey to a config file . In my case I added it to the hdfs-site.xml. usera had the right permissions to access the bucket so no problem .

Case 2: I am reading from 2 hive tables on s3.  table1 and table2.
table1 belongs to user1 and table2 belongs to user2.

given that i cannot specify multiple awsAccessKeyId in the config file for s3. [ I understand that s3a has a concept of bucket specific keys but I am not using s3a I am using s3.]

how are these scenarios supported in aws EMR ?

I understand that IAM , EC2  instance role and profile role can apply here

答: I think the solution to your problem is cross-account permissions. Thus, you can define permission for user1 to access user2's bucket. You can also take a look at this too.</p>

Title: Hive on S3 multi aws users and Spark


问:
Chartjs 2.0 - Increase height of x-axis labels
JSBin here: http://jsbin.com/xukuhanota/1/edit?output

I'm trying to increase the height (or essentially, the top/bottom padding) of the labels (ticks?) along the x axis.

Here is the relevant bit of code for the chart:

```<code>xAxes: [{
  id: 'x-axis-0',
  type: 'category',

  gridLines: {
    display: false,
  },

  ticks: {
    fontSize: 16,
    maxRotation: 0,
    fontFamily: "opensans",
    fontStyle: "bold",

    paddingTop: 10,         // doesnt work
    paddingBottom: 10,      // doesnt work
  },

  paddingTop: 10,           // doesnt work
  paddingBottom: 10,        // doesnt work
</code>```

According to documentation, there are paddingBottom and paddingTop properties, but I don't know if/how they apply to the ticks vs scales.

答:
Just for completeness, provide a options Object like this and your axis will have a fixed height, or change some padding values</p>

```<code>var options = {
    scales: {
        xAxes: [{
            afterFit: (scale) => {
                scale.height = 120;
            }
        }]
    }
};
</code>```

Body:
JSBin here: http://jsbin.com/xukuhanota/1/edit?output

I'm trying to increase the height (or essentially, the top/bottom padding) of the labels (ticks?) along the x axis.

Here is the relevant bit of code for the chart:

xAxes: [{
  id: 'x-axis-0',
  type: 'category',

  gridLines: {
    display: false,
  },

  ticks: {
    fontSize: 16,
    maxRotation: 0,
    fontFamily: "opensans",
    fontStyle: "bold",

    paddingTop: 10,         // doesnt work
    paddingBottom: 10,      // doesnt work
  },

  paddingTop: 10,           // doesnt work
  paddingBottom: 10,        // doesnt work

According to documentation, there are paddingBottom and paddingTop properties, but I don't know if/how they apply to the ticks vs scales.

Body:
Just for completeness, provide a options Object like this and your axis will have a fixed height, or change some padding values

var options = {
    scales: {
        xAxes: [{
            afterFit: (scale) => {
                scale.height = 120;
            }
        }]
    }
};


问:
TFRecord larger than the original data
Actually, I am dealing with many pictures which are from different videos, so I use tf.SequenceExample() to save them as different sequences and their labels attached into TFRcord.

But after running my code to generate TFRecord, it generates a TFRecord which is 29GB larger than my original pictures 3GB.

Is that normal to create TFRecord larger than the original data?

答:
Check the the type of data you load. I guess you load images as pixel-data. Every pixel is unit8 (8 bit) and likely to be converted to float (32 bit). Hence you have to expect that it gets 4 times the original size (3 GB -> 12 GB).

Also, the original format might have (better) compression than tfrecords. (I'm not sure if tfrecords can use compression)

Title: TFRecord larger than the original data


问:
Github.com issues with TFS source control, is it possible?
Is it possible to use Github for the issues, TFS for source control, and reference the github issue ids on the TFS checkins?

We use TFS and there's no plan to switch to Git in the near future.
The product owner is out of our network and we can't allow them VPN access so they can't see the issues on TFS.

答:
No, it is not supported to add issues in Github when check in code at TFS. It could only add workitems in TFS.

If they couldn't see those workitem, you could export those workitems from TFS to Excel and send to them. Or like Daniel said in the comment, you could use VSTS instead of using TFS.


问:
Unable to resume Activity when retrieving images from SD card
My Activity contains this code to get all images on the SD card:

```<code>String[] projection = {MediaStore.Images.Media._ID,
                       MediaStore.Images.Media.DATA,
                       MediaStore.Images.ImageColumns.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                             projection, null, null,
                             MediaStore.Images.Media._ID);
int count = cursor.getCount();
int image_path_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
int i;
for(i = 0; i < count; i++) {
    cursor.moveToPosition(i);
    String p = cursor.getString(image_path_index);
    fd.addToPhonePhoto(p);
}
cursor.close();
</code>```

The occurred while the Activity was resuming:

03-14 14:06:48.380: E/AndroidRuntime(20793): java.lang.RuntimeException: Unable to resume activity {}: java.lang.RuntimeException: Unable to resume activity {}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.

It only occurs on Android 4.0. If on Android 2.x or 3.x, it works normally. But if I change the system setting which selects the "don't keep Activities" option in "Developer options".
The error does not show.

I want to modify my code to avoid this error without changing the system setting. How should I do it?

答:
Function, managedQuery() is deprecated.

Please use getContentResolver().query().

The parameters is the same.

Body:
My Activity contains this code to get all images on the SD card:

String[] projection = {MediaStore.Images.Media._ID,
                       MediaStore.Images.Media.DATA,
                       MediaStore.Images.ImageColumns.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                             projection, null, null,
                             MediaStore.Images.Media._ID);
int count = cursor.getCount();
int image_path_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
int i;
for(i = 0; i < count; i++) {
    cursor.moveToPosition(i);
    String p = cursor.getString(image_path_index);
    fd.addToPhonePhoto(p);
}
cursor.close();

The occurred while the Activity was resuming:

03-14 14:06:48.380: E/AndroidRuntime(20793): java.lang.RuntimeException: Unable to resume activity {}: java.lang.RuntimeException: Unable to resume activity {}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.

It only occurs on Android 4.0. If on Android 2.x or 3.x, it works normally. But if I change the system setting which selects the "don't keep Activities" option in "Developer options".
The error does not show.

I want to modify my code to avoid this error without changing the system setting. How should I do it?


问:
Import file dynamically in vue js
Below code which works for me

```<code>var Index = require('./theme/dir1/index.vue');
</code>```

But I want to use It like this,

```<code>var path = './theme/'+variable+'/index.vue';
var Index = require(path);
</code>```

Which is not working for me, is there any way to make that fix.,

答:
Try this, it should work:</p>

```<code>var Index = require(`./theme/${variable}/index.vue`);
</code>```

Title: Import file dynamically in vue js

Body:
Below code which works for me

var Index = require('./theme/dir1/index.vue');

But I want to use It like this,

var path = './theme/'+variable+'/index.vue';
var Index = require(path);

Which is not working for me, is there any way to make that fix.,

Body:
Try this, it should work:

var Index = require(`./theme/${variable}/index.vue`);


问:
Qt5: show notification popups
I'm writing an image viewer which allows me to do some actions. As a visual feedback to some actions (like copy/move/delete/..) I'd like to have a decent popup in the middle of my application window which informs about what has been done and which disappears after about a second.

Of course I can just use a Widget and and modify it to fit my needs:

placed in the middle/on top of application window (regardless of layout)

disappears after a given time

no interaction/focus possible - clicking on the notification should be like clicking on what's behind of it

decent style (e.g. transparent and easily readable)

.. I'm just wondering if there's something dedicated for this purpose

(I'm NOT talking about tray notifications which appear near to some task barof the window manager)

答:
It sound like you want to use a QMessageBox. For instance:

```<code>QMessageBox* msgbox = new QMessageBox(this);
msgbox->setWindowTitle("Note");
msgbox->setText("Successfully copied item foobar");
msgbox->open();
</code>```

You might want to change the modality according to your desire and implement a timer  to close the dialog.

```<code>QTimer* timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), msgbox, SLOT(close()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(stop()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
timer->start(1000);
</code>```

Note: Example code, not tested.

Title: Qt5: show notification popups

Body:
It sound like you want to use a QMessageBox. For instance:

QMessageBox* msgbox = new QMessageBox(this);
msgbox->setWindowTitle("Note");
msgbox->setText("Successfully copied item foobar");
msgbox->open();

You might want to change the modality according to your desire and implement a timer  to close the dialog.

QTimer* timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), msgbox, SLOT(close()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(stop()));
QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
timer->start(1000);

Note: Example code, not tested.


问:
Gstreamer: how to get three copies of the same video stream in one window?
I'm trying to reproduce "Fractals without a computer" but with a computer instead of three projectors.
I think it should be quite simple to do with gstreamer: just replicate stream from camera with tee and put three identical pictures on one with videomixer.

Here I'm using 'videotestsrc pattern=1' as a stream which I wish to replicate, and 'videotestsrc pattern="black"' as a background for the whole screen.

```<code>#!/bin/bash
gst-launch -v \
    videotestsrc pattern=1 ! video/x-raw-yuv,width=200,height=200 \
        ! tee name=t \
    videomixer name=mix \
          sink_0::xpos=0   sink_0::ypos=0 \
          sink_1::xpos=100 sink_1::ypos=0 \
          sink_2::xpos=200 sink_2::ypos=200 \
          sink_3::xpos=0   sink_3::ypos=200 \
        ! ffmpegcolorspace ! xvimagesink \
    videotestsrc pattern="black" ! video/x-raw-yuv,width=400,height=400 \
        ! mix.sink_0 \
    t. ! queue ! mix.sink_1 \
    t. ! queue ! mix.sink_2 \
    t. ! queue ! mix.sink_3 \
</code>```

The problem is that I get only two copies: the one corresponding to sink_1 and the other -- to sink_2.
If I swap last two lines then I get only sink_1 and sink_3.

So the question is how to show all three copies?

答: Yoa! adding sink_i::zorder=i for each i=0..3 solves the problem.</p>

Body:
I'm trying to reproduce "Fractals without a computer" but with a computer instead of three projectors.
I think it should be quite simple to do with gstreamer: just replicate stream from camera with tee and put three identical pictures on one with videomixer.

Here I'm using 'videotestsrc pattern=1' as a stream which I wish to replicate, and 'videotestsrc pattern="black"' as a background for the whole screen.

#!/bin/bash
gst-launch -v \
    videotestsrc pattern=1 ! video/x-raw-yuv,width=200,height=200 \
        ! tee name=t \
    videomixer name=mix \
          sink_0::xpos=0   sink_0::ypos=0 \
          sink_1::xpos=100 sink_1::ypos=0 \
          sink_2::xpos=200 sink_2::ypos=200 \
          sink_3::xpos=0   sink_3::ypos=200 \
        ! ffmpegcolorspace ! xvimagesink \
    videotestsrc pattern="black" ! video/x-raw-yuv,width=400,height=400 \
        ! mix.sink_0 \
    t. ! queue ! mix.sink_1 \
    t. ! queue ! mix.sink_2 \
    t. ! queue ! mix.sink_3 \

The problem is that I get only two copies: the one corresponding to sink_1 and the other -- to sink_2.
If I swap last two lines then I get only sink_1 and sink_3.

So the question is how to show all three copies?


问:
How get parent Range of current Selection in word add-in using JavaScript API
I need to insert a paragraph with ContentControl after the current selection paragraph, suppose the current selection is in middle of any paragraph, table or CC, I need to insert a new paragraph with CC after that.

I have tried below code to get the current selection and set range to end of that then will insert the paragraph after it:

```<code>var range = context.document.getSelection().getRange("end");
range.insertParagraph("","After");
</code>```

but it insert the Paragraph after the current Selection, not after current selection parent.

Please advice. Thanks.

答:
What you are observing is by design. You are getting the range of the selection. What you need to do is to get the range of the paragraph and then add another after.

All ranges have a paragraphs collection, the first paragraph will the the paragraph containing the selection, so you can get tit by calling:

context.document.getSelection().paragraphs.getFirst().getRange().insertParagraph("",after");

the full code sample would look like this:

Word.run(async (context) => {
            var myParagraph = context.document.getSelection().paragraphs.getFirst().getRange().insertParagraph("", "after")
            myParagraph.insertContentControl();
            return context.sync();
        })

    .catch(function (error) {
        console.log(error.message)
    }) ```

Note: if the selection expands more than one paragraph, probably you would need to do a getLast() instead of a getFirst(), but i am not sure your exact scenario.

thanks!

Body:
I need to insert a paragraph with ContentControl after the current selection paragraph, suppose the current selection is in middle of any paragraph, table or CC, I need to insert a new paragraph with CC after that.

I have tried below code to get the current selection and set range to end of that then will insert the paragraph after it:

var range = context.document.getSelection().getRange("end");
range.insertParagraph("","After");

but it insert the Paragraph after the current Selection, not after current selection parent.

Please advice. Thanks.

Body:
What you are observing is by design. You are getting the range of the selection. What you need to do is to get the range of the paragraph and then add another after.

All ranges have a paragraphs collection, the first paragraph will the the paragraph containing the selection, so you can get tit by calling:

context.document.getSelection().paragraphs.getFirst().getRange().insertParagraph("",after");

the full code sample would look like this:

Word.run(async (context) => {
            var myParagraph = context.document.getSelection().paragraphs.getFirst().getRange().insertParagraph("", "after")
            myParagraph.insertContentControl();
            return context.sync();
        })

    .catch(function (error) {
        console.log(error.message)
    })

Note: if the selection expands more than one paragraph, probably you would need to do a getLast() instead of a getFirst(), but i am not sure your exact scenario.

thanks!


问:
How to get the last x lines of a string in Java?
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.

How can get the last x lines of a string in Java?

答:
Here's a simple solution:</p>

```<code>public static List<String> getLastLines(String string, int numLines) {
    List<String> lines = Arrays.asList(string.split("\n"));
    return new ArrayList<>(lines.subList(Math.max(0, lines.size() - numLines), lines.size()));
}
</code>```

Body:
Here's a simple solution:

public static List<String> getLastLines(String string, int numLines) {
    List<String> lines = Arrays.asList(string.split("\n"));
    return new ArrayList<>(lines.subList(Math.max(0, lines.size() - numLines), lines.size()));
}


问:
Making DataFrame in pandas having diffence size of Lists in List
i have data like this

```<code>genre_list
Out[7]:
0                    [Action, Adventure, Fantasy, Sci-Fi]
1                            [Action, Adventure, Fantasy]
2                           [Action, Adventure, Thriller]
3                                      [Action, Thriller]
4                                           [Documentary]
5                             [Action, Adventure, Sci-Fi]
6                            [Action, Adventure, Romance]
7       [Adventure, Animation, Comedy, Family, Fantasy...
8                             [Action, Adventure, Sci-Fi]
9                   [Adventure, Family, Fantasy, Mystery]
10                            [Action, Adventure, Sci-Fi]
11                            [Action, Adventure, Sci-Fi]
</code>```

i coded to make Dataframe with difference size of list

```<code>genre_df = pd.DataFrame()
for i in range(len(genre_list)):
    genre_df = genre_df.append(pd.DataFrame(genre_list[i]).T)
</code>```

get this

```<code>genre_df.head()
Out[9]:
             0          1         2       3    4    5    6    7
0       Action  Adventure   Fantasy  Sci-Fi  NaN  NaN  NaN  NaN
0       Action  Adventure   Fantasy     NaN  NaN  NaN  NaN  NaN
0       Action  Adventure  Thriller     NaN  NaN  NaN  NaN  NaN
0       Action   Thriller       NaN     NaN  NaN  NaN  NaN  NaN
0  Documentary        NaN       NaN     NaN  NaN  NaN  NaN  NaN
</code>```

is there a simple way to get Dataframe ....?

答:
You can use DataFrame constructor with converterd values of genre_list to numpy array by values and then to list:

```<code>df1 = pd.DataFrame(genre_list.values.tolist(), index=genre_list.index)
print (df1)

              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi     None
1        Action  Adventure   Fantasy     None     None
2        Action  Adventure  Thriller     None     None
3        Action   Thriller      None     None     None
4   Documentary       None      None     None     None
5        Action  Adventure    Sci-Fi     None     None
6        Action  Adventure   Romance     None     None
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi     None     None
9     Adventure     Family   Fantasy  Mystery     None
10       Action  Adventure    Sci-Fi     None     None
11       Action  Adventure    Sci-Fi     None     None
</code>```

If need replace None to NaN:

```<code>df1 = pd.DataFrame(genre_list.values.tolist(), index=genre_list.index).replace({None:np.nan})
print (df1)
              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi      NaN
1        Action  Adventure   Fantasy      NaN      NaN
2        Action  Adventure  Thriller      NaN      NaN
3        Action   Thriller       NaN      NaN      NaN
4   Documentary        NaN       NaN      NaN      NaN
5        Action  Adventure    Sci-Fi      NaN      NaN
6        Action  Adventure   Romance      NaN      NaN
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi      NaN      NaN
9     Adventure     Family   Fantasy  Mystery      NaN
10       Action  Adventure    Sci-Fi      NaN      NaN
11       Action  Adventure    Sci-Fi      NaN      NaN
</code>```

Another slowier solution is apply Series:

```<code>df1 = genre_list.apply(pd.Series)
              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi      NaN
1        Action  Adventure   Fantasy      NaN      NaN
2        Action  Adventure  Thriller      NaN      NaN
3        Action   Thriller       NaN      NaN      NaN
4   Documentary        NaN       NaN      NaN      NaN
5        Action  Adventure    Sci-Fi      NaN      NaN
6        Action  Adventure   Romance      NaN      NaN
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi      NaN      NaN
9     Adventure     Family   Fantasy  Mystery      NaN
10       Action  Adventure    Sci-Fi      NaN      NaN
11       Action  Adventure    Sci-Fi      NaN      NaN
</code>```

Timings:

```<code>#[12000 rows]
genre_list = pd.concat([genre_list]*1000).reset_index(drop=True)

In [115]: %timeit pd.DataFrame(genre_list.values.tolist(), index=genre_list.index).replace({None:np.nan})
100 loops, best of 3: 15.7 ms per loop

In [116]: %timeit df1 = genre_list.apply(pd.Series)
1 loop, best of 3: 1.96 s per loop
</code>```

Body:
i have data like this

genre_list
Out[7]:
0                    [Action, Adventure, Fantasy, Sci-Fi]
1                            [Action, Adventure, Fantasy]
2                           [Action, Adventure, Thriller]
3                                      [Action, Thriller]
4                                           [Documentary]
5                             [Action, Adventure, Sci-Fi]
6                            [Action, Adventure, Romance]
7       [Adventure, Animation, Comedy, Family, Fantasy...
8                             [Action, Adventure, Sci-Fi]
9                   [Adventure, Family, Fantasy, Mystery]
10                            [Action, Adventure, Sci-Fi]
11                            [Action, Adventure, Sci-Fi]

i coded to make Dataframe with difference size of list

genre_df = pd.DataFrame()
for i in range(len(genre_list)):
    genre_df = genre_df.append(pd.DataFrame(genre_list[i]).T)

get this

genre_df.head()
Out[9]:
             0          1         2       3    4    5    6    7
0       Action  Adventure   Fantasy  Sci-Fi  NaN  NaN  NaN  NaN
0       Action  Adventure   Fantasy     NaN  NaN  NaN  NaN  NaN
0       Action  Adventure  Thriller     NaN  NaN  NaN  NaN  NaN
0       Action   Thriller       NaN     NaN  NaN  NaN  NaN  NaN
0  Documentary        NaN       NaN     NaN  NaN  NaN  NaN  NaN

is there a simple way to get Dataframe ....?

Body:
You can use DataFrame constructor with converterd values of genre_list to numpy array by values and then to list:

df1 = pd.DataFrame(genre_list.values.tolist(), index=genre_list.index)
print (df1)

              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi     None
1        Action  Adventure   Fantasy     None     None
2        Action  Adventure  Thriller     None     None
3        Action   Thriller      None     None     None
4   Documentary       None      None     None     None
5        Action  Adventure    Sci-Fi     None     None
6        Action  Adventure   Romance     None     None
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi     None     None
9     Adventure     Family   Fantasy  Mystery     None
10       Action  Adventure    Sci-Fi     None     None
11       Action  Adventure    Sci-Fi     None     None

If need replace None to NaN:

df1 = pd.DataFrame(genre_list.values.tolist(), index=genre_list.index).replace({None:np.nan})
print (df1)
              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi      NaN
1        Action  Adventure   Fantasy      NaN      NaN
2        Action  Adventure  Thriller      NaN      NaN
3        Action   Thriller       NaN      NaN      NaN
4   Documentary        NaN       NaN      NaN      NaN
5        Action  Adventure    Sci-Fi      NaN      NaN
6        Action  Adventure   Romance      NaN      NaN
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi      NaN      NaN
9     Adventure     Family   Fantasy  Mystery      NaN
10       Action  Adventure    Sci-Fi      NaN      NaN
11       Action  Adventure    Sci-Fi      NaN      NaN

Another slowier solution is apply Series:

df1 = genre_list.apply(pd.Series)
              0          1         2        3        4
0        Action  Adventure   Fantasy   Sci-Fi      NaN
1        Action  Adventure   Fantasy      NaN      NaN
2        Action  Adventure  Thriller      NaN      NaN
3        Action   Thriller       NaN      NaN      NaN
4   Documentary        NaN       NaN      NaN      NaN
5        Action  Adventure    Sci-Fi      NaN      NaN
6        Action  Adventure   Romance      NaN      NaN
7     Adventure  Animation    Comedy   Family  Fantasy
8        Action  Adventure    Sci-Fi      NaN      NaN
9     Adventure     Family   Fantasy  Mystery      NaN
10       Action  Adventure    Sci-Fi      NaN      NaN
11       Action  Adventure    Sci-Fi      NaN      NaN

Timings:

#[12000 rows]
genre_list = pd.concat([genre_list]*1000).reset_index(drop=True)

In [115]: %timeit pd.DataFrame(genre_list.values.tolist(), index=genre_list.index).replace({None:np.nan})
100 loops, best of 3: 15.7 ms per loop

In [116]: %timeit df1 = genre_list.apply(pd.Series)
1 loop, best of 3: 1.96 s per loop


问:
This version of the application is not configured for billing through Google Play
When I try to run my application with in-app billing I am getting the error: "This version of the application is not configured for billing through Google Play. Check the help center for more information".

I have the billing permission already in the Manifest file and I have a signed .apk uploaded as a draft onto Google Play and I have also installed that same signed apk onto my phone.

Any help on how to solve this issue?

答: Had the same problem, and it was not solved before i read the post from DZDomi. It suddenly occurred to be that there is a setting in the Google Developer Console  that you need to enable. In the "In app purchases" section, there's a line for your product and to the far right there's a status for it. It should be ACTIVE!</p>


问:
Read XML value using TSQL
I would like to retrieve the CUSTOMERNO from this web service response using TSQL. Note that this is the exact xml file I'm getting. Thanks in advance. </p>

```<code> <?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  <CreateCustomerResponse xmlns="http://tempuri.org/">
  <CreateCustomerResult><RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>
 </CreateCustomerResult></CreateCustomerResponse>
 </soap:Body></soap:Envelope>
</code>```

答:
Assuming your XML is read into a xml typed variable this can be done like here:

```<code>DECLARE @xml XML=
N'<RESPONSEINFO>
  <STATUS>
    <TRANSACTIONNO>60878693</TRANSACTIONNO>
    <ERRORNO>1002</ERRORNO>
    <MESSAGE>Success</MESSAGE>
  </STATUS>
  <CUSTOMERNO>9021325146</CUSTOMERNO>
</RESPONSEINFO>';

SELECT @xml.value(N'(/RESPONSEINFO/CUSTOMERNO)[1]',N'bigint')
</code>```

UPDATE Your question changed completely... (avoid chameleons please!)

You must first read the wrapped XML and read from there:

```<code>DECLARE @xml XML=
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <CreateCustomerResponse xmlns="http://tempuri.org/">
      <CreateCustomerResult><RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>
 </CreateCustomerResult>
    </CreateCustomerResponse>
  </soap:Body>
</soap:Envelope>';

SELECT CAST(@xml.value(N'(/*:Envelope/*:Body/*:CreateCustomerResponse/*:CreateCustomerResult/text())[1]',N'nvarchar(max)') AS XML).value(N'(/RESPONSEINFO/CUSTOMERNO)[1]',N'bigint')
</code>```

Title: Read XML value using TSQL

Body:
I would like to retrieve the CUSTOMERNO from this web service response using TSQL. Note that this is the exact xml file I'm getting. Thanks in advance.

 <?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  <CreateCustomerResponse xmlns="http://tempuri.org/">
  <CreateCustomerResult><RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>
 </CreateCustomerResult></CreateCustomerResponse>
 </soap:Body></soap:Envelope>

Body:
Assuming your XML is read into a xml typed variable this can be done like here:

DECLARE @xml XML=
N'<RESPONSEINFO>
  <STATUS>
    <TRANSACTIONNO>60878693</TRANSACTIONNO>
    <ERRORNO>1002</ERRORNO>
    <MESSAGE>Success</MESSAGE>
  </STATUS>
  <CUSTOMERNO>9021325146</CUSTOMERNO>
</RESPONSEINFO>';

SELECT @xml.value(N'(/RESPONSEINFO/CUSTOMERNO)[1]',N'bigint')

UPDATE Your question changed completely... (avoid chameleons please!)

You must first read the wrapped XML and read from there:

DECLARE @xml XML=
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <CreateCustomerResponse xmlns="http://tempuri.org/">
      <CreateCustomerResult>&lt;RESPONSEINFO&gt;&lt;STATUS&gt;&lt;TRANSACTIONNO&gt;60878693&lt;/TRANSACTIONNO&gt;&lt;ERRORNO&gt;1002&lt;/ERRORNO&gt;&lt;MESSAGE&gt;Success&lt;/MESSAGE&gt;&lt;/STATUS&gt;&lt;CUSTOMERNO&gt;9021325146&lt;/CUSTOMERNO&gt;&lt;/RESPONSEINFO&gt;
 </CreateCustomerResult>
    </CreateCustomerResponse>
  </soap:Body>
</soap:Envelope>';

SELECT CAST(@xml.value(N'(/*:Envelope/*:Body/*:CreateCustomerResponse/*:CreateCustomerResult/text())[1]',N'nvarchar(max)') AS XML).value(N'(/RESPONSEINFO/CUSTOMERNO)[1]',N'bigint')


问:
ODAC11 Oracle 9
We have a problem using ODAC11 (client) and Oracle databases version 9.0 and 9.1.  It returns error message ORA-604 (something about recursive error on level %).
Has anyone else collided with this problem before?</p>

答: You've got to make sure that the client and server are compatible.  The 11 client won't reliably communicate with a server older than 10.2.0.4.  </p>

Title: ODAC11 Oracle 9


问:
How to get a list of all propriety name of a geoJson?
I have a geoJson file structured this way:

```<code>"type":"Feature",
         "id":"AFG",
         "properties":{
            "name":"Afghanistan"
         },
         "geometry":{
            "type":"Polygon",
            "coordinates":[
               [
                  [
                     61.210817,
                     35.650072
</code>```

It's the whole world and I need to grab all the country names and have them as a list the following in order to be able to use them for the autocomplete:

```<code>var availableTags = [
"Afghanistan",
"Angola",
"Albania",
"United Arab Emirates",
    "Angola",
    "Albania",
    "United Arab Emirates",
    ....
</code>```

How would I grab the country names as a list based on the geoJson object?

答:
```<code>var a = <YOUR GEOJSON>;
var countries = a.features.map(function (item) {
    return item.properties.name;
})
</code>```

Body:
I have a geoJson file structured this way:

"type":"Feature",
         "id":"AFG",
         "properties":{
            "name":"Afghanistan"
         },
         "geometry":{
            "type":"Polygon",
            "coordinates":[
               [
                  [
                     61.210817,
                     35.650072

It's the whole world and I need to grab all the country names and have them as a list the following in order to be able to use them for the autocomplete:

var availableTags = [
"Afghanistan",
"Angola",
"Albania",
"United Arab Emirates",
    "Angola",
    "Albania",
    "United Arab Emirates",
    ....

How would I grab the country names as a list based on the geoJson object?


问:
Can we use 'limit' in update query on MongoDB?
I am trying to update my mongodb collection using limit(), But it's not working,is there any other way to apply limit on update query?</p>

答:
You can't use limit with update query...It will give

.update(...).limit is not a function

this error. Because update doesn't return cursor and limit is a cursor function...


问:
How to use FIND_IN_SET() query in codeigniter
I have two tables- One with attendance details and another one with student detail. The following are the table structures:

tbl_attendance

aid             date                     attendance

1           2017-03-09            5,6,9

 2            2017-04-06          12,6,10

  tbl_students

student_id          name

5                               John

6                   Bryan

9                   Anna

10                 Mathew

12                 Susan

Now, I want to display the names of the absentees in the view  as something like say. for example:

Date                 Absentees

2017-03-09   John, Bryan, Anna

2017-03-06   Susan, Bryan, Mathew

I was trying to do it with FIND_IN_SET()..but it seems bad luck..Is there a better way to sort this out?

UPDATE

I used this query instead and it echoed only the first id's name in each row...

```<code>    $query = $this->db
   ->select("tbl_attendance.*,tbl_students.name")
   ->from("tbl_attendance")
   ->join("tbl_students","tbl_students.student_id=tbl_attendance.attendance")
   ->where('FIND_IN_SET(tbl_students.student_id, tbl_attendance.attendance)')
   ->GROUP_BY('tbl_students.student_id')
   ->get()->result_array();
</code>```

But as there are three numbers separated by commas in each row I want the rest to be echoed as well.

答:
You can try query like this,

```<code>SELECT a.`date`,group_concat(s.student_name)
FROM tbl_attendance a,tbl_students s
WHERE FIND_IN_SET(s.st_id, a.attendance) group by `date`;
</code>```

Description :

FIND_IN_SET that allows you to find the position of a string within a comma-separated list of strings.

Syntax:

```<code>FIND_IN_SET(needle,haystack);
</code>```

Hope this will solve your problem.

Body:
I have two tables- One with attendance details and another one with student detail. The following are the table structures:

tbl_attendance

aid             date                     attendance

1           2017-03-09            5,6,9

 2            2017-04-06          12,6,10

  tbl_students

student_id          name

5                               John

6                   Bryan

9                   Anna

10                 Mathew

12                 Susan

Now, I want to display the names of the absentees in the view  as something like say. for example:

Date                 Absentees

2017-03-09   John, Bryan, Anna

2017-03-06   Susan, Bryan, Mathew

I was trying to do it with FIND_IN_SET()..but it seems bad luck..Is there a better way to sort this out?

UPDATE

I used this query instead and it echoed only the first id's name in each row...

    $query = $this->db
   ->select("tbl_attendance.*,tbl_students.name")
   ->from("tbl_attendance")
   ->join("tbl_students","tbl_students.student_id=tbl_attendance.attendance")
   ->where('FIND_IN_SET(tbl_students.student_id, tbl_attendance.attendance)')
   ->GROUP_BY('tbl_students.student_id')
   ->get()->result_array();

But as there are three numbers separated by commas in each row I want the rest to be echoed as well.

Body:
You can try query like this,

SELECT a.`date`,group_concat(s.student_name)
FROM tbl_attendance a,tbl_students s
WHERE FIND_IN_SET(s.st_id, a.attendance) group by `date`;

Description :

FIND_IN_SET that allows you to find the position of a string within a comma-separated list of strings.

Syntax:

FIND_IN_SET(needle,haystack);

Hope this will solve your problem.


答:
Here it is :

```<code>geoJson = //your geoJson Obj;
var countries = [];
for(var k in geoJson.features) {
    countries.push(geoJson.features[k].properties.name);
}
console.log(countries);
</code>```

Use countries as array for your autoComplete.

Title: How to get a list of all propriety name of a geoJson?

Body:
Here it is :

geoJson = //your geoJson Obj;
var countries = [];
for(var k in geoJson.features) {
    countries.push(geoJson.features[k].properties.name);
}
console.log(countries);

Use countries as array for your autoComplete.


问:
5.1 Crash - A TaskDescription's primary color should be opaque
I have implemented material design into my app and it runs perfectly fine on < Android 5 but when I try to run on Android 5.0 and above I get the following in my logcat.

```<code>     FATAL EXCEPTION main
 Process com.test.test, PID 3195
 java.lang.RuntimeException Unable to start activity ComponentInfo{com.test.test/com.test.test.MainActivity} java.lang.RuntimeException A TaskDescription's primary color should be opaque
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2360)
    at android.app.ActivityThread.access$800(ActivityThread.java144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java1278)
    at android.os.Handler.dispatchMessage(Handler.java102)
    at android.os.Looper.loop(Looper.java135)
    at android.app.ActivityThread.main(ActivityThread.java5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java694)
 Caused by java.lang.RuntimeException A TaskDescription's primary color should be opaque
    at android.app.ActivityManager$TaskDescription.<init>(ActivityManager.java536)
    at android.app.Activity.onApplyThemeResource(Activity.java3677)
    at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java140)
    at android.view.ContextThemeWrapper.setTheme(ContextThemeWrapper.java85)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2244)
    ... 10 more
</code>```

And here is my styles:

```<code>    <resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

    -->

    <!-- All customizations that are NOT specific to a particular API-level can go here. -->

    <style name="AppTheme" parent="@style/Theme.AppCompat.NoActionBar">

        <!-- All customizations that are NOT specific to a particular API-level can go here. -->

        <item name="colorPrimaryDark">#4DFF9800</item>
        <item name="colorPrimary">#4D607D8B</item>
    </style>

</resources>
</code>```

If anyone could give me some guidance that would be great thanks.

答:
Simple solution to the issue is to remove the opaque applied to the primary color in colors.xml

When opaque is applied to primary color the color code look like this "#aca688ff", where it has to be ex: "#F50057" (6 letters alphanumeric code without opaque).

Hope the above solution helps you to fix the issue.

Body:
I have implemented material design into my app and it runs perfectly fine on < Android 5 but when I try to run on Android 5.0 and above I get the following in my logcat.

     FATAL EXCEPTION main
 Process com.test.test, PID 3195
 java.lang.RuntimeException Unable to start activity ComponentInfo{com.test.test/com.test.test.MainActivity} java.lang.RuntimeException A TaskDescription's primary color should be opaque
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2360)
    at android.app.ActivityThread.access$800(ActivityThread.java144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java1278)
    at android.os.Handler.dispatchMessage(Handler.java102)
    at android.os.Looper.loop(Looper.java135)
    at android.app.ActivityThread.main(ActivityThread.java5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java694)
 Caused by java.lang.RuntimeException A TaskDescription's primary color should be opaque
    at android.app.ActivityManager$TaskDescription.<init>(ActivityManager.java536)
    at android.app.Activity.onApplyThemeResource(Activity.java3677)
    at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java140)
    at android.view.ContextThemeWrapper.setTheme(ContextThemeWrapper.java85)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2244)
    ... 10 more

And here is my styles:

    <resources>

</resources>

If anyone could give me some guidance that would be great thanks.


问:
Changing connection string for different Users
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

```<code> <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

Connection String 2 :-

```<code><add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</code>```

ApplicationDbContext :-

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}
</code>```

Use :-

```<code> using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }
</code>```

Can anyone suggest how to do this?

答:
You can do something like

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
        public ApplicationDbContext(string connection)
            : base(connection)
        {
            ...
        }
</code>```

}

and to create DbContext object

```<code>var connection = GetDbConnectionByUser(string user);
using (var ctx = new ApplicationDbContext(connection))
{
    ....
}
</code>```

and whatever logic suitable to your structure for differentiating connection string by user

```<code>public string GetDbConnectionByUser(string user)
{

}
</code>```

If you can spend some more time to improve, see the Multi-Tenant Data Architecture

Body:
My application used Code first approach & Entity Framework 6.0.

My requirement is that when a User A logs in connection string AppSchema should be used for whole application & when User B logs in connection string AppSchema1 should be used. My application is very big, i want to achieve this from a central location.

Below is the code :-

Connection String :-

 <add name="AppSchema" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

Connection String 2 :-

<add name="AppSchema1" connectionString="Data Source=Server1\MSSQLSERVER2014;Initial Catalog=MSchema;Integrated Security=True;Persist Security Info=True;" providerName="System.Data.SqlClient" />

ApplicationDbContext :-

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
     public ApplicationDbContext(string schemaname)
                : base("AppSchema")
            {
                SchemaName = schemaname;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
            }
}

Use :-

 using (var ctx = new ApplicationDbContext(schemaName))
    {
        ....
        ctx.tblEmployee.Add(mod);
    }

Can anyone suggest how to do this?

Body:
You can do something like

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbModelCacheKeyProvider, IDisposable
{
        public ApplicationDbContext(string connection)
            : base(connection)
        {
            ...
        }

}

and to create DbContext object

var connection = GetDbConnectionByUser(string user);
using (var ctx = new ApplicationDbContext(connection))
{
    ....
}

and whatever logic suitable to your structure for differentiating connection string by user

public string GetDbConnectionByUser(string user)
{

}

If you can spend some more time to improve, see the Multi-Tenant Data Architecture


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答: I deleted the watch-related targets, and uploaded successfully.</p>


问:
Context popup hiding after Ajax postback
I am using this jQuery context popup menu extension:
http://www.trendskitchens.co.nz/jquery/contextmenu/

This context menu is bound against an ASP.NET treeview adding a context menu to all items.

All contained within an update panel.

In order to select the item when right clicking, I am using JQuery to parse the postback from HREF that would normally fire when the tree item is being clicked, and using eval() against this HREF. This results in a post-back to IIS. Immediately after is my JQuery code for displaying the context menu. The context menu appears briefly however goes as soon as IIS returns the updated page data.

Just after some general advice on how people think is best to approach this. I can avoid this by making users LEFT click the tree node prior to right clicking it, but that just seems unintuitive.

答:
Hey Sam, as far as I see it the whole idea is kind of wrong from the start, I am a .Net developer but I've always avoided introducing an update panel in my applications, if you look behind the curtains you will see that update panels insert a form tag within the application which kind'a runs at server, try to insert two forms with runat server attribute one within the other in a VS see what they say :). To be honest it's fairly easy to build a contextual menu with templates as layout; it's about 3 hour work and several others for testing.
   Getting back to your issue. I see that you have two options here: either learn how to open the menu from javascript and retain the position inside a hidden field before postback(on click/open) and after the postback occurs reopen the menu at the desired position/components, either search for the code which actually does the post back and prevent it in your case. Could be a click and if so all you need is an ev.preventDefault(), could be a submit and then you would need to set up a variable and on submit return false or something like that. Can't really give you the actual code solution without seeing the page which has this "bad" behaviour, anyhow left clicking is, as you said, not intuitive and frankly not an option in this case.</p>


问:
how can we broadcast live video from android with http
I have tried using libstreaming library and succeed to live stream using rtsp and played in vlc player but i am not able to use http for streaming so that i can broadcast my video streaming to my own server,Is there any way to do that ?

I have a requirement to broadcast live video from android app and that can also be viewed from another android devices.

答:
I think you getting it in a wrong way, you don't broadcast to server you send (upload) and server broadcast that for you. broadcasting is sending same data to all connected client at the same time. clients don't broadcast data for the server. also you can setup a http-server on your android but since you have a separate server already I don't think that would be what you want.

so if it's java with UDP case then start would be something like this:

```<code>UDPServer.java:
import java.io.*;
import java.net.*;

class UDPServer
{
    public static void main(String args[]) throws Exception
    {
        DatagramSocket serverSocket = new DatagramSocket(PORT);
        byte[] receiveData = new byte[FRAMESIZE];
        while(true)
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            // IP and port of the client who sent you this
            // in case of some type of feedback since UDP doesn't do that
            //InetAddress IPAddress = receivePacket.getAddress();
            //int port = receivePacket.getPort();

            // store data somewhere sharable lock it before store it
        }
    }
}

UDPClient.java:
import java.io.*;
import java.net.*;

class UDPClient
{
    public static void main(String args[]) throws Exception
    {
        BufferedReader inFromUser =
        new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[FRAMESIZE];
        /* WebCam Frame Capture Code*/
        // but you should do it continuously on your frame capture event
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, PORT);
        clientSocket.send(sendPacket);

        clientSocket.close();
    }
}
</code>```

here some references:

http://android-er.blogspot.com/2016/05/android-datagramudp-client-example.html
http://www.helloandroid.com/tutorials/simple-udp-communication-example
https://www.digi.com/wiki/developer/index.php/Android_UDP_Client

http://www.androidhive.info/2014/06/android-streaming-live-camera-video-to-web-page/

and by some modifications I think this is what you want :

http://code.google.com/p/spydroid-ipcamera/

Body:
I think you getting it in a wrong way, you don't broadcast to server you send (upload) and server broadcast that for you. broadcasting is sending same data to all connected client at the same time. clients don't broadcast data for the server. also you can setup a http-server on your android but since you have a separate server already I don't think that would be what you want.

so if it's java with UDP case then start would be something like this:

UDPServer.java:
import java.io.*;
import java.net.*;

class UDPServer
{
    public static void main(String args[]) throws Exception
    {
        DatagramSocket serverSocket = new DatagramSocket(PORT);
        byte[] receiveData = new byte[FRAMESIZE];
        while(true)
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            // IP and port of the client who sent you this
            // in case of some type of feedback since UDP doesn't do that
            //InetAddress IPAddress = receivePacket.getAddress();
            //int port = receivePacket.getPort();

            // store data somewhere sharable lock it before store it
        }
    }
}

UDPClient.java:
import java.io.*;
import java.net.*;

class UDPClient
{
    public static void main(String args[]) throws Exception
    {
        BufferedReader inFromUser =
        new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[FRAMESIZE];
        /* WebCam Frame Capture Code*/
        // but you should do it continuously on your frame capture event
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, PORT);
        clientSocket.send(sendPacket);

        clientSocket.close();
    }
}

here some references:

http://android-er.blogspot.com/2016/05/android-datagramudp-client-example.html
http://www.helloandroid.com/tutorials/simple-udp-communication-example
https://www.digi.com/wiki/developer/index.php/Android_UDP_Client

http://www.androidhive.info/2014/06/android-streaming-live-camera-video-to-web-page/

and by some modifications I think this is what you want :

http://code.google.com/p/spydroid-ipcamera/


问:
CNTK: Define a custom loss function (Sørensen-Dice coefficient)
I'd like to use Wiki: Sørensen–Dice coefficient as a loss function in CNTK/Python. How can I define a custom loss function.</p>

答:
To answer your more general question "How can I define a custom loss function:"

In CNTK, loss functions are not special. Any expression that results in a scalar can be used as a loss function. The learner will compute the minibatch-level loss by summing up the scalar loss values of all samples in the minibatch, and backpropagate through it like through any CNTK expression.

For example, the following is a way of defining a square-error loss:

```<code>def my_square_error(x,y):
    diff = x-y
    return times_transpose(diff, diff)
</code>```

and the cross_entropy_with_softmax() loss can be written in Python like this:

```<code>def my_cross_entropy_with_softmax(output, labels):
    logZ = reduce_log_sum(output)  # log of softmax denominator
    return times_transpose(labels, output) - logZ
</code>```

Lastly, multi-task learning can be trivially realized by using a loss function that is a weighted sum over multiple losses.

Body:
To answer your more general question "How can I define a custom loss function:"

In CNTK, loss functions are not special. Any expression that results in a scalar can be used as a loss function. The learner will compute the minibatch-level loss by summing up the scalar loss values of all samples in the minibatch, and backpropagate through it like through any CNTK expression.

For example, the following is a way of defining a square-error loss:

def my_square_error(x,y):
    diff = x-y
    return times_transpose(diff, diff)

and the cross_entropy_with_softmax() loss can be written in Python like this:

def my_cross_entropy_with_softmax(output, labels):
    logZ = reduce_log_sum(output)  # log of softmax denominator
    return times_transpose(labels, output) - logZ

Lastly, multi-task learning can be trivially realized by using a loss function that is a weighted sum over multiple losses.