问:
how to show dialog only once
Hi i'm trying to create dialog contains two buttons [ GOT IT ! ] and [ DON'T SHOW ME THIS AGAIN ] i want when i click [ DON'T SHOW ME THIS AGAIN ] button dialog Completely closed And do not show again at application Reopen

```<code>public boolean Show = false;

public void IntroSupport(){

    Show = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Some text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me this Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                    break;
                case 1:

                    if(Show == false){
                        IntroSupport();
                    }

                    getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                    break;
            }
        }
</code>```

答:
Use SharedPreference for showing dialog or not. Try this code:

```<code>public boolean Show = false;

public void IntroSupport(){
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Somme text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences.Editor editor = getSharedPreferences("mypref", MODE_PRIVATE).edit();
                     editor.putBoolean("dontshow", true);
                     editor.commit();
                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                break;
            case 1:
                SharedPreferences prefs = getSharedPreferences("mypref", MODE_PRIVATE);
                show = prefs.getBoolean("dontshow", false);
                if(Show == false){
                    IntroSupport();
                }

                getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                break;
        }
    }
</code>```

Title: how to show dialog only once

Body:
Hi i'm trying to create dialog contains two buttons [ GOT IT ! ] and [ DON'T SHOW ME THIS AGAIN ] i want when i click [ DON'T SHOW ME THIS AGAIN ] button dialog Completely closed And do not show again at application Reopen

public boolean Show = false;

public void IntroSupport(){

    Show = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Some text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me this Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                    break;
                case 1:

                    if(Show == false){
                        IntroSupport();
                    }

                    getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                    break;
            }
        }

Body:
Use SharedPreference for showing dialog or not. Try this code:

public boolean Show = false;

public void IntroSupport(){
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Somme text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences.Editor editor = getSharedPreferences("mypref", MODE_PRIVATE).edit();
                     editor.putBoolean("dontshow", true);
                     editor.commit();
                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                break;
            case 1:
                SharedPreferences prefs = getSharedPreferences("mypref", MODE_PRIVATE);
                show = prefs.getBoolean("dontshow", false);
                if(Show == false){
                    IntroSupport();
                }

                getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                break;
        }
    }


来源: stackexchange

问:
Property or indexer 'string.this[int]' cannot be assigned to -- it's read only
I didn't get the problem - I was trying to do a simple action:

```<code>for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
    backx[j] = x[i];
}
</code>```

Both are declared:

```<code>String x;
String backx;
</code>```

What is the problem ? It says the error in the title...
If there is a problem - is there another way to do that?
The result (As the name 'backx' hints) is that backx will contain the string X backwards.
P.S. x is not empty - it contains a substring from another string.

答:
The code below simply swaps the index of each char in the string which enables you to only have to iterate half way through the original string which is pretty efficient if you're dealing with a lot of characters. The result is the original string reversed. I tested this with a string consisting of 100 characters and it executed in 0.0000021 seconds.</p>

```<code>private string ReverseString(string testString)
    {

        int j = testString.Length - 1;
        char[] charArray = new char[testString.Length];

        for (int i = 0; i <= j; i++)
        {

            if (i != j)
            {
                charArray[i] = testString[j];
                charArray[j] = testString[i];
            }

            j--;
        }

        return new string(charArray);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I didn't get the problem - I was trying to do a simple action:

for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
    backx[j] = x[i];
}

Both are declared:

String x;
String backx;

What is the problem ? It says the error in the title...
If there is a problem - is there another way to do that?
The result (As the name 'backx' hints) is that backx will contain the string X backwards.
P.S. x is not empty - it contains a substring from another string.

Body:
The code below simply swaps the index of each char in the string which enables you to only have to iterate half way through the original string which is pretty efficient if you're dealing with a lot of characters. The result is the original string reversed. I tested this with a string consisting of 100 characters and it executed in 0.0000021 seconds.

private string ReverseString(string testString)
    {

        int j = testString.Length - 1;
        char[] charArray = new char[testString.Length];

        for (int i = 0; i <= j; i++)
        {

            if (i != j)
            {
                charArray[i] = testString[j];
                charArray[j] = testString[i];
            }

            j--;
        }

        return new string(charArray);
    }


问:
How redirect apache2 to jboss web service and consume with php
I'm trying to redirect a web service from apache2 to jboss, and later consume this with php.

I succes can redirect request, and see the wsdl in the browser, but when I call with php:

```<code>$server = new SoapServer('http://subdomain.midomain.com/FirmaElectronica/WebService?wsdl');

var_dump($server);
// Returns:
// object(SoapServer)[1]
// public 'service' => resource(1, Unknown)

var_dump($server->__getFunctions());
// Error, Call to undefined method

$salida = $server->hello('mat');
// Error, Call to undefined method
</code>```

My apache conf:

```<code><VirtualHost *:80>
ServerName subdomain.midomain.com
ServerAlias midomain.com
# ProxyRequests On
# ProxyVia On
ProxyPass "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
ProxyPassReverse "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
</VirtualHost>
</code>```

Also tried:

```<code><VirtualHost *:80>
ServerName subdomain.midomain.com
ServerAlias midomain.com
ProxyRequests On
ProxyVia On
ProxyPass "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
ProxyPassReverse "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
</VirtualHost>
</code>```

And a few more different configuration for apache, in every case I can see wsdl in browser, but when a do a php call, everything brokes.

Any idea?

答: I solved, the problem was use SoapCliente and a bad configuration in web service url in windfly with jboss</p>

Body:
I'm trying to redirect a web service from apache2 to jboss, and later consume this with php.

I succes can redirect request, and see the wsdl in the browser, but when I call with php:

$server = new SoapServer('http://subdomain.midomain.com/FirmaElectronica/WebService?wsdl');

var_dump($server);
// Returns:
// object(SoapServer)[1]
// public 'service' => resource(1, Unknown)

var_dump($server->__getFunctions());
// Error, Call to undefined method

$salida = $server->hello('mat');
// Error, Call to undefined method

My apache conf:

<VirtualHost *:80>
ServerName subdomain.midomain.com
ServerAlias midomain.com
# ProxyRequests On
# ProxyVia On
ProxyPass "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
ProxyPassReverse "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
</VirtualHost>

Also tried:

<VirtualHost *:80>
ServerName subdomain.midomain.com
ServerAlias midomain.com
ProxyRequests On
ProxyVia On
ProxyPass "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
ProxyPassReverse "/FirmaElectronica" "http://10.128.0.2:8080/FirmaElectronica"
</VirtualHost>

And a few more different configuration for apache, in every case I can see wsdl in browser, but when a do a php call, everything brokes.

Any idea?


问:
Using __set with arrays solved, but why?
Having done a bit of research, I eventually came across the answer to a question I was soon to ask here anyways; How do you work with arrays via the __get and __set magic methods in PHP? Whenever I was trying to set a value using something like $object->foo['bar'] = 42; it seemed to silently discard it.

Anyways, the answer is simple; The __get method simply needs to return by reference. And after tossing an ampersand in front of it, sure enough it works.

My question actually, is why? I can't seem to understand why this is working. How does __get returning by reference affect __set working with multidimensional arrays?

Edit: By the way, running PHP 5.3.1

答: In PHP when you return a value from a function you can consider it making a copy of that value (unless it's a class). In the case of __get unless you return the actual thing you want to edit, all the changes are made to a copy which is then discarded.

ContentLicense: CC BY-SA 2.5


问:
Vue syntax error
I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

```<code>  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });
</code>```

HTML

```<code><div id="qa-suggest">
    <ul class="list-unstyled">
        <li v-for="profile in profiles">
          <div class="clearfix" style="border-bottom: 1px solid #ddd; padding: 5px;">
        <div class="pull-left">
          <img :src="profile.picture" class="img-responsive" style="max-width: 60px; margin-right: 10px;">
        </div>
        <div class="pull-left">
          <p style="font-size: 12px; margin-bottom: 0;">{{ profile.category }} / {{ profile.subcategory }}</p>
          <p><strong>{{ profile.name }}</strong></p>
        </div>
      </div>
    </li>
</ul>

