问:
How to avoid recreate Fragment into ViewPager?
I am using a ViewPager with a FragmentStatePagerAdapter that contains 5 pages.

In the first page I have a ListView with items. When I change at the last page of the ViewPager, and I come back to first page, my ListView is empty because the Adapter has been recreated.

Android always calls to the next methods: onAttach(), onCreate(), onCreateView(), onViewCreated(), onActivityCreated(), onStart() and onResume().

I would like don't use ViewPager.setOffscreenPageLimit() methods to avoid that my pages can be destroyed. There are any alternative solution?

The behavior I want is the same that makes Facebook.

What I doing wrong? How I can keep the data in my ListView?

Code of my FragmentStatePageAdapter:

```<code>public class AdapterMain extends FragmentStatePagerAdapter {
    List<ChicfyFragment> fragments = new ArrayList<ChicfyFragment>();

    public AdapterMain(FragmentManager fm) {
        super(fm);

        fragments.add(new FragmentShop());
        fragments.add(new FragmentSearch());
        fragments.add(new FragmentSell());
        fragments.add(new FragmentNotification());
        fragments.add(new FragmentProfile());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}
</code>```

Code of the first page of my ViewPager:

```<code>public class FragmentShop extends ChicfyFragment implements SwipeRefreshLayout.OnRefreshListener {

    ListView mListView;
    AdapterProductList mAdapter;
    SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_shop, container, false);

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        mListView = (ListView) view.findViewById(R.id.fragment_main_shop_listview);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // setup adapter
        mAdapter = new AdapterProductList((FragmentActivity) getActivity(), new ArrayList());

        // setup listview
        mListView.setAdapter(mAdapter);
        mListView.setDivider(null);

        // setup swipe
        mSwipeRefreshLayout.setColorScheme(R.color.red, R.color.white, R.color.blue, R.color.white);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        new AsyncTask<Void, Void, Void>() {
            List<String> list = new ArrayList<String>();

            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    Thread.sleep(1000);
                    for(int i=0; i<10; i++) list.add("" + i);
                } catch (Exception e) {}
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                mAdapter.clear();
                mAdapter.addAll(list);
                mAdapter.notifyDataSetChanged();

                mSwipeRefreshLayout.setRefreshing(false);
            }
        }.execute();
    }
}
</code>```

答:
You can use this line for X count of fragments

mViewPager.setOffscreenPageLimit(X);

Body:
I am using a ViewPager with a FragmentStatePagerAdapter that contains 5 pages.

In the first page I have a ListView with items. When I change at the last page of the ViewPager, and I come back to first page, my ListView is empty because the Adapter has been recreated.

Android always calls to the next methods: onAttach(), onCreate(), onCreateView(), onViewCreated(), onActivityCreated(), onStart() and onResume().

I would like don't use ViewPager.setOffscreenPageLimit() methods to avoid that my pages can be destroyed. There are any alternative solution?

The behavior I want is the same that makes Facebook.

What I doing wrong? How I can keep the data in my ListView?

Code of my FragmentStatePageAdapter:

public class AdapterMain extends FragmentStatePagerAdapter {
    List<ChicfyFragment> fragments = new ArrayList<ChicfyFragment>();

    public AdapterMain(FragmentManager fm) {
        super(fm);

        fragments.add(new FragmentShop());
        fragments.add(new FragmentSearch());
        fragments.add(new FragmentSell());
        fragments.add(new FragmentNotification());
        fragments.add(new FragmentProfile());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

Code of the first page of my ViewPager:

public class FragmentShop extends ChicfyFragment implements SwipeRefreshLayout.OnRefreshListener {

    ListView mListView;
    AdapterProductList mAdapter;
    SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_shop, container, false);

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        mListView = (ListView) view.findViewById(R.id.fragment_main_shop_listview);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // setup adapter
        mAdapter = new AdapterProductList((FragmentActivity) getActivity(), new ArrayList());

        // setup listview
        mListView.setAdapter(mAdapter);
        mListView.setDivider(null);

        // setup swipe
        mSwipeRefreshLayout.setColorScheme(R.color.red, R.color.white, R.color.blue, R.color.white);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        new AsyncTask<Void, Void, Void>() {
            List<String> list = new ArrayList<String>();

            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    Thread.sleep(1000);
                    for(int i=0; i<10; i++) list.add("" + i);
                } catch (Exception e) {}
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                mAdapter.clear();
                mAdapter.addAll(list);
                mAdapter.notifyDataSetChanged();

                mSwipeRefreshLayout.setRefreshing(false);
            }
        }.execute();
    }
}


来源: stackexchange

问:
java: maximum execution time within for-loop
I've got the folowing code:

```<code>    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }
</code>```

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

答:
There are many ways of implementing the requested functionality.

One approach could be converting the code in the for to a FutureTask object and submit it to an ExecutorService - even one with just 1 thread, if the loop has to be executed in sequence - e.g.

```<code>ExecutorService executor = Executors.newFixedThreadPool(1);
</code>```

The benefit of having a FutureTask (or any other object implementing the Future interface), is that the cancel() method can be used to make sure that the interrupted iteration will not create any side effects.

For the interrupts, there are numerous alternatives. For example, the javax.swing.Timer class can be used, which fires ActionEvent notifications after the expiry of the timer.

In the above approach, the task (for loop code) will be executed until completion, or until an ActionEvent is received from the timer. In the latter case, a call to cancel() can be used to stop the running task and the next task will start. The counter of the total number of iterations can be maintained at the same place.

For more sophisticated solutions, one can play with the various implementations of ExecutorService and timeout specification options, as in another StackOverflow question.

ContentLicense: CC BY-SA 3.0

Body:
I've got the folowing code:

    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

Body:
There are many ways of implementing the requested functionality.

One approach could be converting the code in the for to a FutureTask object and submit it to an ExecutorService - even one with just 1 thread, if the loop has to be executed in sequence - e.g.

ExecutorService executor = Executors.newFixedThreadPool(1);

The benefit of having a FutureTask (or any other object implementing the Future interface), is that the cancel() method can be used to make sure that the interrupted iteration will not create any side effects.

For the interrupts, there are numerous alternatives. For example, the javax.swing.Timer class can be used, which fires ActionEvent notifications after the expiry of the timer.

In the above approach, the task (for loop code) will be executed until completion, or until an ActionEvent is received from the timer. In the latter case, a call to cancel() can be used to stop the running task and the next task will start. The counter of the total number of iterations can be maintained at the same place.

For more sophisticated solutions, one can play with the various implementations of ExecutorService and timeout specification options, as in another StackOverflow question.


问:
Java repeat part of a program with if and boolean operators
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

```<code>else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;
</code>```

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

答:
The code looks pretty much OK, but your string comparison is incorrect at the end of while loop. Java compares strings with equals() method. Like this:

String_1.equals(String2)

or in your case

if (PlayAgain.equals("nein"))
And also your while loop doesn't have start and end stated w/ curly brackets:

```<code>while (condition){
   //insides
}
</code>```

And also - Your IFs are not correct. Ending with ; will always run next line. Rather have this:

```<code>if  (PlayAgain.equals("nein")){
   boolean inGame = false;
}
</code>```

Body:
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

Body:
The code looks pretty much OK, but your string comparison is incorrect at the end of while loop. Java compares strings with equals() method. Like this:

String_1.equals(String2)

or in your case

if (PlayAgain.equals("nein"))
And also your while loop doesn't have start and end stated w/ curly brackets:

while (condition){
   //insides
}

And also - Your IFs are not correct. Ending with ; will always run next line. Rather have this:

if  (PlayAgain.equals("nein")){
   boolean inGame = false;
}


问:
Height button in e-mails
I have a problem with height button in e-mail.

When I open the html file email in a browser button it is displayed correctly.

html in browser

However, when it comes to e-mail the customer is too narrow.

html in e-mail

My code

Zistiť aktuálny stav objednávky

```

答:
Thanks for tips.

But when I add padding to button, text around too close button :/

img

Title: Height button in e-mails


问:
head is always null in linked list insert
I am trying to insert into my linked list. Here is what I wrote for the same:

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

struct node
{
    int data;
    struct node *next;
};

void show_menu()
{
    printf("\nWhat do you want to do: \n");
    printf("1.Insert \n2.Delete \n3.Show");
    printf("\nEnter your choice: \n");
}

void insert(struct node *head)
{
    int new_numer;
    printf("Enter a number to insert in the linked list: \n");
    scanf("%d",&new_numer);

    if ( head == NULL )
    {
        head = (struct node *)malloc(sizeof(struct node));
        head->data = new_numer;
        head->next = NULL;
    }
    else
    {
        struct node *temp = head;

        struct node *new_node = (struct node *)malloc(sizeof(struct node));

        new_node -> data = new_numer;

        new_node -> next = NULL;

        while( temp -> next != NULL )
        {
            temp = temp -> next;
        }
        temp->next = new_node;
    }
}

void show(struct node *head)
{
    printf("\n The elements in the list are: \n");
    while ( head != NULL )
    {
        printf("%d\n", head->data);
        head = head -> next;
    }
}

int main(int argc, char const *argv[])
{
    int choice;

    struct node *head = NULL;

    while(1)
    {
        show_menu();
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
                insert(head);
                show(head);
            break;

            case 2:
                show(head);
            break;

            case 3:
            break;

            default:
                printf("Don't fuck with me.\n");
        }

    }

    return 0;
}
</code>```