Topic: {{ selectedTopic.name }}
</code>```

答:
You'll get the same kind of error if that were put into a computed property. Vue just executes the JS code as-is without any kind of null-protection.

In your case, I would protect that part of the template with a v-if="selectedTopic", or just use null checking directly in the interpolation: {{ selectedTopic ? selectedTopic.name : 'No topic selected' }}.

You could also initialize it to a default value, like an empty object {}, but in my opinion this is flawed because selectedTopic is now non-null but in fact no actual topic is selected, which complicates the code.

Title: Vue syntax error

Body:
I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });

HTML

{{ profile.category }} / {{ profile.subcategory }}

{{ profile.name }}

Topic: {{ selectedTopic.name }}


问:
VSTS website view Git tags
I am using Visual Studio Team Services with a project, using Git for the source control.

I am using the Git command line to tag the last commit with a version number before doing a release, then pushing it to VSTS, as follows:

```<code>git tag -a 1.2.4 -m "Some Message"
git push origin master --tags
</code>```

This appears to complete successfully.

When I go to the "Code" tab on the VSTS website, I can see all of the commits in the branch history, but I cannot see the version tag that I created and pushed.

How can I view these tags on the VSTS website?

答: When selecting a branch, you can choose between "Mine", "All Branches", and "Tags". You want to look at "Tags".

Title: VSTS website view Git tags

Body:
I am using Visual Studio Team Services with a project, using Git for the source control.

I am using the Git command line to tag the last commit with a version number before doing a release, then pushing it to VSTS, as follows:

git tag -a 1.2.4 -m "Some Message"
git push origin master --tags

This appears to complete successfully.

When I go to the "Code" tab on the VSTS website, I can see all of the commits in the branch history, but I cannot see the version tag that I created and pushed.

How can I view these tags on the VSTS website?


问:
After calling alfresco webcsript, Getting HTTP ERROR 504 on production but not on local and DEV
I wrote one Java Backed webscript in alfresco to traverse all documents in one site and check some properties.
But After calling that webcsript on Production, I am Getting HTTP ERROR 504

But Same webscript is working on DEV and Local.
The reason here is there are very less documents on local and DEV. but on production there are huge number of documents present in the site.
SO its taking more time for traverse, and i am not getting my expected result on production.

SO can we increase that time out period, or is there any other way using that i can execute my webscript and get the expected result on production.

Please suggest the possible ways.

Thanks in Advance.

答:
You must provide code if you want anything more specific than general suggestions. As Muralidharan Deenathayalan said, you should try paging in your controller.

You might also want to try using an entirely different approach. For something like this you probably don't really need a web script. If you are just checking properties, why not use OpenCMIS instead? It's still Java, it has paging support, and you can use it to hit the server remotely.


问:
Copy a Template each time and replace using Excel Macro
I have the following data set in my sheet 1

And this template in sheet 3

I wish to

Copy the template from sheet 3 to sheet2

Read the city and name from row 1 in sheet1

Replace the City and Name in sheet 2

Repeat it for every row in sheet 1

So my ideal output will be:

As you can see because we have three rows in sheet 1 the template is copied three times.

I tried this code, but it doesn't go to loop for 'sheet1'

```<code>Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim ii As Long

Set copySheet = Worksheets("Sheet3")
Set pasteSheet = Worksheets("Sheet2")

For ii = 1 To 10
 copySheet.Range("A1:E3").Copy
 pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
 Application.CutCopyMode = False
 Application.ScreenUpdating = True

Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 3

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

   Next i

Next ii

 End Sub
</code>```

Any guidance is really appreciated.

答:
Try this:

```<code>Private Sub CommandButton1_Click()
Dim rng1() As Variant, rng2 As Range, rng3() As Variant,k&
With Worksheets("Sheet1")
    rng1 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 2).End(xlUp)).Value
End With
With Worksheets("Sheet3")
    rng3 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 2).End(xlUp)).Value
End With
With Worksheets("Sheet2")
    For k = LBound(rng1, 1) To UBound(rng1, 1)
        Set rng2 = .Range("A1").Offset(UBound(rng3, 1) * (k - 1)).Resize(UBound(rng3, 1), UBound(rng3, 2))
        With rng2
            .Value = rng3
            .Replace "City", rng1(k, 2)
            .Replace "Name", rng1(k, 1)
        End With
    Next k
End With
End Sub
</code>```

Inputs:

Sheet1:

Sheet3:

Output:

Sheet2:

Body:
I have the following data set in my sheet 1

And this template in sheet 3

I wish to

Copy the template from sheet 3 to sheet2

Read the city and name from row 1 in sheet1

Replace the City and Name in sheet 2

Repeat it for every row in sheet 1

So my ideal output will be:

As you can see because we have three rows in sheet 1 the template is copied three times.

I tried this code, but it doesn't go to loop for 'sheet1'

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim ii As Long

Set copySheet = Worksheets("Sheet3")
Set pasteSheet = Worksheets("Sheet2")

For ii = 1 To 10
 copySheet.Range("A1:E3").Copy
 pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
 Application.CutCopyMode = False
 Application.ScreenUpdating = True

Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 3

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

   Next i

Next ii

 End Sub

Any guidance is really appreciated.

Body:
Try this:

Private Sub CommandButton1_Click()
Dim rng1() As Variant, rng2 As Range, rng3() As Variant,k&
With Worksheets("Sheet1")
    rng1 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 2).End(xlUp)).Value
End With
With Worksheets("Sheet3")
    rng3 = .Range(.Cells(1, 1), .Cells(.Rows.Count, 2).End(xlUp)).Value
End With
With Worksheets("Sheet2")
    For k = LBound(rng1, 1) To UBound(rng1, 1)
        Set rng2 = .Range("A1").Offset(UBound(rng3, 1) * (k - 1)).Resize(UBound(rng3, 1), UBound(rng3, 2))
        With rng2
            .Value = rng3
            .Replace "City", rng1(k, 2)
            .Replace "Name", rng1(k, 1)
        End With
    Next k
End With
End Sub

Inputs:

Sheet1:

Sheet3:

Output:

Sheet2:


问:
Multi-touch cross platform java application (Windows, Mac, and Linux(Ubuntu)(possibly Android))
Am trying to add multi-touch to an existing cross platform java project. I have looked in to 2 ways. There was several other ways but they seemed to not be cross platform or needed special software.

JavaFx - Working gesturing/touchevent events on windows and osx but not functioning on Ubuntu 16.04.

MT4J - Looks to be discontinued and/or unsupported.

My conclusions for the above could be wrong and am willing to try them again given good feedback.

Is there anyway to achieving a cross platform multi-touch java application? Seems I may need to write some native code and add it through the JNI which seems like a lot of work. Any ideas on this line of thought?. Feed back is appreciated, Thanks.

Continuation 1.0:

I have kept investigating using JavaFX on linux mostly because the only drawback right now for using JavaFX is linux multitouch support. What I have found out is that JavaFx multitouch does work on Linux distributions that are for embedded systems(ex: Raspberry Pi, probably most to be honest). What I can gather from this is if OpenJFX can be compiled for the embedded system then the embedded version of OpenJFX uses the device drivers directly to get input(/dev/input/) instead of the X11/GTK. Since the Linux dists for the desktop use X11/GTK for there input into the desktop environment JavaFx is unable to get these events due to a lack of support.

I don't wish to use a link but here it is

https://wiki.openjdk.java.net/display/OpenJFX/Building+the+OpenJFX+embedded+stack+for+Linux+desktop

The above link, seems to me at-least, to be about compiling a version of the OpenJFX for x86 systems(should work x64) which uses the embedded systems way of getting device input. I'am able to compile this version but when I run it appears to crash the Desktop and sometimes it does leave the Java App up. When the Java App is left running touch events do work but this end result is just not acceptable because it is unpredictable and seems to crash the desktop manager(Requires a reboot of the desktop after this).

Continuation 1.1:

I looked into using TUIO but none of the sample programs worked. They say you need a TUIO enable device which might be a special standard/protocal my devices don't use. Pretty much just downloaded the TUIO demo and ran it on a touch screen with no luck.

I also thought about attaching xev to my java application window and streaming the results to a file to latter be read by the java application and parsed into java events. This seems pretty hacky and am not sure if it would even work. If someone would lay out the possibility of this working I may try it. But at this point it seems like way to much work.

Continuation 1.2:

Found this https://bugs.openjdk.java.net/browse/JDK-8090954
and thought it was interesting.

Posted the solution below.

答:
The solution was to use TUIO and roll our own Multi-Touch library. The trick was starting the TUIOClient and runing a TUIO server. The TUIOClient listens on a given port and the TUIO server forwards OS events to the port the TUIO client is listening on.

I used the mtdev2tuio server(output bridge) for linux and ran it along side a TUIO client.

Example Flow:

1.) TUIOClient listening on port x

2.) TUIOServer forwarding TUIO events to port x from os events y

Linux:

1.) new TUIOClient(3333)

2.) ./mtdev2tuio /dev/input/event5 osc.udp://127.0.0.1:3333

The solution isn't ideal but it works and should support multi-touch on any device provided there is a TUIO server(Output Bridge) running. Another downside is one needs to capture touches and interpret them into gestures. Also note depending on how it is developed dictates how you use it in different frameworks. Ours will need to be used in Swing/JavaFX.


问:
Identify duplicate values in a list in Python
Is it possible to get which values are duplicates in a list using python?

I have a list of items:

```<code>    mylist = [20, 30, 25, 20]
</code>```

I know the best way of removing the duplicates is set(mylist), but is it possible to know what values are being duplicated? As you can see, in this list the duplicates are the first and last values. [0, 3].

Is it possible to get this result or something similar in python? I'm trying to avoid making a ridiculously big if elif conditional statement.

答:
The following code will fetch you desired results with duplicate items and their index values.</p>

```<code>  for i in set(mylist):
    if mylist.count(i) > 1:
         print(i, mylist.index(i))
</code>```

Body:
Is it possible to get which values are duplicates in a list using python?

I have a list of items:

    mylist = [20, 30, 25, 20]

I know the best way of removing the duplicates is set(mylist), but is it possible to know what values are being duplicated? As you can see, in this list the duplicates are the first and last values. [0, 3].

Is it possible to get this result or something similar in python? I'm trying to avoid making a ridiculously big if elif conditional statement.

Body:
The following code will fetch you desired results with duplicate items and their index values.

  for i in set(mylist):
    if mylist.count(i) > 1:
         print(i, mylist.index(i))


问:
Java-based Config that creates Parameterized Singleton Spring Bean
I have the following list of bean definitions in XML:

```<code><bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on
</code>```

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

```<code>@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}
</code>```

but I can specify the args somewhere? Thanks.

答:
You can use an externalized property file to contain the year and week values for your beans.  An example of properties might look like this...

```<code>version201627.year=2016
version201627.week=27

version201628.year=2016
version201628.week=28
</code>```

Then in your java configuration file, you can do this...

```<code>@Bean
@ConfigurationProperties(prefix="version201627")
public ClientVersionPredicate version201627() {
    return new ClientVersionPredicate();
}

@Bean
@ConfigurationProperties(prefix="version201628")
public ClientVersionPredicate version201628() {
    return new ClientVersionPredicate();
}
</code>```

Body:
I have the following list of bean definitions in XML:

<bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}

but I can specify the args somewhere? Thanks.

Body:
You can use an externalized property file to contain the year and week values for your beans.  An example of properties might look like this...

version201627.year=2016
version201627.week=27

version201628.year=2016
version201628.week=28

Then in your java configuration file, you can do this...

@Bean
@ConfigurationProperties(prefix="version201627")
public ClientVersionPredicate version201627() {
    return new ClientVersionPredicate();
}

@Bean
@ConfigurationProperties(prefix="version201628")
public ClientVersionPredicate version201628() {
    return new ClientVersionPredicate();
}


问:
Does groupby automatically group over all non numeric columns in pandas?
I have a sample of a dataset below (only showing the first couple rows but there are 193 rows):

```<code>country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continent
Afghanistan,0,0,0,0.0,Asia
Albania,89,132,54,4.9,Europe
Algeria,25,0,14,0.7,Africa
Andorra,245,138,312,12.4,Europe
Angola,217,57,45,5.9,Africa
Antigua & Barbuda,102,128,45,4.9,North America
...
</code>```

When I run this: drinks.groupby('continent').head()

I get back a dataframe with 30 rows. But in those 30 rows I still have duplicate names for the continent. For example in the image below you can see that Europe is repeated two times (at rows 1 and 3):

I am not able to understand why I am still having two rows with the same continent when I grouped by continent originally?

In this case is the groupby operation also grouping by the country even though I never specified it in the groupby function? Since I know in SQL you are supposed to use an aggregate function like max, min, sum, etc. But in this case I don't have to pass in an aggregate function and I get the result above.

答:
No!

What is happening is that head is a method on the groupby object and behaves a little differently than pd.DataFrame.head.

What the the groupby version of head does is returns the head of each group.

So we can see this more clearly by passing 1 to the head method and see it return the first row of each subset

```<code>df.groupby('continent').head(1)
</code>```

Body:
I have a sample of a dataset below (only showing the first couple rows but there are 193 rows):

country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continent
Afghanistan,0,0,0,0.0,Asia
Albania,89,132,54,4.9,Europe
Algeria,25,0,14,0.7,Africa
Andorra,245,138,312,12.4,Europe
Angola,217,57,45,5.9,Africa
Antigua & Barbuda,102,128,45,4.9,North America
...

When I run this: drinks.groupby('continent').head()

I get back a dataframe with 30 rows. But in those 30 rows I still have duplicate names for the continent. For example in the image below you can see that Europe is repeated two times (at rows 1 and 3):

I am not able to understand why I am still having two rows with the same continent when I grouped by continent originally?

In this case is the groupby operation also grouping by the country even though I never specified it in the groupby function? Since I know in SQL you are supposed to use an aggregate function like max, min, sum, etc. But in this case I don't have to pass in an aggregate function and I get the result above.

Body:
No!

What is happening is that head is a method on the groupby object and behaves a little differently than pd.DataFrame.head.

What the the groupby version of head does is returns the head of each group.

So we can see this more clearly by passing 1 to the head method and see it return the first row of each subset

df.groupby('continent').head(1)


问:
Infinite while loop issue while inserting element to quadtree
I'm trying to insert element to quadtree when mouse clicked. I call insert method when mouse clicked and sending point as parameter. After few clicks, while loop in insert method goes infinity and I couldn't find out why.

Here's method;

```<code>public void insert(Point point){
        Node newNode = new Node(point);
        if(root==null){
            root=newNode;
            return;
        }
        Node current=root;
        Node parent=null;

        while(true){
            parent = current;
            System.out.println("a");
            if(point.getX()<current.point.getX() && point.getY()<current.point.getY()){
                current=current.NW;
                if(current==null){
                    parent.NW= newNode;
                    return;
                }
            }
            else if(point.getX()>current.point.getX() && point.getY()<current.point.getY()){
                current=current.NE;
                if(current==null){
                    parent.NE= newNode;
                    return;
                }
        }
            else if(point.getX()<current.point.getX() && point.getY()>current.point.getY()){
                current=current.SW;
                if(current==null){
                    parent.SW=newNode;
                    return;
                }
            }
            else if(point.getX()>current.point.getX() && point.getY()>current.point.getY()){
                current=current.SE;
                if(current==null){
                    parent.SE=newNode;
                    return;
                }
            }

    }
    }