On running the code, I got:

```<code>What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
1
Enter a number to insert in the linked list:
12

 The elements in the list are:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
</code>```

Why there is no element inserted in the list?

If I am moving

```<code>head = (struct node *)malloc(sizeof(struct node));
</code>```

to the main function, I am getting first element as zero and other inserted.

What am I missing here?

答:
Whenever you want to change the value of some variable passed to a function, you need to pass by reference or use pointer of the variable. Same is the case here. The function insert changes the value of your variable head, which is a pointer. So you will have to pass a pointer of the pointer.

Thus, the argument has to be  struct node **head and in the main() function pass &head to insert().

Body:
I am trying to insert into my linked list. Here is what I wrote for the same:

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

struct node
{
    int data;
    struct node *next;
};

void show_menu()
{
    printf("\nWhat do you want to do: \n");
    printf("1.Insert \n2.Delete \n3.Show");
    printf("\nEnter your choice: \n");
}

void insert(struct node *head)
{
    int new_numer;
    printf("Enter a number to insert in the linked list: \n");
    scanf("%d",&new_numer);

    if ( head == NULL )
    {
        head = (struct node *)malloc(sizeof(struct node));
        head->data = new_numer;
        head->next = NULL;
    }
    else
    {
        struct node *temp = head;

        struct node *new_node = (struct node *)malloc(sizeof(struct node));

        new_node -> data = new_numer;

        new_node -> next = NULL;

        while( temp -> next != NULL )
        {
            temp = temp -> next;
        }
        temp->next = new_node;
    }
}

void show(struct node *head)
{
    printf("\n The elements in the list are: \n");
    while ( head != NULL )
    {
        printf("%d\n", head->data);
        head = head -> next;
    }
}

int main(int argc, char const *argv[])
{
    int choice;

    struct node *head = NULL;

    while(1)
    {
        show_menu();
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
                insert(head);
                show(head);
            break;

            case 2:
                show(head);
            break;

            case 3:
            break;

            default:
                printf("Don't fuck with me.\n");
        }

    }

    return 0;
}

On running the code, I got:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
1
Enter a number to insert in the linked list:
12

 The elements in the list are:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:

Why there is no element inserted in the list?

If I am moving

head = (struct node *)malloc(sizeof(struct node));

to the main function, I am getting first element as zero and other inserted.

What am I missing here?


问:
How can I play a single PCM sample in Python?
I intend to pass PCM samples into my audio card in bulk only when I want at speed I choose. The best solution for me in this case would be to have a function that takes one PCM sample, passes it into the audio card and plays it.

Is there a library to do this? I've tried alsaaudio which lets me write PCM data to its alsaaudio.device, but only starts to play once I finish writing data to it (how they accomplished that is a great wonder for me).

If not, can I write a simple function to do that?

答:
According to Wikipedia, a single sample is just a numeric value representing current "amplitude" of the playback device. (https://en.wikipedia.org/wiki/Sampling_(signal_processing))

Standard sampling frequency of audio files starts at 44.1 kHz. This means You have at least 44100 samples per second. So do You really want to play the audio samples one by one? I am not sure, but probably it is not possible them one by one since operation of transfering data to audiodevice coasts much.

I propose You to play packets of samples. Consider sending several thousands of samples. Experiment what value makes sounding smooth and minimizes initial delay.


问:
integer overflow in kernel -- possible?
I have to do integer arithmetic in kernel, specifically I need to increment a size_t object by some delta, and this will happen quite often. So I'm wondering if I need to guard against possible integer overflows in the kernel, and if so, does the kernel provide macros or APIs for this?

答:
integer overflow in kernel — possible?

Yes. It doesn't matter, user space or kernel -- it's just how CPU works.

I'm wondering if I need to guard against possible integer overflows in the kernel

If you think that it can happen and it's not acceptable in your case -- then yes. For signed integers it can even lead to undefined behavior.

does the kernel provide macros or APIs for this

No, there are no ready-to-use functions in kernel for dealing with integer overflows. Well, there are some GCC wrappers for overflow detection... But be sure not to use it. Otherwise Linus Torvalds will come and yell at you, like here :)

Anyway, it's quite easy to detect integer overflows manually, when you really need that. Look here for example. In your case, size_t is unsigned, so you only need to ensure that it doesn't wrap or handle wrapped value: details.

Title: integer overflow in kernel -- possible?


问:
How to map an object inside a string to set using ObjectMapper
I am converting a String to Pojo using Jackson ObjectMapper.

My incoming message:

```<code>{
    "countryCode": "US",
    "skuNumber": "TEST",
    "itemTaxCd": "89999",
    "lastModifiedBy": "xyz"
}
</code>```

Method :

```<code>public void processImsProductTaxEvents(String event) {
    try {
        SkuMasterDTO message = objectMapper.readValue(event, SkuMasterDTO.class);
        log.debug("Received message from IMS", message);
    } catch (Exception e) {
        log.error("Error in Object Mapper converting String to TaxCodeDTO", e);
    }
}
</code>```

Now countryCode is inside CountryDTO inside SkuMasterDTO defined as a Set

```<code>private Set<CountryDTO> countries = new HashSet<>();
</code>```

CountryDTO class

```<code>public class CountryDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull
    @Size(max = 2)
    private String countryCode;
</code>```

I am trying to set the countryCode to the set without changing the input Json. Any suggestions?

答:
You have to define countryCode inside SkuMasterDTO class.

You can add a getter and build a set

```<code>Set<CountryDTO> getCountries(){
    Set<CountryDTO> countries = new HashSet<>();
    countries.add(new CountryDTO(countryCode));
    return countries;
}
</code>```

Or you can prepare set inside set method.

Body:
I am converting a String to Pojo using Jackson ObjectMapper.

My incoming message:

{
    "countryCode": "US",
    "skuNumber": "TEST",
    "itemTaxCd": "89999",
    "lastModifiedBy": "xyz"
}

Method :

public void processImsProductTaxEvents(String event) {
    try {
        SkuMasterDTO message = objectMapper.readValue(event, SkuMasterDTO.class);
        log.debug("Received message from IMS", message);
    } catch (Exception e) {
        log.error("Error in Object Mapper converting String to TaxCodeDTO", e);
    }
}

Now countryCode is inside CountryDTO inside SkuMasterDTO defined as a Set

private Set<CountryDTO> countries = new HashSet<>();

CountryDTO class

public class CountryDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull
    @Size(max = 2)
    private String countryCode;

I am trying to set the countryCode to the set without changing the input Json. Any suggestions?

Body:
You have to define countryCode inside SkuMasterDTO class.

You can add a getter and build a set

Set<CountryDTO> getCountries(){
    Set<CountryDTO> countries = new HashSet<>();
    countries.add(new CountryDTO(countryCode));
    return countries;
}

Or you can prepare set inside set method.


问:
How to connect MySQL Database in django 1.10.6
```<code>import MySQLDB as Database
</code>```

File "c:\pythonprojects\env\lib\site-packages\mysql_python-1.2.2-py3.6-win32.egg\mysqldb__init__py", line 22

```<code> raise ImportError, "This is MySQL Version %s, But _mysql is version %r"
</code>```

SyntaxError: invalid syntax

答:
i) First you have to install the mysql server in your machine, if you already have mysql server up and running then jump to next step.

ii) Create a user in mysql (you can use the root user, but I would suggest create a separate one) you can refer mysql documentation for creating a new user. Let, you have created a user with:- username = testuser , password = testpass@123

iii) Create a database in mysql , let named it testDB

iv) Now you have to install mysqlclient-python, to install it from PyPI you can do so by typing pip install mysqlclient (by default pip the python package manager points python2 series if you are setting up your django project on python3 then you have to use pip3) for more information on how to install mysqlclient-python on your particular OS you can refer this link: https://github.com/PyMySQL/mysqlclient-python

v) Now In settings.py under key DATABASES make these changes:

```<code> DATABASES = {
    'default': {
      'ENGINE': 'django.db.backends.mysql', # for mysql engine
      'NAME': 'testDB',
      'USER': 'testuser',
      'PASSWORD': 'testpass@123',
      'HOST': 'localhost', # if you want to run your project on your localmachine
 }
    }
</code>```

vi) Now change your working directory to your django project directory: " cd yourDjangoProject" and run these django commands

 python manage.py makemigrations

python manage.py migrate

Now I hope that above django commands will run successfully and you would be able to use to your mysql database in your django project.

Body:
import MySQLDB as Database

File "c:\pythonprojects\env\lib\site-packages\mysql_python-1.2.2-py3.6-win32.egg\mysqldb__init__py", line 22

 raise ImportError, "This is MySQL Version %s, But _mysql is version %r"

SyntaxError: invalid syntax

Body:
i) First you have to install the mysql server in your machine, if you already have mysql server up and running then jump to next step.

ii) Create a user in mysql (you can use the root user, but I would suggest create a separate one) you can refer mysql documentation for creating a new user. Let, you have created a user with:- username = testuser , password = testpass@123

iii) Create a database in mysql , let named it testDB

iv) Now you have to install mysqlclient-python, to install it from PyPI you can do so by typing pip install mysqlclient (by default pip the python package manager points python2 series if you are setting up your django project on python3 then you have to use pip3) for more information on how to install mysqlclient-python on your particular OS you can refer this link: https://github.com/PyMySQL/mysqlclient-python

v) Now In settings.py under key DATABASES make these changes:

 DATABASES = {
    'default': {
      'ENGINE': 'django.db.backends.mysql', # for mysql engine
      'NAME': 'testDB',
      'USER': 'testuser',
      'PASSWORD': 'testpass@123',
      'HOST': 'localhost', # if you want to run your project on your localmachine
 }
    }

vi) Now change your working directory to your django project directory: " cd yourDjangoProject" and run these django commands

 python manage.py makemigrations

python manage.py migrate

Now I hope that above django commands will run successfully and you would be able to use to your mysql database in your django project.


问:
Tomcat vs Jetty JNDI Lookup
I use Spring to configure my Java Web App and in my Spring configuration I obtain a datasource via JNDI for Jetty as follows:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/myDataSource" />

but this won't work with Tomcat.  With Tomcat I have to do this:

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDataSource" />

Whats the best way to solve this?  I am already using JNDI as a way to externalize configuration, so I can't externalize my externalized configuration!  At the same time I absolutely loath the idea of having two separate Spring configuration files. HELP!!!

答:
The cleanest way to do it is to configure your configuration. ;)

Use a Spring property place holder.  See

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-placeholderconfigurer

The basic idea is that you just put a placeholder in your spring config with a property, and then it reads matching property from a properties file.  You generate the properties file in your build process.  Ive seen it done where the build tool (ant) reads an environment variable and then creates a properties file appropriate for the environment based of a skeleton file populated with tokens.

ContentLicense: CC BY-SA 2.5

Title: Tomcat vs Jetty JNDI Lookup


问:
Registration with two steps, next fragment by button
I want to handle user registration in my app. I red that using fragments is the best way to handle it.
I prefer using button to move to registration finish fragment, than swype.

I have to send few field to another and finally send all of data by Retrofit.

Any solution?

答:
You can implement a Callback to save the values on your activity.

First create the interface:

```<code>public interface ActivityCallback {

    void sendData(String data1,String data2);

}
</code>```

Then make your activity implements this interface:

```<code>public class MyActivity extends AppCompatActivity implements ActivityCallback{
    private ArrayList<String> arrayData = new ArrayList<>();
    ...
    @Override
    void sendData(String data1, String data2){
        this.arrayData.add(data1);
        this.arrayData.add(data2);
    }
    ...

}
</code>```

Then on your fragment, when you decide to go to the next step:

```<code>public class YourFragment extends Fragment{
    private Button nextButton;
    private EditText text1;
    private EditText text2;
    protected ActivityCallback callback;

    ...

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        callback = (ActivityCallback) context;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ...
        nextButton = (Button) findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.sendData(text1.getText().toString(),text2.getText().toString());
            }
        });
    }
}
</code>```

Body:
You can implement a Callback to save the values on your activity.

First create the interface:

public interface ActivityCallback {

    void sendData(String data1,String data2);

}

Then make your activity implements this interface:

public class MyActivity extends AppCompatActivity implements ActivityCallback{
    private ArrayList<String> arrayData = new ArrayList<>();
    ...
    @Override
    void sendData(String data1, String data2){
        this.arrayData.add(data1);
        this.arrayData.add(data2);
    }
    ...

}

Then on your fragment, when you decide to go to the next step:

public class YourFragment extends Fragment{
    private Button nextButton;
    private EditText text1;
    private EditText text2;
    protected ActivityCallback callback;

    ...

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        callback = (ActivityCallback) context;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ...
        nextButton = (Button) findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.sendData(text1.getText().toString(),text2.getText().toString());
            }
        });
    }
}


问:
Css files in Apache Tapestry 5.3.8 between projects
I have an issue with Tapestry 5.3.8.

Let's assume we hae 3 projects: Gui, Main and Work. Gui project contains custom tapestry componenets. Main and Work are independent projects, both used Gui. I would like to have common css files for Main and Work in Gui.

Gui components are working and they are using Gui css. But is there any way that e.g. Main be using Gui css as well? E.g. I have a page in Main, on which I would like to use css from Gui.

"Context:" unfortunatley is not working... (asset not found)

Any hints would be welcome :)

答:
If gui project is included as dependency for main and work you can use all resources (assets and modules) that has gui project. You can import it via @Import(stylesheet="path/to/asset.css") placed to component or page class. Path can be either relative or absolute.

For tapestry prior to 5.4 to assets can be kept in src/main/resources, for 5.4 and above they should be in META-INF/assets


问:
Change the Textbox height?
How do I change the height of a textbox ?

Neither of the below work:

```<code>this.TextBox1.Size = new System.Drawing.Size(173, 100);
</code>```

or

```<code>this.TextBox1.Size.Height = 100;
</code>```

I wanted to be able to change the single line text box height to fit a font size on it without using multi-line if possible.

答:
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can't just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.</p>

```<code>Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;
</code>```

Title: Change the Textbox height?

Body:
How do I change the height of a textbox ?

Neither of the below work:

this.TextBox1.Size = new System.Drawing.Size(173, 100);

or

this.TextBox1.Size.Height = 100;

I wanted to be able to change the single line text box height to fit a font size on it without using multi-line if possible.

Body:
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can't just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.

Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;


问:
Click radio buttons that are used as links in Chrome?
I am working on a website for work and have two options for radio buttons.  I've used  tags as wrappers for the text and radio button to send the user to a specific webpage of that website.  The radio buttons and text work each perfectly well on Firefox.  On Chrome however, the text works fine as a link.  The radio buttons on the other hand do not work.  The page just refreshes and nothing happens.  I even decided to add a submit so it directs it to one of those pages, with no success as of now.  I tried to replicate the code as close as I could to the code from the website down below.

https://jsfiddle.net/hLph4at4/1/

```<code><form name="frmSite" style="float: left; margin-top: 5px;">
  <a class="loginPg_choices" href="www.youtube.com">
    <input type="radio" name="site" value="1" id="radio_btn_1" style="float: left; clear: both;" />
    <span style="float: left; margin: -2px 0 0 5px;">Take me to youtube.</span>
    <br/>
  </a>
  <a class="loginPg_choices" href="www.google.com">
    <input type="radio" name="site" value="1" id="radio_btn_1" style="float: left; clear: both;" />
    <span style="float: left; margin: -2px 0 0 5px;">Take me to google.</span>
    <br/>
  </a>
  <a href="#" type="submit" value="Submit" title="Login" style="float: right; clear: both;">
    Submit
  </a>
</form>
</code>```

答:
You could add an onclick attribute to your  tag, e.g. onclick="window.location.href = 'https://youtube.com'"

Or, as an updated Fiddle: https://jsfiddle.net/hLph4at4/7/

That will always be called (unless the propagation is stopped), which also includes the radio button.

Body:
I am working on a website for work and have two options for radio buttons.  I've used  tags as wrappers for the text and radio button to send the user to a specific webpage of that website.  The radio buttons and text work each perfectly well on Firefox.  On Chrome however, the text works fine as a link.  The radio buttons on the other hand do not work.  The page just refreshes and nothing happens.  I even decided to add a submit so it directs it to one of those pages, with no success as of now.  I tried to replicate the code as close as I could to the code from the website down below.

https://jsfiddle.net/hLph4at4/1/