</code>```

If you need rest of code, let me know.

答:
Well, you haven't covered the cases where point and current.point are the same point, or are in line horizontally, or are in line vertically.  In each of these three cases, none of your if conditions are true, and there's no way to exit the loop.

You need to change either your < conditions to <= or your > conditions to >=.  So, something like

```<code>if(point.getX()<=current.point.getX() && point.getY()<=current.point.getY()){
</code>```

and similarly for every other comparison you've done using <.

This makes sure that your loop can exit when the X value are equal, or when the Y values are equal.

Body:
I'm trying to insert element to quadtree when mouse clicked. I call insert method when mouse clicked and sending point as parameter. After few clicks, while loop in insert method goes infinity and I couldn't find out why.

Here's method;

public void insert(Point point){
        Node newNode = new Node(point);
        if(root==null){
            root=newNode;
            return;
        }
        Node current=root;
        Node parent=null;

        while(true){
            parent = current;
            System.out.println("a");
            if(point.getX()<current.point.getX() && point.getY()<current.point.getY()){
                current=current.NW;
                if(current==null){
                    parent.NW= newNode;
                    return;
                }
            }
            else if(point.getX()>current.point.getX() && point.getY()<current.point.getY()){
                current=current.NE;
                if(current==null){
                    parent.NE= newNode;
                    return;
                }
        }
            else if(point.getX()<current.point.getX() && point.getY()>current.point.getY()){
                current=current.SW;
                if(current==null){
                    parent.SW=newNode;
                    return;
                }
            }
            else if(point.getX()>current.point.getX() && point.getY()>current.point.getY()){
                current=current.SE;
                if(current==null){
                    parent.SE=newNode;
                    return;
                }
            }

    }
    }

If you need rest of code, let me know.

Body:
Well, you haven't covered the cases where point and current.point are the same point, or are in line horizontally, or are in line vertically.  In each of these three cases, none of your if conditions are true, and there's no way to exit the loop.

You need to change either your < conditions to <= or your > conditions to >=.  So, something like

if(point.getX()<=current.point.getX() && point.getY()<=current.point.getY()){

and similarly for every other comparison you've done using <.

This makes sure that your loop can exit when the X value are equal, or when the Y values are equal.


问:
Gradle, Android and the ANDROID_HOME SDK location
edit: (aug-2016)

That question is from November 2013 (while Android Studio was still in Developer Preview mode),

Currently (AS v2.2, Aug-2016) during instalation AS asks to choose the SDK folder (or install on their default) and it automatically applies to which ever project you're opening.

That means any possible workaround or fix is irrelevant as the issue is not reproducible anymore.

original question:

we have this project with several modules that is already configured and executes correctly on another developer PC using a wrapper. I cloned the complete git submodules into my machine.

Below it's a directly print of my command line:

```<code>$ ./gradlew

FAILURE: Build failed with an exception.

* Where:
Build file '/home/budius/project_name/ActionBar-PullToRefresh/library/build.gradle' line: 1

* What went wrong:
A problem occurred evaluating project ':ActionBar-PullToRefresh:library'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.378 secs

$ echo $ANDROID_HOME
/home/budius/Applications/android-studio/sdk
$
</code>```

so, as you can see the ANDROID_HOME is there. What else do they want? What's wrong here.

running on Ubuntu 13.04

edit:

I already created a local.properties file with sdk.dir=<path> on the project root and it works. But that makes the code harder to port across systems n build server, so the question is still open.

Anyone knows why the ANDROID_HOME is not working and what to do to make it work?

答: i encountered the same error but in my case i was cloning a project, the cloned project was built with Android API 22 which i did not install at the time(i had API 24 and 25 installed)........so i had to download the sdk tools for API 22</p>

Body:
edit: (aug-2016)

That question is from November 2013 (while Android Studio was still in Developer Preview mode),

Currently (AS v2.2, Aug-2016) during instalation AS asks to choose the SDK folder (or install on their default) and it automatically applies to which ever project you're opening.

That means any possible workaround or fix is irrelevant as the issue is not reproducible anymore.

original question:

we have this project with several modules that is already configured and executes correctly on another developer PC using a wrapper. I cloned the complete git submodules into my machine.

Below it's a directly print of my command line:

$ ./gradlew

FAILURE: Build failed with an exception.

* Where:
Build file '/home/budius/project_name/ActionBar-PullToRefresh/library/build.gradle' line: 1

* What went wrong:
A problem occurred evaluating project ':ActionBar-PullToRefresh:library'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.378 secs

$ echo $ANDROID_HOME
/home/budius/Applications/android-studio/sdk
$

so, as you can see the ANDROID_HOME is there. What else do they want? What's wrong here.

running on Ubuntu 13.04

edit:

I already created a local.properties file with sdk.dir=<path> on the project root and it works. But that makes the code harder to port across systems n build server, so the question is still open.

Anyone knows why the ANDROID_HOME is not working and what to do to make it work?


问:
Is it possible to disable mac gatekeeper by extension?
I want to be warned by Mac gatekeeper whenever I attempt to use an app for the first time that is not signed through the store. However, I'm having trouble using LibreOffice Vanilla by clicking on files with relevant extensions (eg .ods, .odt). It seems to consider each file a different app and I think needs me to authorize it individually. Double-clicking file yeilds '"myfile.odt” can’t be opened because it is from an unidentified developer.'

Right-clicking and using Open with ... LibreOffice Vanilla yeilds:
'"myfile.odt” is from an unidentified developer. Are you sure you want to open it?'

I don't find the 'help' at https://support.apple.com/en-ca/HT202491 helpful. How can I configure OS X so it lets me open LibreOffice files with a double-click yet still have GateKeeper check other new applications that are not signed?

答:
You can bypass gatekeeper if you select a file type to "always open with" a certain type of program. Other programs that are not of this type will still invoke gatekeeper, so you won't have the security issues. So if you set your .odt file type to always open with libreoffice, the issue should go away.

See this:

https://apple.stackexchange.com/questions/193233/gatekeeper-wont-let-libreoffice-open-csv-files


问:
How do I return (k) amount of bits a binary strings in a file?
Essentially, if I were to type in 4 for n and 4 for k, it should return 4 lines of a 4 bit binary string in a file.

Instead, it returns four lines of binary, but in ascending order of bits. (So first line has one bit, second line has two, third line has three, and so on.)

Here is my code:

```<code>import random
def makeStrings():
    fileName = str(input("file:"))
    outputFile = open(fileName, "w")
    userInput = str(input("k:"))
    anotherinput = str(input("n:"))
    counter = 0
    while (counter < int(anotherinput)):
        stringy = ""
        for i in range(int(userInput)):
            RandoNumber=int(random.random()*2)
            stringy=stringy+str(RandoNumber)
            outputFile.write(str(stringy) + "\n")
            counter = counter +1
    outputFile.close()
</code>```

Thanks for your help!

答:
In this code:

```<code>    stringy = ""
    for i in range(int(userInput)):
        RandoNumber=int(random.random()*2)
        stringy=stringy+str(RandoNumber)
        outputFile.write(str(stringy) + "\n")
        counter = counter +1
</code>```

You are looping up to userInput, but printing every time. (In this case, outputFile.writeing every time.)

You need to wait until your for loop finishes before writing a value out to the outputFile. That way, your stringy variable will have the correct length.

Body:
Essentially, if I were to type in 4 for n and 4 for k, it should return 4 lines of a 4 bit binary string in a file.

Instead, it returns four lines of binary, but in ascending order of bits. (So first line has one bit, second line has two, third line has three, and so on.)

Here is my code:

import random
def makeStrings():
    fileName = str(input("file:"))
    outputFile = open(fileName, "w")
    userInput = str(input("k:"))
    anotherinput = str(input("n:"))
    counter = 0
    while (counter < int(anotherinput)):
        stringy = ""
        for i in range(int(userInput)):
            RandoNumber=int(random.random()*2)
            stringy=stringy+str(RandoNumber)
            outputFile.write(str(stringy) + "\n")
            counter = counter +1
    outputFile.close()

Thanks for your help!

Body:
In this code:

    stringy = ""
    for i in range(int(userInput)):
        RandoNumber=int(random.random()*2)
        stringy=stringy+str(RandoNumber)
        outputFile.write(str(stringy) + "\n")
        counter = counter +1

You are looping up to userInput, but printing every time. (In this case, outputFile.writeing every time.)

You need to wait until your for loop finishes before writing a value out to the outputFile. That way, your stringy variable will have the correct length.


问:
Json parsing errors while using json_extract_path_text() function in where clause
I have a Redshift table that contains columns with json objects. I am running into json parser failures while trying to execute queries on this table that applies specific filters on the json object content.
While I am able to use the json_extract_path_text() in the select statements, the same fails when used in where clause.

Following is the error I see:
Amazon Invalid operation: JSON parsing error;

When I look at the STL_ERROR table for more details, this is what I see in the error details:
errcode: 8001
context: JSON parsing error
error: invalid json object null

Following is an example of the content in one such json column:

```<code>{"att1":"att1_val","att2":"att2_val","att3":[{"att3_sub1_1":"att3_sub1_1_val","att3_sub1_2":"att3_sub1_2_val"},{"att3_sub2_1":"att3_sub2_1_val","att3_sub2_2":"att3_sub2_2_val"}],"att4":"att4_val","att5":"att5_val"}
</code>```

Now when I run the following query, it executes without any issues:

```<code>select
json_extract_path_text(col_with_json_obj,'att4') as required_val
from table_with_json_data;
</code>```

Now when I use the json_extract_path_text() in the where clause it fails with the above error:

```<code>select
json_extract_path_text(col_with_json_obj,'att4') as required_val
from table_with_json_data
where json_extract_path_text(col_with_json_obj,'att4') = 'att4_val';
</code>```

Is there anything that I am using incorrectly or missing here?

P.S: I have another table with similar schema and the same queries run just fine on that. The only difference between the two tables is the way the data is loaded - one uses jsonpaths file in the copy options and the other uses json 'auto'.

答:
This is the error you would receive if table_with_json_data contained even a single row in which the value of col_with_json_obj was the four-character string "null".

To avoid errors like this in general I'd recommend creating a Redshift UDF for validating JSON. The is_json() method described at http://discourse.snowplowanalytics.com/t/more-robust-json-parsing-in-redshift-with-python-udfs/197 has worked well for me:

```<code>create or replace function is_json(j varchar(max))
  returns boolean
  stable as $$
    import json
    try:
      json_object = json.loads(j)
    except ValueError, e:
      return False
    return True
  $$ language plpythonu;
</code>```

Then you could add a and where is_json(col_with_json_obj) clause to your query and this class of errors can be avoided entirely.

Body:
I have a Redshift table that contains columns with json objects. I am running into json parser failures while trying to execute queries on this table that applies specific filters on the json object content.
While I am able to use the json_extract_path_text() in the select statements, the same fails when used in where clause.

Following is the error I see:
Amazon Invalid operation: JSON parsing error;

When I look at the STL_ERROR table for more details, this is what I see in the error details:
errcode: 8001
context: JSON parsing error
error: invalid json object null

Following is an example of the content in one such json column:

{"att1":"att1_val","att2":"att2_val","att3":[{"att3_sub1_1":"att3_sub1_1_val","att3_sub1_2":"att3_sub1_2_val"},{"att3_sub2_1":"att3_sub2_1_val","att3_sub2_2":"att3_sub2_2_val"}],"att4":"att4_val","att5":"att5_val"}

Now when I run the following query, it executes without any issues:

select
json_extract_path_text(col_with_json_obj,'att4') as required_val
from table_with_json_data;

Now when I use the json_extract_path_text() in the where clause it fails with the above error:

select
json_extract_path_text(col_with_json_obj,'att4') as required_val
from table_with_json_data
where json_extract_path_text(col_with_json_obj,'att4') = 'att4_val';

Is there anything that I am using incorrectly or missing here?

P.S: I have another table with similar schema and the same queries run just fine on that. The only difference between the two tables is the way the data is loaded - one uses jsonpaths file in the copy options and the other uses json 'auto'.

Body:
This is the error you would receive if table_with_json_data contained even a single row in which the value of col_with_json_obj was the four-character string "null".

To avoid errors like this in general I'd recommend creating a Redshift UDF for validating JSON. The is_json() method described at http://discourse.snowplowanalytics.com/t/more-robust-json-parsing-in-redshift-with-python-udfs/197 has worked well for me:

create or replace function is_json(j varchar(max))
  returns boolean
  stable as $$
    import json
    try:
      json_object = json.loads(j)
    except ValueError, e:
      return False
    return True
  $$ language plpythonu;

Then you could add a and where is_json(col_with_json_obj) clause to your query and this class of errors can be avoided entirely.


问:
How to create a Form dynamically?
I want to create, dynamically, forms depending a type of user. For example:
I want, if it is an administrator, to create the form or the buttons, for this user specifically.
 In the code of my login there is a validation that identifies the type of user.
But I only did that when it identifies the user to send it to the corresponding screen with its buttons already set, but what I want is that when identifying the user type, generate the buttons that the user should have access to;
The user has a type of user and that type of user has 1 or more permissions, then, depending on how many permissions that user has, create the buttons. Each permission is a button.
Example:
The user Alfonso is type of sales and has permissions to invoice and sell, then when it initiates session the "invoice" and "sell" buttons will be generated.</p>

答: The simplest way is to create classes that inherit from Form, and add the controls you want and set the properties of the controls to what you want.  When you need a form you just create a new one.  If necessary you can pass parameters you need in setting up the form through the constructor.

Title: How to create a Form dynamically?


问:
Alter appearance of data after report is generated
I have a detail report with interactive sorting on the headers.
After the report is refreshed, the user would like to highlight some rows of data that appear throughout the report in order to see if patterns are detectable.

Say, a vendor name that appears on multiple customer rows might indicate that they all shopped at the same vendor before their credit card was compromised.  Highlighting that vendor name might make it easier to spot whether this is a problem vendor.  They won't know what they want to highlight until they start perusing the data, so a run-time parameter won't work.

In the past I used BusinessObjects which had a control that could be used to trigger alerts (formatting changes).

Is there a way to hack such a thing in SSRS?

答:
Is there a way to hack such a thing in SSRS? No.

But, if the report user wants to export the report to Excel, then they can do whatever they would like to that spreadsheet afterward. They just need to know that any changes will not be written back to a data store any where as a result of that.

SSRS is purely for reporting data, not altering it, or annotating it. Changing the report output in Report Manager is not possible, either.

If you need to be able to highlight data in a report at run time, you can do that via a combination of properties and expressions in the RDL. Your business users would need to tell you what the rules for that are, then you can make the changes in what ever dev tool you are using to create reports.

I hope this clarifies some things for you.


问:
Using GCC extensions with code compiled with clang?
I have a two questions regarding GCC extensions

If I compile a library using GCC attributes/extensions, will they work even if I link them to a program compiled with for example clang?

Should function attributes/extensions be declared in the function declaration or prototype?

答:
It depends on the extension.

See https://clang.llvm.org/docs/LanguageExtensions.html

This document describes the language extensions provided by Clang. In
  addition to the language extensions listed here, Clang aims to support
  a broad range of GCC extensions. Please see the GCC manual for more
  information on these extensions.


问:
Draw Straight line between two points in vertical orientation using Opencv and C++
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

```<code>cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);
</code>```

This is the following output:

What am I doing wrong?

答:
This is a known bug, now fixed.

So update to the latest version of OpenCV (version 3.2) or use cv::clipLine(img.size(), p, q); before drawing line.

All credits to @sturkmen

Body:
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);

This is the following output:

What am I doing wrong?


问:
One button to fire toggle functions? Press button -> toggleOn(), press again -> toggleOff(), press again -> toggleOn()
Is it possible to use the same onClick from a button to make it a "toggle"?

I have a button, <button>Toggle</button> and basically toggling it on should execute either toggleOn() or toggleOff().

How do I do this with just onClick property?

答:
Here is a simple "toggler" higher-order function:

```<code>function toggler(fn1, fn2) {
  var toggled = true;
  return function () {
    toggled = !toggled;
    return (toggled ? fn1 : fn2).apply(this, arguments);
  }
}

function logToConsole (e) {
  console.log(this, e);
}

function logToAlert (e) {
  alert(e);
}

var toggledLog = toggler(logToConsole, logToAlert);
</code>```

Now running toggledLog with arguments and context will work properly. You can use it in your onClick handler.

Body:
Here is a simple "toggler" higher-order function:

function toggler(fn1, fn2) {
  var toggled = true;
  return function () {
    toggled = !toggled;
    return (toggled ? fn1 : fn2).apply(this, arguments);
  }
}

function logToConsole (e) {
  console.log(this, e);
}

function logToAlert (e) {
  alert(e);
}

var toggledLog = toggler(logToConsole, logToAlert);

Now running toggledLog with arguments and context will work properly. You can use it in your onClick handler.


问:
Shared pointer with observer pointers
I have a class Foo, which has a vector of some large classes. The idea is, that an octal tree will be built recursively out of the elements of the vector, and each OctreeNode will have a pointer to few elements of the vector found in Foo. (In the example, just for simplicity, a node will point to only one element of the vector)

```<code>class Foo
{
    vector<LargeClass>  mLargeClasses;

    void removeItem(const int index);    //remove an element from the vector at the index
}

class OctreeNode
{
    LargeClass* mLargeClass;
}
</code>```

One can say, "why bother keeping the vector after the tree is built, and store the objects in the tree itself". True, let's just say, I need to keep vector parallel to the built tree as well.

While the above concept works, I have issues when elements got removed from the underlying vector. In such case, some Octree nodes end up with dangling pointers.

My solution #1:
If removeItem function is called, then before it removes the vector element, it first recursively traverse the octal tree, and make all mLargeClass pointer a nullptr which happen to point to that particular vector element. It's ok to have nullptr in the nodes, as I check each time against nullptr, when I access them anyway.

My solution #2:
Have the vector store shared_ptrs, and have the OctreeNode store a weak_ptr. I am not fan of this, as each time I access a weak_ptr in the tree, it gets converted to a shared_ptr in the background with all the atomic counter increases. I am not expert on performance testing, but I have a feeling, that it is slower than a simple pointer access with if condition.

Does anybody know any better solutions?

I think the most elegant would be:
To have smart pointer which behaves like a shared_pointer, counts, how many other pointer refers to it, keep a record of them, and in case it gets destroyed, it automatically nulls out all other "observer" pointers which refer to it?

答:
While the field, and the purpose is somewhat different, i think i will give a try for the handle system described in this port:
Simple, efficient weak pointer that is set to NULL when target memory is deallocated
If I fail, I will revert back to the shared_ptr/weak_ptr duo. Described in the same post.</p>

Title: Shared pointer with observer pointers

Body:
I have a class Foo, which has a vector of some large classes. The idea is, that an octal tree will be built recursively out of the elements of the vector, and each OctreeNode will have a pointer to few elements of the vector found in Foo. (In the example, just for simplicity, a node will point to only one element of the vector)

class Foo
{
    vector<LargeClass>  mLargeClasses;

    void removeItem(const int index);    //remove an element from the vector at the index
}

class OctreeNode
{
    LargeClass* mLargeClass;
}

One can say, "why bother keeping the vector after the tree is built, and store the objects in the tree itself". True, let's just say, I need to keep vector parallel to the built tree as well.

While the above concept works, I have issues when elements got removed from the underlying vector. In such case, some Octree nodes end up with dangling pointers.

My solution #1:
If removeItem function is called, then before it removes the vector element, it first recursively traverse the octal tree, and make all mLargeClass pointer a nullptr which happen to point to that particular vector element. It's ok to have nullptr in the nodes, as I check each time against nullptr, when I access them anyway.

My solution #2:
Have the vector store shared_ptrs, and have the OctreeNode store a weak_ptr. I am not fan of this, as each time I access a weak_ptr in the tree, it gets converted to a shared_ptr in the background with all the atomic counter increases. I am not expert on performance testing, but I have a feeling, that it is slower than a simple pointer access with if condition.

Does anybody know any better solutions?

I think the most elegant would be:
To have smart pointer which behaves like a shared_pointer, counts, how many other pointer refers to it, keep a record of them, and in case it gets destroyed, it automatically nulls out all other "observer" pointers which refer to it?


问:
IIS UrlRewrite problem
I've been using the UrlRewrite IIS plugin for about a month on our production site.

I created a single redirect rule using the supplied template/wizard, the resulting config enrty is as follows:

```<code><rewrite>
    <rules>
        <rule name="CanonicalHostNameRule1" enabled="true">
            <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^www\.mycompany\.com$" negate="true" />
            </conditions>
            <action type="Redirect" url="http://www.mycompany.com/{R:1}" />
        </rule>
    </rules>