<form name="frmSite" style="float: left; margin-top: 5px;">

    <input type="radio" name="site" value="1" id="radio_btn_1" style="float: left; clear: both;" />
    Take me to youtube.

    <input type="radio" name="site" value="1" id="radio_btn_1" style="float: left; clear: both;" />
    Take me to google.

    Submit

</form>


问:
stop button activity if function returns false
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

```<code>register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...
</code>```

答:
Try use something like control Thread.

which if isValidEmail(email) lock some functions.

I try writed code and you paste?

Body:
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...


问:
Why is function being called without clicking on button?
I am trying to move the smaller block 'onclick' of the button in html. But either it is not calling that function or may be it is calling it even before the button is clicked. How to find out and solve to get the required response?</p>

```<code><html>
<head>
<script>
var pos = 0;
//getting box element
var box = document.getElementById("box");
var time = setInterval(move, 10);
document.getElementById("btn1").onclick = move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
};
</script>
</head>
<body>
<h1><p id="p1" style="color:#dd3333">Sample Game</p></h1>
<p id="p2" styel="color:#b5b5b5">Click on the button below</p>
<style>
#container{
width:200px;
height:200px;
background:green;
position:relative;
}
#box{
width:50px;
height:50px;
background:red;
position:absolute;
}
</style>
<div id="container">
<div id="box"></div>
</div>
<br></br>
<button id="btn1">Click Me</button>
</body>

</html>
</code>```

答:
Try this, if you do not need to reuse the function.</p>

```<code>   document.getElementById('btn1').onclick = function()
   {
       alert('you clicked me');
   }
</code>```

Body:
I am trying to move the smaller block 'onclick' of the button in html. But either it is not calling that function or may be it is calling it even before the button is clicked. How to find out and solve to get the required response?

Sample Game

Click on the button below

<button id="btn1">Click Me</button>

Body:
Try this, if you do not need to reuse the function.

   document.getElementById('btn1').onclick = function()
   {
       alert('you clicked me');
   }


问:
Error 1064 - In statement
I am trying to show the average price of products bought by customers from ‘Tucson’, however this query returns null even though there are two customers that have placed orders from Tuscon.

```<code>select AVG(product_price) from product where product_id in
(select product_id from orderline where order_id in
(select order_id from ordertable where cust_id in
(Select cust_id from customer where city = 'Tuscon')))
</code>```

答:
You're using fom instead of from in your query: select order_id fom ordertable where cust_id in

This should be select order_id from ordertable where cust_id in

Title: Error 1064 - In statement

Body:
I am trying to show the average price of products bought by customers from ‘Tucson’, however this query returns null even though there are two customers that have placed orders from Tuscon.

select AVG(product_price) from product where product_id in
(select product_id from orderline where order_id in
(select order_id from ordertable where cust_id in
(Select cust_id from customer where city = 'Tuscon')))


问:
How to add jsonobject in to jsonarray which i want
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}
</code>```

答:
Use dataToSend.put("profile", JSONArrayProfile) to add profile JSONArray to JSONObject.

Here is the working code. Try this:

```<code>try {
        JSONObject dataToSend = new JSONObject();

        // Profile
        JSONArray jsonArrayProfile = new JSONArray();

        // Post 1
        JSONObject jsonObjectPost1 = new JSONObject();
        jsonObjectPost1.put("fbname", "Think Twice Code Once");
        jsonObjectPost1.put("content", "felling full");
        jsonObjectPost1.put("likes", 1);
        jsonObjectPost1.put("comments", 3);

        // Post 2
        JSONObject jsonObjectPost2 = new JSONObject();
        jsonObjectPost2.put("fbname", "Think Twice Code Once");
        jsonObjectPost2.put("content", "felling full");
        jsonObjectPost2.put("likes", 1);
        jsonObjectPost2.put("comments", 3);

        // Add post1, post2 jsonObject to profile jsonArray
        jsonArrayProfile.put(jsonObjectPost1);
        jsonArrayProfile.put(jsonObjectPost2);

        // Add profile jsonArray to jsonObject
        dataToSend.put("profile", jsonArrayProfile);

        Log.d("SUCCESS", "JSON: " + dataToSend.toString());

    } catch (final JSONException e) {
        Log.e("FAILED", "Json build error: " + e.getMessage());
    }
</code>```

OUTPUT:

```<code>        {
            "profile":[
                {
                    "fbname":"Think Twice Code Once",
                    "content":"felling full",
                    "likes":1,
                    "comments":3
                },
                {
                    "fbname":"Think Twice Code Once",
                    "content":"felling full",
                    "likes":1,
                    "comments":3
                }
            ]
        }