</rewrite>
</code>```

It's been running fine until this morning, when the site started erroring with "too many redirects".  As far as I know, nothing in the configuration or infrastructure changed.

I disabled the rule, and the site became functional again (though clearly without any redirecting).

I then re-enabled the rule, and now all is running as expected.  I didn't make any changes to the rule other than to temporarily disable it.

Any ideas?  Is the plugin buggy?

答:
The fix below worked for me. I discovered my rewrite rule was at out-of-date.  The other domain had changed their URL policy and were now redirecting all traffic from otherdomain.com to www.otherdomain.com

```<code><action type="Rewrite" url="http://otherdomain.com/abc/{R:1}" />
</code>```

to

```<code><action type="Rewrite" url="http://www.otherdomain.com/abc/{R:1}" />
</code>```

Do you see the difference?  By adding the 'www' I preempted the other domain redirection.  I basically just complied with their new policy.

Title: IIS UrlRewrite problem

Body:
I've been using the UrlRewrite IIS plugin for about a month on our production site.

I created a single redirect rule using the supplied template/wizard, the resulting config enrty is as follows:

<rewrite>
    <rules>
        <rule name="CanonicalHostNameRule1" enabled="true">
            <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^www\.mycompany\.com$" negate="true" />
            </conditions>
            <action type="Redirect" url="http://www.mycompany.com/{R:1}" />
        </rule>
    </rules>
</rewrite>

It's been running fine until this morning, when the site started erroring with "too many redirects".  As far as I know, nothing in the configuration or infrastructure changed.

I disabled the rule, and the site became functional again (though clearly without any redirecting).

I then re-enabled the rule, and now all is running as expected.  I didn't make any changes to the rule other than to temporarily disable it.

Any ideas?  Is the plugin buggy?

Body:
The fix below worked for me. I discovered my rewrite rule was at out-of-date.  The other domain had changed their URL policy and were now redirecting all traffic from otherdomain.com to www.otherdomain.com

<action type="Rewrite" url="http://otherdomain.com/abc/{R:1}" />

to

<action type="Rewrite" url="http://www.otherdomain.com/abc/{R:1}" />

Do you see the difference?  By adding the 'www' I preempted the other domain redirection.  I basically just complied with their new policy.


问:
How to use an interface with methods that has in input or return type the reference of the interface?
I have an interface like that:

```<code>public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}
</code>```

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

```<code>public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);
</code>```

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}
</code>```

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

答:
The equals method is unnecesary, it's already defined in Object. You should override it.

For addChildren, you could store a IntTree list:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<IntTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
       this.data = data;
       this.children = new LinkedList<>();
    }

    public void addChild(IntTree child) {
        children.addFirst(child);
    }

    public LinkedList<IntTree> getChildren() {
        return children;
    }

    public IntTree followPath(int[] path) throws NoSuchTreeException {
        for (int i = 0; i < path.length; i++) {
            path[i] = path[i] - 1;
        }

        IntTree oggetto = this;
        for (int i = 0; i < path.length; i++) {
            int index = path[i];
            if (index >= oggetto.getChildren().size() || oggetto.getChildren().isEmpty()) {
                throw new NoSuchTreeException();
            }
            oggetto = oggetto.getChildren().get(i);
        }

        return oggetto;
    }
</code>```

In "followpath" i changed the type of oggeto asswell.

The key is hold the most general reference while avoiding the casts.

Body:
I have an interface like that:

public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

Body:
The equals method is unnecesary, it's already defined in Object. You should override it.

For addChildren, you could store a IntTree list:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<IntTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
       this.data = data;
       this.children = new LinkedList<>();
    }

    public void addChild(IntTree child) {
        children.addFirst(child);
    }

    public LinkedList<IntTree> getChildren() {
        return children;
    }

    public IntTree followPath(int[] path) throws NoSuchTreeException {
        for (int i = 0; i < path.length; i++) {
            path[i] = path[i] - 1;
        }

        IntTree oggetto = this;
        for (int i = 0; i < path.length; i++) {
            int index = path[i];
            if (index >= oggetto.getChildren().size() || oggetto.getChildren().isEmpty()) {
                throw new NoSuchTreeException();
            }
            oggetto = oggetto.getChildren().get(i);
        }

        return oggetto;
    }

In "followpath" i changed the type of oggeto asswell.

The key is hold the most general reference while avoiding the casts.


问:
newbie: idled python def
I'm feeling a rabbit posting this question, but I don't continue because this:
What's is wrong with this stretch of my code:

When I put something after the "if" I receive:

IndentationError: unindent does not match any outer indentation level

For example, if I put "cont =3" after the "if" and before "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      post = form2.save(commit=False)
                                    ^ IndentationError: unindent does not match any outer indentation level

If I put the same expression but before of "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      cont = 3
             ^ TabError: inconsistent use of tabs and spaces in indentation

the code:

```<code>def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            cont = 3
            post = form2.save(commit=False)
            post.save()
            return redirect('canditate_list')
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})
</code>```

[EDIT]:
Guys, I don't indented wrong because I just press "Enter" before I type "True:",There's no way I could have mistaken it if the editor did this automatically

[EDIT2]:
I NEVER use space to indent my codes precisely avoid this problems, I ALWAYS use "tab" and just "tab"

答:
It's all about indentation!  Python determines what where the code is based on its indentation (rather than {} like most other languages).

Here's an example, this is valid code:

```<code>if 1 == 1:
    print('If passed!')
</code>```

Once the if statement determines that 1 == 1 is True it looks for the indentation on the next line and runs it!

Here's another example, this is invalid code:

```<code>if 1 == 1:
print('If passed!')
</code>```

Once the if statement determines that 1 == 1 is True it looks for the indentation on the next line, however, it doesn't find the indentation, so it doesn't know what to do, so it throws an IndentationError

In your code, you have this, and it works!

```<code>if request.method == "POST":
    form2 = EvalForm(request.POST)
</code>```

My guess is that when you add the cont = 3 you add it like this

```<code>if request.method == "POST":
cont = 3
    form2 = EvalForm(request.POST)
</code>```

So when python gets passed the if statement it looks for the next indentation, but there is none, so it throws an IndentationError.

I hope this helps you understand what's going on!

Title: newbie: idled python def

Body:
I'm feeling a rabbit posting this question, but I don't continue because this:
What's is wrong with this stretch of my code:

When I put something after the "if" I receive:

IndentationError: unindent does not match any outer indentation level

For example, if I put "cont =3" after the "if" and before "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      post = form2.save(commit=False)
                                    ^ IndentationError: unindent does not match any outer indentation level

If I put the same expression but before of "post = form2.save(commit=False)" I receive:

File
  "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py",
  line 59
      cont = 3
             ^ TabError: inconsistent use of tabs and spaces in indentation

the code:

def evaluation(request):
    # form2 initialization
    list_evaluation = Evaluation.objects.all()
    form2 = EvalForm()
    cont = 0

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid() == True:
            cont = 3
            post = form2.save(commit=False)
            post.save()
            return redirect('canditate_list')
    else:
        form2 = EvalForm()
    return render(request, 'app/evaluation.html', {'criterions': form2,})

[EDIT]:
Guys, I don't indented wrong because I just press "Enter" before I type "True:",There's no way I could have mistaken it if the editor did this automatically

[EDIT2]:
I NEVER use space to indent my codes precisely avoid this problems, I ALWAYS use "tab" and just "tab"

Body:
It's all about indentation!  Python determines what where the code is based on its indentation (rather than {} like most other languages).

Here's an example, this is valid code:

if 1 == 1:
    print('If passed!')

Once the if statement determines that 1 == 1 is True it looks for the indentation on the next line and runs it!

Here's another example, this is invalid code:

if 1 == 1:
print('If passed!')

Once the if statement determines that 1 == 1 is True it looks for the indentation on the next line, however, it doesn't find the indentation, so it doesn't know what to do, so it throws an IndentationError

In your code, you have this, and it works!

if request.method == "POST":
    form2 = EvalForm(request.POST)

My guess is that when you add the cont = 3 you add it like this

if request.method == "POST":
cont = 3
    form2 = EvalForm(request.POST)

So when python gets passed the if statement it looks for the next indentation, but there is none, so it throws an IndentationError.

I hope this helps you understand what's going on!


问:
Python While/for/if statements
I wrote a program that multiplies input number by 127. The input doesn't accept alpha as well as number 9.

Besides number 9, it doesn't allow any number that contains 9 e.g. 99, 19 etc. Can we overcome this?

Also, if I type "99", it prints "Banned number" two times. Is this co-related with the first statement?

```<code>banned_number = "9"
while True:
    number = input("number ")

    for items in number:
        if items in banned_number:
            print ("Banned number.")
        elif number.isalpha():
            print ("Sorry, numbers only.")
        elif number.isdigit():
            a = int(number)
            print(a* 127)
</code>```

I know this program is useless, which it clearly is - I went off track when exercising loops and this is the final shape. Is there any way to make this code shorter? Can we make both elif's obsolete with a simple code?

I would appreciate your patience as I've only started Python last week, thank you.

答:
Take the logic out of the loop, and invert the membership check:</p>

```<code>banned_number = "9"
while True:
    number = input("number ")
    if banned_number in number:
        print ("Banned number.")
    elif number.isalpha():
        print ("Sorry, numbers only.")
    elif number.isdigit():
        a = int(number)
        print(a* 127)
</code>```

Title: Python While/for/if statements

Body:
I wrote a program that multiplies input number by 127. The input doesn't accept alpha as well as number 9.

Besides number 9, it doesn't allow any number that contains 9 e.g. 99, 19 etc. Can we overcome this?

Also, if I type "99", it prints "Banned number" two times. Is this co-related with the first statement?

banned_number = "9"
while True:
    number = input("number ")

    for items in number:
        if items in banned_number:
            print ("Banned number.")
        elif number.isalpha():
            print ("Sorry, numbers only.")
        elif number.isdigit():
            a = int(number)
            print(a* 127)

I know this program is useless, which it clearly is - I went off track when exercising loops and this is the final shape. Is there any way to make this code shorter? Can we make both elif's obsolete with a simple code?

I would appreciate your patience as I've only started Python last week, thank you.

Body:
Take the logic out of the loop, and invert the membership check:

banned_number = "9"
while True:
    number = input("number ")
    if banned_number in number:
        print ("Banned number.")
    elif number.isalpha():
        print ("Sorry, numbers only.")
    elif number.isdigit():
        a = int(number)
        print(a* 127)


问:
Saving model in afterSave() in cakePHP
I have a form with a file upload field in it and I have created a model behaviour file to handle file processing.

I have two functions, beforeSave and afterSave:

In beforeSave I do some stuff and then set the file value in data to null so it can be saved. Else it will try to save an array, and the database expects just a string (the file name)

In afterSave I generate a new file name based on some text fields on the form, and add the lastInsertId infront of it. I also move the file from temp to desired location.
This all works fine, but when I try to save the new filename to the Model it just doesnt work.

I have done a lot of test and debugging, and also spent hours searching online. The conclusion is that you can not save in afterSave, it triggers itself and will run beforeSave again.

So my question is, how can I update the newly inserted model? The filename inserted need to have the primary key in its name, and its unknown at time of beforeSave.

grateful for any help!
jason

答:
Ideally, if your filename is dependent on other columns in the database, then you don't need to resave your model data again. In fact, it would introduce columns in your table's schema that depend on each other, which goes against normalization.

Eg. If your filename is of the form "textfield1-textfield2-yourid.ext", you should store the values of textfield1, textfield2 and ext in the database. Then, in the afterFind() method of your model, you can loop through your results creating the generated filename as a new field in your data array.

Sample Table Schema:

```<code>id | textfield1 | textfield2 | extension | created | modified
</code>```

Sample View Code:

```<code>echo $this->Html->image("{$data['Picture']['textfield1']}-{$data['Picture']['textfield2']}-{$data['Picture']['id']}.{$data['Picture']['extension']}");
</code>```

Of course, like I mentioned earlier, this can be simplified if you override the afterFind() in your model and create a new field called "filename". More on that over here.

This would shorten your code to:

```<code>echo $this->Html->image($data['Picture']['filename']);
</code>```

And would also make it easier to modify universally at any point.

Title: Saving model in afterSave() in cakePHP

Body:
Ideally, if your filename is dependent on other columns in the database, then you don't need to resave your model data again. In fact, it would introduce columns in your table's schema that depend on each other, which goes against normalization.

Eg. If your filename is of the form "textfield1-textfield2-yourid.ext", you should store the values of textfield1, textfield2 and ext in the database. Then, in the afterFind() method of your model, you can loop through your results creating the generated filename as a new field in your data array.

Sample Table Schema:

id | textfield1 | textfield2 | extension | created | modified

Sample View Code:

echo $this->Html->image("{$data['Picture']['textfield1']}-{$data['Picture']['textfield2']}-{$data['Picture']['id']}.{$data['Picture']['extension']}");

Of course, like I mentioned earlier, this can be simplified if you override the afterFind() in your model and create a new field called "filename". More on that over here.

This would shorten your code to:

echo $this->Html->image($data['Picture']['filename']);

And would also make it easier to modify universally at any point.


问:
C2065: "ui" : undeclared identifier
I'm writting my first program in Qt Designer, and I have problem with changing QLineEdit text to nothing. I want to use for this operation detached thread, so I can continue working in another part of program without waiting for end of Sleep(5000) function. But when I want to compile this code I'm getting 3 errors:

C2065: "ui" : undeclared identifier

C2227: left "->AutoWyl_textPotwierdzenie" must pointing type class/struct/union/generic

C2227: left "->setText" must pointing type class/struct/union/generic

Could you help me with that errors? Thanks in advance.

Here is problematic part of code:

```<code>    {...
        void autowyl_potwierdzenie_reset();
        std::thread reset(autowyl_potwierdzenie_reset);
        reset.detach();
    }

    void autowyl_potwierdzenie_reset()
    {
        Sleep(5000);
        ui->Autowyl_textPotwierdzenie->setText(""); //3 errors
    }
</code>```

答:
I think you are creating the thread from a method of a class containing ui (which is probably a pointer to the Ui::TheWidgetYouDesignedInQtDesigner). On the other hand, the function that the thread runs is out of the class, thus it can't reach ui.

I suggest passing ui as a parameter, or, better, passing only the QLineEdit:

```<code>// ...
std::thread reset(autowyl_potwierdzenie_reset, ui-> Autowyl_textPotwierdzenie);
// ...