</code>```

Body:
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}

Body:
Use dataToSend.put("profile", JSONArrayProfile) to add profile JSONArray to JSONObject.

Here is the working code. Try this:

try {
        JSONObject dataToSend = new JSONObject();

        // Profile
        JSONArray jsonArrayProfile = new JSONArray();

        // Post 1
        JSONObject jsonObjectPost1 = new JSONObject();
        jsonObjectPost1.put("fbname", "Think Twice Code Once");
        jsonObjectPost1.put("content", "felling full");
        jsonObjectPost1.put("likes", 1);
        jsonObjectPost1.put("comments", 3);

        // Post 2
        JSONObject jsonObjectPost2 = new JSONObject();
        jsonObjectPost2.put("fbname", "Think Twice Code Once");
        jsonObjectPost2.put("content", "felling full");
        jsonObjectPost2.put("likes", 1);
        jsonObjectPost2.put("comments", 3);

        // Add post1, post2 jsonObject to profile jsonArray
        jsonArrayProfile.put(jsonObjectPost1);
        jsonArrayProfile.put(jsonObjectPost2);

        // Add profile jsonArray to jsonObject
        dataToSend.put("profile", jsonArrayProfile);

        Log.d("SUCCESS", "JSON: " + dataToSend.toString());

    } catch (final JSONException e) {
        Log.e("FAILED", "Json build error: " + e.getMessage());
    }

OUTPUT:

        {
            "profile":[
                {
                    "fbname":"Think Twice Code Once",
                    "content":"felling full",
                    "likes":1,
                    "comments":3
                },
                {
                    "fbname":"Think Twice Code Once",
                    "content":"felling full",
                    "likes":1,
                    "comments":3
                }
            ]
        }


问:
Dynamic object allocation using array of dynamic pointers - what delete to use?
Can someone help me understand these examples?

I think following code generates an array of 10 pointers that are using automatic memory allocation. Since we are using dynamic memory allocation for objects, pointers to the objects in array are lost when array goes out of scope, but objects remain in the memory until delete is called.

```<code>MyClass* c[10];
c[0] = new MyClass();
</code>```

I guess the following example generates array of ten objects that are using dynamic memory allocation. We have to use delete[] to delete array and objects.

```<code>MyClass* d = new MyClass[10];
</code>```

I guess in the following example we are allocating an array of 50 pointers to object. Do we have to call delete[] or delete or both here?

```<code>MyClass** b = new MyClass*[50];
b[0] = new MyClass();
</code>```

I know that there are better things I could use to manage memory allocation, but I am forced to use new and delete. Can someone check if my understanding is correct and explain what delete I have to use in third example?

Thanks.

答:
delete and delete[] was something that was used extensively in early C++, but has now been rendered almost obsolete by the STL container classes.

The basic idea is that new creates a new instance of a class, on the heap, whilst delete destroys it. However, if you create an array of objects using new[], you need to call delete[] to help the compiler out.

However, you can also have an array of pointers. A pointer is an object in its own right. So, if you have an array of pointers allocated with new[], and then each element is allocated with new, you have to delete the contents of the array, one by one, using plain delete, and then delete the array itself using delete[].

Fortunately, nowaday we use std::vector to store arrays of objects. The vector type handles all the allocation and deletion for you, so you simply have to wait for its lifetime to cease and it delete the objects for you.

Body:
Can someone help me understand these examples?

I think following code generates an array of 10 pointers that are using automatic memory allocation. Since we are using dynamic memory allocation for objects, pointers to the objects in array are lost when array goes out of scope, but objects remain in the memory until delete is called.

MyClass* c[10];
c[0] = new MyClass();

I guess the following example generates array of ten objects that are using dynamic memory allocation. We have to use delete[] to delete array and objects.

MyClass* d = new MyClass[10];

I guess in the following example we are allocating an array of 50 pointers to object. Do we have to call delete[] or delete or both here?

MyClass** b = new MyClass*[50];
b[0] = new MyClass();

I know that there are better things I could use to manage memory allocation, but I am forced to use new and delete. Can someone check if my understanding is correct and explain what delete I have to use in third example?

Thanks.


问:
Absolute imports and entrypoints
So I'm trying to expand my knowledge and skill of Python by moving from small scripts and web development to desktop applications, and am having some trouble understanding entry points with setup.pyand the effect they have on imports. I also don't have a deep understanding of how imports work in Python, which doesn't help.

My confusion comes from looking at example code of a large desktop application, specifically Deluge, a torrenting app written in Python.

Looking at it's code, it seems that all imports for its own modules are absolute, for example:

```<code># deluge/core/core.py
import deluge.common
from deluge.core.eventmanager import EventManager
</code>```

But interestingly all it's entrypoints, as defined in setup.py are also deeper within the program:

```<code># setup.py
entry_points = {
    'console_scripts': [
        'deluge-console = deluge.ui.console:start',
        'deluge-web = deluge.ui.web:start',
        'deluged = deluge.core.daemon_entry:start_daemon'
    ],
    'gui_scripts': [
        'deluge = deluge.ui.ui_entry:start_ui',
        'deluge-gtk = deluge.ui.gtkui:start'
    ],
    'deluge.ui': [
        'console = deluge.ui.console:Console',
        'web = deluge.ui.web:Web',
        'gtk = deluge.ui.gtkui:Gtk',
    ],
}
</code>```

From what I can tell, according to the answer for this SO question, this would not normally be possible. To use absolute imports the program would have to be started from a file in the projects root.

As far as my understanding goes, deluge must be changing its PYTHONPATH somehow, such as with sys.path, however searching the code only finds one instance of it, but it only seems to be related to the documentation, not the actually software code.

So how would one have an entry point for their Python program deeper within the modules, but use absolute imports from the project root? Deluge seems to have done it, but I don't know how, and I would like to do so in my project.

And as a side question, if you know of any other large desktop apps written in Python that I can look at for examples, I'd love it if you told me about it :)

Cheers

答:
All of these are actually doing the exact same thing.

In the entrypoint we have a line like this one

```<code>'deluge-console = deluge.ui.console:start'
</code>```

it is accessing the top-level package name, deluge.  Within that, it goes into the ui module, and a file within there called console.py.  In that file is a definition for 'start'.  After installation, when called from the command line, you will be accessing the installed python modules, and eventually the function you want to run.

In the files themselves we see lines like this.

```<code>from deluge.core.eventmanager import EventManager
</code>```

It goes into the installed package deluge.  Goes into the module 'core' and it will find a file called eventmanager.py.  In that file, I'll guess there is a class called EventManager.

In each case, you are accessing installed packages, and providing information about modules and sub-modules, and then finally the actual objects functions classes whatever that you want.

Title: Absolute imports and entrypoints

Body:
So I'm trying to expand my knowledge and skill of Python by moving from small scripts and web development to desktop applications, and am having some trouble understanding entry points with setup.pyand the effect they have on imports. I also don't have a deep understanding of how imports work in Python, which doesn't help.

My confusion comes from looking at example code of a large desktop application, specifically Deluge, a torrenting app written in Python.

Looking at it's code, it seems that all imports for its own modules are absolute, for example:

# deluge/core/core.py
import deluge.common
from deluge.core.eventmanager import EventManager

But interestingly all it's entrypoints, as defined in setup.py are also deeper within the program:

# setup.py
entry_points = {
    'console_scripts': [
        'deluge-console = deluge.ui.console:start',
        'deluge-web = deluge.ui.web:start',
        'deluged = deluge.core.daemon_entry:start_daemon'
    ],
    'gui_scripts': [
        'deluge = deluge.ui.ui_entry:start_ui',
        'deluge-gtk = deluge.ui.gtkui:start'
    ],
    'deluge.ui': [
        'console = deluge.ui.console:Console',
        'web = deluge.ui.web:Web',
        'gtk = deluge.ui.gtkui:Gtk',
    ],
}

From what I can tell, according to the answer for this SO question, this would not normally be possible. To use absolute imports the program would have to be started from a file in the projects root.

As far as my understanding goes, deluge must be changing its PYTHONPATH somehow, such as with sys.path, however searching the code only finds one instance of it, but it only seems to be related to the documentation, not the actually software code.

So how would one have an entry point for their Python program deeper within the modules, but use absolute imports from the project root? Deluge seems to have done it, but I don't know how, and I would like to do so in my project.

And as a side question, if you know of any other large desktop apps written in Python that I can look at for examples, I'd love it if you told me about it :)

Cheers

Body:
All of these are actually doing the exact same thing.

In the entrypoint we have a line like this one

'deluge-console = deluge.ui.console:start'

it is accessing the top-level package name, deluge.  Within that, it goes into the ui module, and a file within there called console.py.  In that file is a definition for 'start'.  After installation, when called from the command line, you will be accessing the installed python modules, and eventually the function you want to run.

In the files themselves we see lines like this.

from deluge.core.eventmanager import EventManager

It goes into the installed package deluge.  Goes into the module 'core' and it will find a file called eventmanager.py.  In that file, I'll guess there is a class called EventManager.

In each case, you are accessing installed packages, and providing information about modules and sub-modules, and then finally the actual objects functions classes whatever that you want.


问:
How can i write Linq of this query ? ( Linq C#)
Sql Query is :

```<code>select T1.SellerId , count(T2.productId)
 from
tbl_1 T1
left join
tbl_2 T2
on T1.SellerId = T2.sellerId
where VisitorUserId = 'bf8581b04429fdf56c6ebc'
group by T1.SellerId
</code>```

I Need This SQL Query in Linq C#.

答:
Assuming that VisitorUserId is a column of tbl_1 and assuming you use ORM like Entity Framework with navigation properties for foreign keys relationships it should be smth like this:

```<code>context.tbl_1
    .Where(i => i.VisitorUserId = 'bf8581b04429fdf56c6ebc')
    .Select(i => new { SellerId = i.SellerId, ProductCount = i.tbl_2.Count() })
</code>```

Body:
Sql Query is :

select T1.SellerId , count(T2.productId)
 from
tbl_1 T1
left join
tbl_2 T2
on T1.SellerId = T2.sellerId
where VisitorUserId = 'bf8581b04429fdf56c6ebc'
group by T1.SellerId

I Need This SQL Query in Linq C#.

Body:
Assuming that VisitorUserId is a column of tbl_1 and assuming you use ORM like Entity Framework with navigation properties for foreign keys relationships it should be smth like this:

context.tbl_1
    .Where(i => i.VisitorUserId = 'bf8581b04429fdf56c6ebc')
    .Select(i => new { SellerId = i.SellerId, ProductCount = i.tbl_2.Count() })


问:
What does the regex (?<n>a)(b)\2(c) match?
What does this regex match?

```<code>(?<n>a)(b)\2(c)
</code>```

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.

答:
It matches "abbc" for me.  I am using Perl regex flavor and I get "a" as the group 1, the "b" as group 2 and the c as group 3. the \2 refers to the 2nd group which is "b"

(?<n>a)  - A named capture group: the name is "n" the regex is "a"

(b)\2    - Capture group matching "b" then a reference to the second group which is "b"

(c)      - third capture group matching "c"

Body:
What does this regex match?

(?<n>a)(b)\2(c)

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.


问:
BigQuery except double nested column
Hi need to exclude the column hits.latencyTracking.userTimingLabel from my table and select all the other columns. How can I do this in Standard Sql?
I found already a question on a similar problem (BigQuery select * except nested column) but in my case I have a double nested column and I am not able do adapt the code.
thanks

答:
Below are my few cents on this:

I think it answers your exact question / case

#standardSQL
SELECT * REPLACE(
  ARRAY(
    SELECT AS STRUCT hit.*
      REPLACE((SELECT AS STRUCT latencyTracking.* EXCEPT(userTimingLabel)) AS latencyTracking)
    FROM UNNEST(hits) AS hit
  ) AS hits)
FROM `yourProject.yourDataset.yourTable`
```

<p>I tested it on public table as below:   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT * REPLACE(
  ARRAY(
    SELECT AS STRUCT hit.*
      REPLACE((SELECT AS STRUCT page.* EXCEPT(hostname)) AS page)
    FROM UNNEST(hits) AS hit
  ) AS hits)
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`
</code>```

Title: BigQuery except double nested column

Body:
Below are my few cents on this:

I think it answers your exact question / case

#standardSQL
SELECT * REPLACE(
  ARRAY(
    SELECT AS STRUCT hit.*
      REPLACE((SELECT AS STRUCT latencyTracking.* EXCEPT(userTimingLabel)) AS latencyTracking)
    FROM UNNEST(hits) AS hit
  ) AS hits)
FROM `yourProject.yourDataset.yourTable`

I tested it on public table as below:

#standardSQL
SELECT * REPLACE(
  ARRAY(
    SELECT AS STRUCT hit.*
      REPLACE((SELECT AS STRUCT page.* EXCEPT(hostname)) AS page)
    FROM UNNEST(hits) AS hit
  ) AS hits)
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`


问:
SQLSTATE[HY000] [2002] Connection refused within Laravel homestead
Using Mac OS X and Homestead 2.2.1 with Laravel 5.2.

In terminal (within homestead in my project folder) I can do php artisan to see all the available commands. When I try to run php artisan migrate I get a connection error:

SQLSTATE[HY000] [2002] Connection refused

I have setup a Laravel project with these .env settings

```<code>DB_HOST=127.0.0.1
DB_DATABASE=tcv
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

I have also tried localhost for DB_HOST and root for DB_USERNAME and DB_PASSWORD. And all possible variations of these put together!

In Sequel Pro (db management application) I CAN connect with these settings

```<code>Host       127.0.0.1
Username   homestead
Password   secret
Database   tcv
Port       33060
</code>```

But this database is obviously empty, because I cant migrate to it from terminal ...

As far as I can make out it is a configuration issue, since I can connect to it with Sequel Pro. But I have honestly no freaking idea what is setup wrong.

Thanks for the help !!

EDIT

For some reason I get the same SQLSTATE[HY000] [2002] Connection refused error when moving my project to MAMP and running php artisan migrate.

Now I am completely lost  ...

答: I was having this problem. When connecting with Sequel Pro, I need to use 33060 as the port, but in the .env file it has to be 3306. I had 33060 in the .env file. Changed it to 3306 and it worked.

Body:
Using Mac OS X and Homestead 2.2.1 with Laravel 5.2.

In terminal (within homestead in my project folder) I can do php artisan to see all the available commands. When I try to run php artisan migrate I get a connection error:

SQLSTATE[HY000] [2002] Connection refused

I have setup a Laravel project with these .env settings

DB_HOST=127.0.0.1
DB_DATABASE=tcv
DB_USERNAME=homestead
DB_PASSWORD=secret

I have also tried localhost for DB_HOST and root for DB_USERNAME and DB_PASSWORD. And all possible variations of these put together!

In Sequel Pro (db management application) I CAN connect with these settings

Host       127.0.0.1
Username   homestead
Password   secret
Database   tcv
Port       33060

But this database is obviously empty, because I cant migrate to it from terminal ...

As far as I can make out it is a configuration issue, since I can connect to it with Sequel Pro. But I have honestly no freaking idea what is setup wrong.

Thanks for the help !!

EDIT

For some reason I get the same SQLSTATE[HY000] [2002] Connection refused error when moving my project to MAMP and running php artisan migrate.

Now I am completely lost  ...

ContentLicense: CC BY-SA 4.0


问:
Div stuck at bottom of parent
I have the situation in the screenshot below:

I want the div surrounded in blue to be aligned to the top of the parent div (surrounded in black) as the image (surrounded in red) is. How can I accomplish this?

I know top -10px is an option (where 10 is replaced with the exact number) but I need this to work on various screen sizes so finding the exact value that fixes the problem with that method is not an option.

The html for the divs is below:

```<code><div class="product">
    <img class="productImg" src="http://placehold.it/300x240">
    <div class="productTxt">
        <h1>Title</h1>
        <h3>Price</h3>
        <p>Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description </p>
    </div>
</div>
</code>```

And the CSS:

```<code>.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    border: 3px solid red;
}

.productTxt {
    border: 3px solid blue;
    display: inline-block;
}
</code>```

答:
vertical-align: top will align that element to the top.

.product {
  box-sizing: border-box;
  margin: 0px;
  padding: 10px;
  width: 100%;
  height: 330px;
  border: 5px solid black;
}

.productImg {
  width: 240px;
  height: 300px;
  display: inline-block;
  border: 3px solid red;
}

.productTxt {
  border: 3px solid blue;
  display: inline-block;
  vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="product">
  <img class="productImg" src="http://placehold.it/300x240">
  <div class="productTxt">
    <h1>Title</h1>
    <h3>Price</h3>
    <p>Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description </p>
  </div>
</div></code>```

Title: Div stuck at bottom of parent

Body:
I have the situation in the screenshot below:

I want the div surrounded in blue to be aligned to the top of the parent div (surrounded in black) as the image (surrounded in red) is. How can I accomplish this?

I know top -10px is an option (where 10 is replaced with the exact number) but I need this to work on various screen sizes so finding the exact value that fixes the problem with that method is not an option.

The html for the divs is below:

Title

Price

Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description

And the CSS:

.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    border: 3px solid red;
}

.productTxt {
    border: 3px solid blue;
    display: inline-block;
}

Body:
vertical-align: top will align that element to the top.

.product {
  box-sizing: border-box;
  margin: 0px;
  padding: 10px;
  width: 100%;
  height: 330px;
  border: 5px solid black;
}

.productImg {
  width: 240px;
  height: 300px;
  display: inline-block;
  border: 3px solid red;
}

.productTxt {
  border: 3px solid blue;
  display: inline-block;
  vertical-align: top;
}

<div class="product">
  <img class="productImg" src="http://placehold.it/300x240">
  <div class="productTxt">
    <h1>Title</h1>
    <h3>Price</h3>
    <p>Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description </p>
  </div>
</div>


答:
```<code><html>
<head>

</head>
<body>
<h1><p id="p1" style="color:#dd3333">Sample Game</p></h1>
<p id="p2" styel="color:#b5b5b5">Click on the button below</p>
<style>
#container{
width:200px;
height:200px;
background:green;
position:relative;
}
#box{
width:50px;
height:50px;
background:red;
position:absolute;
}
</style>
<div id="container">
<div id="box"></div>
</div>
<br></br>
<button id="btn1">Click Me</button>
<script>

function move(){
if(pos >= 150){
    clearInterval(time);
} else{
    pos += 1;
    box.style.left = pos+"px";
}
}

document.getElementById("btn1").addEventListener("click", move);
var pos = 0;
//getting box element
var box = document.getElementById("box");
var time = setInterval(move, 10);
</script>
</body>

</html>
</code>```

Title: Why is function being called without clicking on button?


问:
Filtering by group and keeping all instances where condition is met
I found an example of something similar

Essentially, I need to keep all items of a group where a user equal to some factor.

For example here is my initial data frame.

```<code>data <- data.frame(user = c("a","a",'b',"b",'c',"c","a","a","a","d","d","d"),
                   invoiceNum =c(1,1,1,1,1,1,2,2,2,2,2,2))
</code>```

I need to keep all invoices which have user d.

The output would look like:

```<code>  user invoiceNum
1    a          2
2    a          2
3    a          2
4    d          2
5    d          2
6    d          2
</code>```

I tried writing the following code but it does not work and gives me the following

```<code>data%>% group_by(invoiceNum)%>%dplyr::filter(user == "d")

    user invoiceNum
  <fctr>      <dbl>
1      d          2
2      d          2
3      d          2
</code>```

答:
Try this in base R:

```<code>data[data$invoiceNum %in% unique(data[data$user=="d",]$invoiceNum),]

#   user invoiceNum
#7     a          2
#8     a          2
#9     a          2
#10    d          2
#11    d          2
#12    d          2
</code>```

So you first find those invoiceNum in which user d is appeared

unique(data[data$user=="d",]$invoiceNum)

and then filter out the rows with those extracted invoiceNum.

EDIT

In case you want to do the same for multiple users:

```<code>usr <- c("d", "a")
data[data$invoiceNum %in% unique(data[data$user %in% usr,]$invoiceNum),]
</code>```

Body:
I found an example of something similar

Essentially, I need to keep all items of a group where a user equal to some factor.

For example here is my initial data frame.

data <- data.frame(user = c("a","a",'b',"b",'c',"c","a","a","a","d","d","d"),
                   invoiceNum =c(1,1,1,1,1,1,2,2,2,2,2,2))

I need to keep all invoices which have user d.

The output would look like:

  user invoiceNum
1    a          2
2    a          2
3    a          2
4    d          2
5    d          2
6    d          2

I tried writing the following code but it does not work and gives me the following

data%>% group_by(invoiceNum)%>%dplyr::filter(user == "d")

    user invoiceNum
  <fctr>      <dbl>
1      d          2
2      d          2
3      d          2

Body:
Try this in base R:

data[data$invoiceNum %in% unique(data[data$user=="d",]$invoiceNum),]

#   user invoiceNum
#7     a          2
#8     a          2
#9     a          2
#10    d          2
#11    d          2
#12    d          2

So you first find those invoiceNum in which user d is appeared

unique(data[data$user=="d",]$invoiceNum)

and then filter out the rows with those extracted invoiceNum.

EDIT

In case you want to do the same for multiple users:

usr <- c("d", "a")
data[data$invoiceNum %in% unique(data[data$user %in% usr,]$invoiceNum),]


问:
C# winforms RichTextBox Coloration
I'm sure it is something stupid I'm missing here but it's been few years since I last used winforms extensively and I can't figure this.
I want to write to a richTextBox with different color every time - like this:

```<code>    private void MainForm_Load(object sender, EventArgs e)
    {
        if (Legend != null)
        {
            foreach (KeyValuePair<string, Color> kvp in Legend)
            {
                writeColor(kvp.Key, richTextBoxLegend, kvp.Value, true);
            }
        }
    }
    private void writeColor(string text, RichTextBox rtb, Color c, bool newLine = false)
    {
        if (newLine && !String.IsNullOrEmpty(rtb.Text)) rtb.Text += Environment.NewLine;
        rtb.Text += text;

        rtb.Select(rtb.Text.Length - text.Length, text.Length);
        rtb.SelectionBackColor = c;
    }