void autowyl_potwierdzenie_reset(QLineEdit* lineEdit)
{
    Sleep(5000);
    lineEdit->setText("");
}
</code>```

If autowyl_potwierdzenie_reset is never used again, you can use a lambda function instead (increasing the readability of your code):

```<code>std::thread reset([ui]() {
  Sleep(5000);
  ui->Autowyl_textPotwierdzenie->setText("");
});
reset.detach();
</code>```

Title: C2065: "ui" : undeclared identifier

Body:
I'm writting my first program in Qt Designer, and I have problem with changing QLineEdit text to nothing. I want to use for this operation detached thread, so I can continue working in another part of program without waiting for end of Sleep(5000) function. But when I want to compile this code I'm getting 3 errors:

C2065: "ui" : undeclared identifier

C2227: left "->AutoWyl_textPotwierdzenie" must pointing type class/struct/union/generic

C2227: left "->setText" must pointing type class/struct/union/generic

Could you help me with that errors? Thanks in advance.

Here is problematic part of code:

    {...
        void autowyl_potwierdzenie_reset();
        std::thread reset(autowyl_potwierdzenie_reset);
        reset.detach();
    }

    void autowyl_potwierdzenie_reset()
    {
        Sleep(5000);
        ui->Autowyl_textPotwierdzenie->setText(""); //3 errors
    }

Body:
I think you are creating the thread from a method of a class containing ui (which is probably a pointer to the Ui::TheWidgetYouDesignedInQtDesigner). On the other hand, the function that the thread runs is out of the class, thus it can't reach ui.

I suggest passing ui as a parameter, or, better, passing only the QLineEdit:

// ...
std::thread reset(autowyl_potwierdzenie_reset, ui-> Autowyl_textPotwierdzenie);
// ...

void autowyl_potwierdzenie_reset(QLineEdit* lineEdit)
{
    Sleep(5000);
    lineEdit->setText("");
}

If autowyl_potwierdzenie_reset is never used again, you can use a lambda function instead (increasing the readability of your code):

std::thread reset([ui]() {
  Sleep(5000);
  ui->Autowyl_textPotwierdzenie->setText("");
});
reset.detach();


问:
Are too many Session variables bad practice?
I am thinking to use 5 session variables per user. I know if I store these variables using inproc mode it will surely affect the performance as I am having shared server.

But I am using SQL Server to store my session variables.So will it be sill overload on performance.

Because if I store variables in session my joins will be be quite simplified plus one hit to db will be saved.

答:
I want to say "Yes", but it depends on what you are trying to achieve.  I have read a lot of talented developer's blogs on this topic because I have inherited older applications with lots of sessions.

I create one session per user with a unique id(guid), which is used as a key for my MemoryCache.  The guid is created after the user is authenticated.  Session is defaulted to expire after 15 minutes if idle, Cache expires after 20 minutes.  Renewal is handled for active users.  One benefit of cache is it forces the developer to create clean code (checks and balances) whereas lots of sessions can help contribute to spaghetti code.

Within my BaseController, I have a method that uses the guid to get all information saved in cache for that user.  Here is a sample and is not all the code:

LoginController (snippet)

```<code>userCache.UniqueID = GuidUtil.GenerateGuid()
userCache.UserSiteCount = userSitesList.Count
userCache.UserID = user.UserID
userCache.UserName = user.UserName
_registeredUserService.AddUserToCache(userCache)
Session("UserKey") = userCache.UniqueID
</code>```

BaseController

```<code>    Private Function CheckAuthentication() As Boolean
        If Not Session("UserKey") Is Nothing Then
            Return True
        End If
        Return False
    End Function

    Private Function GetUserKey() As String
        Return Session("UserKey").ToString()
    End Function

    Protected ReadOnly Property GetUserInfo() As UserCache
        Get
            Return If(CheckAuthentication(), LoadUserInfo(), Nothing)
        End Get
    End Property

    Private Function LoadUserInfo() As UserCache
        Dim cachedUser = _registeredUserService.GetUserFromCache(GetUserKey())
        Return cachedUser
    End Function
</code>```

AllOtherControllers (snippet)

```<code>Dim viewModel As New ChooseSiteViewModel
viewModel.UserSites = _registeredUserService.GetUserSites(GetUserInfo.UserID)
Return View(viewModel)
</code>```

ServiceLevel

```<code>Function GetUserFromCache(ByVal uniqueKey As String) As UserCache _
Implements IRegisteredUserService.GetUserFromCache
    Dim userKey = String.Concat(CacheKeys.User.Main, uniqueKey)
    Return _cacheService.[Get](Of UserCache)(userKey)
End Function
</code>```

Body:
I want to say "Yes", but it depends on what you are trying to achieve.  I have read a lot of talented developer's blogs on this topic because I have inherited older applications with lots of sessions.

I create one session per user with a unique id(guid), which is used as a key for my MemoryCache.  The guid is created after the user is authenticated.  Session is defaulted to expire after 15 minutes if idle, Cache expires after 20 minutes.  Renewal is handled for active users.  One benefit of cache is it forces the developer to create clean code (checks and balances) whereas lots of sessions can help contribute to spaghetti code.

Within my BaseController, I have a method that uses the guid to get all information saved in cache for that user.  Here is a sample and is not all the code:

LoginController (snippet)

userCache.UniqueID = GuidUtil.GenerateGuid()
userCache.UserSiteCount = userSitesList.Count
userCache.UserID = user.UserID
userCache.UserName = user.UserName
_registeredUserService.AddUserToCache(userCache)
Session("UserKey") = userCache.UniqueID

BaseController

    Private Function CheckAuthentication() As Boolean
        If Not Session("UserKey") Is Nothing Then
            Return True
        End If
        Return False
    End Function

    Private Function GetUserKey() As String
        Return Session("UserKey").ToString()
    End Function

    Protected ReadOnly Property GetUserInfo() As UserCache
        Get
            Return If(CheckAuthentication(), LoadUserInfo(), Nothing)
        End Get
    End Property

    Private Function LoadUserInfo() As UserCache
        Dim cachedUser = _registeredUserService.GetUserFromCache(GetUserKey())
        Return cachedUser
    End Function

AllOtherControllers (snippet)

Dim viewModel As New ChooseSiteViewModel
viewModel.UserSites = _registeredUserService.GetUserSites(GetUserInfo.UserID)
Return View(viewModel)

ServiceLevel

Function GetUserFromCache(ByVal uniqueKey As String) As UserCache _
Implements IRegisteredUserService.GetUserFromCache
    Dim userKey = String.Concat(CacheKeys.User.Main, uniqueKey)
    Return _cacheService.[Get](Of UserCache)(userKey)
End Function


问:
Can not reference GeoSpatial type Point in Azure functions
I want to store location information in DocumentDB, hence using the Point type from DocumentDB. I have a class LocationInfo to map data from the incoming post request.

```<code>#r "Newtonsoft.Json"

using Newtonsoft.Json;
using Microsoft.Azure.Documents.Spatial;

public class LocationInfo
{
    [JsonProperty(PropertyName = "deviceId")]
    public string DeviceId {get; set;}

    [JsonProperty(PropertyName = "location")]
    public Point Location {get; set;}

    [JsonProperty(PropertyName = "activityId")]
    public string ActivityId {get; set;}

    [JsonProperty(PropertyName = "type")]
    public string Type {get; set;}

    [JsonProperty(PropertyName = "dateTime")]
    public DateTime DateTime {get; set;}
}
</code>```

My function isn't compiling and I am getting the error below.

```<code>error CS0234: The type or namespace name 'Documents' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)
error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)
</code>```

How do I reference using Microsoft.Azure.Documents.Spatial; in an Azure Function.

答:
You'll need to add the Document DB nuget package to your function, see this answer: https://stackoverflow.com/a/36411537/5915331

In the function's develop section, click on view files

Click on the option to create a file (you can also click on the option to upload a file if you have a previously created project.json file on your machine

Name the file project.json and define your package references (you can use the example above as a template).

Body:
I want to store location information in DocumentDB, hence using the Point type from DocumentDB. I have a class LocationInfo to map data from the incoming post request.

#r "Newtonsoft.Json"

using Newtonsoft.Json;
using Microsoft.Azure.Documents.Spatial;

public class LocationInfo
{
    [JsonProperty(PropertyName = "deviceId")]
    public string DeviceId {get; set;}

    [JsonProperty(PropertyName = "location")]
    public Point Location {get; set;}

    [JsonProperty(PropertyName = "activityId")]
    public string ActivityId {get; set;}

    [JsonProperty(PropertyName = "type")]
    public string Type {get; set;}

    [JsonProperty(PropertyName = "dateTime")]
    public DateTime DateTime {get; set;}
}

My function isn't compiling and I am getting the error below.

error CS0234: The type or namespace name 'Documents' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)
error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)

How do I reference using Microsoft.Azure.Documents.Spatial; in an Azure Function.