</code>```

So with one pair everything works fine, the colored text is added.
With two everything works fine too, a different color text is added.
With three pairs or more however, I get the entire text colored with the first selection color and just the last line with different color.

答:
Probably works better if you set the color before adding the text:</p>

```<code>private void writeColor(string text, RichTextBox rtb, Color c, bool newLine = false) {
  if (newLine) rtb.AppendText(Environment.NewLine);
  rtb.SelectionBackColor = c;
  rtb.AppendText(text);
}
</code>```

Title: C# winforms RichTextBox Coloration

Body:
I'm sure it is something stupid I'm missing here but it's been few years since I last used winforms extensively and I can't figure this.
I want to write to a richTextBox with different color every time - like this:

    private void MainForm_Load(object sender, EventArgs e)
    {
        if (Legend != null)
        {
            foreach (KeyValuePair<string, Color> kvp in Legend)
            {
                writeColor(kvp.Key, richTextBoxLegend, kvp.Value, true);
            }
        }
    }
    private void writeColor(string text, RichTextBox rtb, Color c, bool newLine = false)
    {
        if (newLine && !String.IsNullOrEmpty(rtb.Text)) rtb.Text += Environment.NewLine;
        rtb.Text += text;

        rtb.Select(rtb.Text.Length - text.Length, text.Length);
        rtb.SelectionBackColor = c;
    }

So with one pair everything works fine, the colored text is added.
With two everything works fine too, a different color text is added.
With three pairs or more however, I get the entire text colored with the first selection color and just the last line with different color.

Body:
Probably works better if you set the color before adding the text:

private void writeColor(string text, RichTextBox rtb, Color c, bool newLine = false) {
  if (newLine) rtb.AppendText(Environment.NewLine);
  rtb.SelectionBackColor = c;
  rtb.AppendText(text);
}


问:
How to fix compile error 'System.ServiceModel.ComIntegration.IParseDisplayName' is inaccessible due to its protection level'
I'm trying to implement a COM component in C# that will be invokable using GetObject and supplying a custom string.  Two components already do this WMI with GetObject("winmgmts:\.\root\cimv2") and LDAP with GetObject("LDAP://example.com/OU=Users,DC=asp,DC=rippe,DC=com").  I'm attracted to this custom activation syntax and would like to replicate it.

It seems I have to implement the Class Com Interface IParseDisplayName.

So I'm trying to do this in C#, I have simple COM object that does simple calculations.  I am stuck trying to implement IParseDisplayName, I get the following error

```<code>`'System.ServiceModel.ComIntegration.IParseDisplayName' is inaccessible due to its protection level`
</code>```

Now I've seen other C# questions with these errors and they are access modifier issues that are solved by upgrading access to public.  But I do not control this interface as it is a system interface.

How do I solve please?  Here the code as it currently stands.

```<code>using Microsoft.Win32;
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Xml;

namespace MonikerParseDisplayName
{
    // In Project Properties->Build->Check 'Interop for COM'
    // In AssemblyInfo.cs [assembly: ComVisible(true)]
    // compile with /unsafe In Project Properties->Build->Check 'Allow unsafe code'

    public interface ICalculator
    {
        double add( double a, double b);
        double mult(double a, double b);
    }
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(ICalculator))]
    //[System.Security.SuppressUnmanagedCodeSecurity]
    public class Calculator : ICalculator, System.ServiceModel.ComIntegration.IParseDisplayName  //, System.Runtime.InteropServices.ComTypes.IMoniker
    {
        public double add( double a, double b)
        {
            return a+b;
        }
        public double mult(double a, double b)
        {
            return a*b;
        }

        //void IParseDisplayName.ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft,
        //    string pszDisplayName, out int pchEaten, out IMoniker ppmkOut)
        void IParseDisplayName.ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft,
            string pszDisplayName, IntPtr pchEaten, IntPtr ppmkOut)
        {
            return new Exception("Not yet implemented");
        }
    }
}
</code>```

EDIT: Also, I think Windows Communication Foundation (WCF) also uses same mechanism here is a link and here a code snippet.  If true then this proves that it can be done in C#!

```<code>Set typedServiceMoniker = GetObject(
"service4:address=http://localhost/ServiceModelSamples/service.svc,      binding=wsHttpBinding,
contractType={9213C6D2-5A6F-3D26-839B-3BA9B82228D3}")
</code>```

答:
You should just be able to re-declare that interface yourself. The interesting thing about COM interfaces in .NET is that you can define them in multiple places and they won't conflict. Just stick this in your code somewhere and use this definition instead of the one in System.ServiceModel.ComIntegration.

```<code>[ComImport]
[SuppressUnmanagedCodeSecurity]
[Guid("0000011a-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IParseDisplayName
{
    void ParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, IntPtr pchEaten, IntPtr ppmkOut);
}
</code>```

Body:
I'm trying to implement a COM component in C# that will be invokable using GetObject and supplying a custom string.  Two components already do this WMI with GetObject("winmgmts:\.\root\cimv2") and LDAP with GetObject("LDAP://example.com/OU=Users,DC=asp,DC=rippe,DC=com").  I'm attracted to this custom activation syntax and would like to replicate it.

It seems I have to implement the Class Com Interface IParseDisplayName.

So I'm trying to do this in C#, I have simple COM object that does simple calculations.  I am stuck trying to implement IParseDisplayName, I get the following error

`'System.ServiceModel.ComIntegration.IParseDisplayName' is inaccessible due to its protection level`

Now I've seen other C# questions with these errors and they are access modifier issues that are solved by upgrading access to public.  But I do not control this interface as it is a system interface.

How do I solve please?  Here the code as it currently stands.

using Microsoft.Win32;
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Xml;

namespace MonikerParseDisplayName
{
    // In Project Properties->Build->Check 'Interop for COM'
    // In AssemblyInfo.cs [assembly: ComVisible(true)]
    // compile with /unsafe In Project Properties->Build->Check 'Allow unsafe code'

    public interface ICalculator
    {
        double add( double a, double b);
        double mult(double a, double b);
    }
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(ICalculator))]
    //[System.Security.SuppressUnmanagedCodeSecurity]
    public class Calculator : ICalculator, System.ServiceModel.ComIntegration.IParseDisplayName  //, System.Runtime.InteropServices.ComTypes.IMoniker
    {
        public double add( double a, double b)
        {
            return a+b;
        }
        public double mult(double a, double b)
        {
            return a*b;
        }

        //void IParseDisplayName.ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft,
        //    string pszDisplayName, out int pchEaten, out IMoniker ppmkOut)
        void IParseDisplayName.ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft,
            string pszDisplayName, IntPtr pchEaten, IntPtr ppmkOut)
        {
            return new Exception("Not yet implemented");
        }
    }
}

EDIT: Also, I think Windows Communication Foundation (WCF) also uses same mechanism here is a link and here a code snippet.  If true then this proves that it can be done in C#!

Set typedServiceMoniker = GetObject(
"service4:address=http://localhost/ServiceModelSamples/service.svc,      binding=wsHttpBinding,
contractType={9213C6D2-5A6F-3D26-839B-3BA9B82228D3}")

Body:
You should just be able to re-declare that interface yourself. The interesting thing about COM interfaces in .NET is that you can define them in multiple places and they won't conflict. Just stick this in your code somewhere and use this definition instead of the one in System.ServiceModel.ComIntegration.

[ComImport]
[SuppressUnmanagedCodeSecurity]
[Guid("0000011a-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IParseDisplayName
{
    void ParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, IntPtr pchEaten, IntPtr ppmkOut);
}


问:
What is the easiest way to sort a NSMutableArray in obj C
I have code as follows:

```<code>-(NSInteger) sortList:(NSMutableArray*)list {
    if(!list)
        return -1;

    //sort list
     [list sortUsingSelector:@selector(compare:)];

   //do other stuff

}
</code>```

My code constantly crashes with *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance

The list is not empty and definitely contains some elements. So I have no idea why it is crashing. I instead tried to use this piece of code instead for comparision

```<code> [list sortUsingComparator:^NSComparisonResult(id  obj1, id obj2) {
            NSNumber *num1 = obj1;
            NSNumber *num2 = obj2;

        if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            }
        else
            return NSOrderedDescending;
    }];
</code>```

Also crashes with the same issue. Any idea what I might be doing wrong here?

答:
This seems to work for me, but it doesn't sort inline, rather returns the sorted list:</p>

```<code>-(NSArray *) sortList:(NSMutableArray*)list {

    NSMutableArray *copy = [list mutableCopy];

    [copy sortUsingComparator:^NSComparisonResult(id  _Nonnull num1, id  _Nonnull num2) {
            if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            }
            else
                return NSOrderedDescending;

    return copy;
}
</code>```

Body:
I have code as follows:

-(NSInteger) sortList:(NSMutableArray*)list {
    if(!list)
        return -1;

    //sort list
     [list sortUsingSelector:@selector(compare:)];

   //do other stuff

}

My code constantly crashes with *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance

The list is not empty and definitely contains some elements. So I have no idea why it is crashing. I instead tried to use this piece of code instead for comparision

 [list sortUsingComparator:^NSComparisonResult(id  obj1, id obj2) {
            NSNumber *num1 = obj1;
            NSNumber *num2 = obj2;

        if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            }
        else
            return NSOrderedDescending;
    }];

Also crashes with the same issue. Any idea what I might be doing wrong here?

Body:
This seems to work for me, but it doesn't sort inline, rather returns the sorted list:

-(NSArray *) sortList:(NSMutableArray*)list {

    NSMutableArray *copy = [list mutableCopy];

    [copy sortUsingComparator:^NSComparisonResult(id  _Nonnull num1, id  _Nonnull num2) {
            if([num1 integerValue] <= [num2 integerValue]){
                return NSOrderedAscending;
            }
            else
                return NSOrderedDescending;

    return copy;
}


问:
Creating a standalone package in java and take some settings from the configuration file
Anyone plz let us know what to do when we have some configuration file which is basically xml.I want to for example give the path to save the image(for my java program) in a folder from some config file (xml in my case).In that case where should the config file be kept.Rt now every thing is converted to jar file when i create a java standalone package.But i want to give some setting from xml file.What to do in that case.How is it possible.This article only provides to create a single jar file for java project but talks nothing about the configuration settings that u can provide from some external source.

Regards
Sagar

答: I'm not sure I fully understand your question, but if it is where to put the XML file with configuration information, you can place your xml file in the same directory as your jar file, and then pass the XML file name and path into the Jar on the command line when calling the Jar.  If you're running it in Windows, this is often done using a shortcut. Then you can get the full path string for the Jar from the main method's String[] arg array that accepts the command parameters.</p>


问:
how to use select sub query in other query MySQL
I am writing a mysql select sub query, that is working fine, it returns 2 column is there way to select only 1 column.
My query is

```<code>SELECT sum(fl.qunt) as qunt,(
    SELECT GROUP_CONCAT( xp.id
    SEPARATOR  ',' )
    FROM prdt AS xp
    LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
    WHERE pf.prdt_fat = p.id
    AND pf.prdt_ch = 6953
    GROUP BY pf.prdt_fat
    LIMIT 0 , 1
    ) AS prdt_chd
    FROM fac_log AS fl
    LEFT JOIN fac AS f ON fl.fac = f.id
    LEFT JOIN prdt AS p ON f.prdt = p.id
    GROUP BY prod_child
    ORDER BY fl.tms DESC
    LIMIT 0 , 1
</code>```

This return two column qunt and prdt_ch.
But i want only column in result qunt.
Is there any way, becuase inner select query is must be used to get correct result.
Main purpose of this query is that i have to use this query as sub query in an other query, in this condition it throws error "operand should contain 1 column"
Thanks in advance

答:
just select qunt using your select  query as a table (t)</p>

```<code>  select qunt from (
        SELECT sum(fl.qunt) as qunt,(
            SELECT GROUP_CONCAT( xp.id
            SEPARATOR  ',' )
            FROM prdt AS xp
            LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
            WHERE pf.prdt_fat = p.id
            AND pf.prdt_ch = 6953
            GROUP BY pf.prdt_fat
            LIMIT 0 , 1
            ) AS prdt_chd
            FROM fac_log AS fl
            LEFT JOIN fac AS f ON fl.fac = f.id
            LEFT JOIN prdt AS p ON f.prdt = p.id
            GROUP BY prod_child
            ORDER BY fl.tms DESC
      LIMIT 0 , 1 ) t
</code>```

Body:
I am writing a mysql select sub query, that is working fine, it returns 2 column is there way to select only 1 column.
My query is

SELECT sum(fl.qunt) as qunt,(
    SELECT GROUP_CONCAT( xp.id
    SEPARATOR  ',' )
    FROM prdt AS xp
    LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
    WHERE pf.prdt_fat = p.id
    AND pf.prdt_ch = 6953
    GROUP BY pf.prdt_fat
    LIMIT 0 , 1
    ) AS prdt_chd
    FROM fac_log AS fl
    LEFT JOIN fac AS f ON fl.fac = f.id
    LEFT JOIN prdt AS p ON f.prdt = p.id
    GROUP BY prod_child
    ORDER BY fl.tms DESC
    LIMIT 0 , 1

This return two column qunt and prdt_ch.
But i want only column in result qunt.
Is there any way, becuase inner select query is must be used to get correct result.
Main purpose of this query is that i have to use this query as sub query in an other query, in this condition it throws error "operand should contain 1 column"
Thanks in advance

Body:
just select qunt using your select  query as a table (t)

  select qunt from (
        SELECT sum(fl.qunt) as qunt,(
            SELECT GROUP_CONCAT( xp.id
            SEPARATOR  ',' )
            FROM prdt AS xp
            LEFT JOIN prdt_fac AS pf ON pf.fk_product_children = xp.rowid
            WHERE pf.prdt_fat = p.id
            AND pf.prdt_ch = 6953
            GROUP BY pf.prdt_fat
            LIMIT 0 , 1
            ) AS prdt_chd
            FROM fac_log AS fl
            LEFT JOIN fac AS f ON fl.fac = f.id
            LEFT JOIN prdt AS p ON f.prdt = p.id
            GROUP BY prod_child
            ORDER BY fl.tms DESC
      LIMIT 0 , 1 ) t


问:
How to test on destroy scope
How to unit testing an $destroy event of a Directive in angularjs?

I have the code in my directive:

```<code>scope.$on('$destroy', function () {
    //clean something
});
</code>```

My test code:

```<code>it('on destroy',function(){
    scope.$destroy();
    scope.$digest();

    //expect everything done?
});
</code>```

Any suggestion!

答:
Here is what I do:

```<code>var destroyed = spyOn(scope, '$destroy').and.callThrough();
scope.$destroy();
expect(destroyed).toHaveBeenCalled();
</code>```

unlike other answers I don't have to create flag variables that only make sense for testing, also, it makes more sense to me to use Jasmine spyOn and callThrough to check if the function $destry is being successfully called.

Title: How to test on destroy scope

Body:
How to unit testing an $destroy event of a Directive in angularjs?

I have the code in my directive:

scope.$on('$destroy', function () {
    //clean something
});

My test code:

it('on destroy',function(){
    scope.$destroy();
    scope.$digest();

    //expect everything done?
});

Any suggestion!

Body:
Here is what I do:

var destroyed = spyOn(scope, '$destroy').and.callThrough();
scope.$destroy();
expect(destroyed).toHaveBeenCalled();

unlike other answers I don't have to create flag variables that only make sense for testing, also, it makes more sense to me to use Jasmine spyOn and callThrough to check if the function $destry is being successfully called.


问:
stop button activity if function returns false
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

```<code>register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...
</code>```

答:
You can disable button and call return  so the below code will not be executed

```<code>      @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

                if(!valid_email){
                    button.setEnabled(false);  //disable button
                    return;
                }else{
                       button.setEnabled(true);
                }
            }
</code>```

Body:
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...

Body:
You can disable button and call return  so the below code will not be executed

      @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

                if(!valid_email){
                    button.setEnabled(false);  //disable button
                    return;
                }else{
                       button.setEnabled(true);
                }
            }