问:
Formatted toString()
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

```<code>public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }
</code>```

The main area I believe will be in the toString() is here:

```<code>// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }
</code>```

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

```<code>Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs
</code>```

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

答:
Your shuffle is similar to, but not quite, a Fisher-Yates shuffle, and will not give you an even distribution of all the permutations of the cards. (Java comes with the Fisher-Yates shuffle in the java.util.Collections class. You can use Collections.shuffle(list) to shuffle a list of objects into random order.

Once you get the suit and rank of each card you can put them into a list:

```<code>    List<Card> cards = new ArrayList<>();

    for (int i = 0; i < 52; i++) {
        String suit = suits[deck[i] / 13];
        String rank = ranks[deck[i] % 13];
        cards.add(new Card(suit, rank));
    }
</code>```

(You will need to import these classes from java.util at the top of your file.)

```<code>import java.util.ArrayList;
import java.util.List;
</code>```

Create a Card class with a toString method:

```<code>public class Card {
    private final String suit;
    private final String rank;

    public Card(String suit, String rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public String getSuit() {
        return suit;
    }

    public String getRank() {
        return rank;
    }

    @Override
    public String toString() {
        return rank + " of " + suit;
    }
}
</code>```

I have included a few things that you don't strictly need. The fields don't have to be final, but it can be useful later on to have objects that are immutable. Once you create a Queen of Diamonds, it doesn't need to ever turn into another card. A good rule of thumb is, don't make objects mutable unless they really need to be. (A mutable card would have fields that weren't final and would have setters for the fields, not just getters.) I also provided getters for the fields, even though we're not using them here yet. And I included the @Override annotation on the toString method, which isn't strictly necessary, but if you include it when you intend to override a method, the compile will warn you if you didn't, which could happen if I accidentally wrote tostring instead of toString.

Now that we have our cards, we can ask them to print themselves out using their toString method:

```<code>for (Card card : cards) {
    System.out.println(card);
}
</code>```

One last note. In your code, you weren't using System.out.printf correctly. If you wanted to use something like that in your toString method, there is a related method in String, String.format, and its use would look like this:

```<code>    @Override
    public String toString() {
        return String.format("%s of %s", rank, suit);
    }
</code>```

Or, when you print the cards, you could use it like this (%n produces a newline):

```<code>for (Card card : cards) {
    System.out.printf("Your card is the %s%n", card);
}
</code>```

Title: Formatted toString()

Body:
I am beginner using the toString() method to return a formatted String. I am printing a deck of cards where each column is the different suit. Does anyone have any ideas? Here is the code I have:

public class DeckOfCards {
  public static void main(String[] args) {
    int[] deck = new int[52];
    //String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
    //String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};

    // Initialize cards
        for (int i = 0; i < deck.length; i++) {
            deck[i] = i;
        }

        // Shuffle the cards
        for (int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

        System.out.println("------------------------------");

        for(int i=0;i<deck.length;i++){
            for(int j=i;j<deck.length;j++){
                if(deck[j]==51-i){
                    int temp = deck[i];
                    deck[i] = deck[j];
                    deck[j] = temp;
                }
            }
        }

        // Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.printf( rank + " of " + suit + "\t");
        }

    }
  }

The main area I believe will be in the toString() is here:

// Display the all the cards
        for (int i = 0; i < 52; i++) {
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println( rank + " of " + suit);
        }

How would I use this in the toString() method and also instantiate an object that can print this toString() method? Thank you for your time. So that it displays in order in a game of bridge I was thinking of an output like this:

Ace of Spades     Ace of Hearts     Ace of Diamonds     Ace of Clubs
...
// And so on until it reaches two of clubs

Do any of these ways print it like such without one being extra spaced or if not what could be modified in the toString() to have it come out like that? Thank you for your time, again.

Body:
Your shuffle is similar to, but not quite, a Fisher-Yates shuffle, and will not give you an even distribution of all the permutations of the cards. (Java comes with the Fisher-Yates shuffle in the java.util.Collections class. You can use Collections.shuffle(list) to shuffle a list of objects into random order.

Once you get the suit and rank of each card you can put them into a list:

    List<Card> cards = new ArrayList<>();

    for (int i = 0; i < 52; i++) {
        String suit = suits[deck[i] / 13];
        String rank = ranks[deck[i] % 13];
        cards.add(new Card(suit, rank));
    }

(You will need to import these classes from java.util at the top of your file.)

import java.util.ArrayList;
import java.util.List;

Create a Card class with a toString method:

public class Card {
    private final String suit;
    private final String rank;

    public Card(String suit, String rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public String getSuit() {
        return suit;
    }

    public String getRank() {
        return rank;
    }

    @Override
    public String toString() {
        return rank + " of " + suit;
    }
}

I have included a few things that you don't strictly need. The fields don't have to be final, but it can be useful later on to have objects that are immutable. Once you create a Queen of Diamonds, it doesn't need to ever turn into another card. A good rule of thumb is, don't make objects mutable unless they really need to be. (A mutable card would have fields that weren't final and would have setters for the fields, not just getters.) I also provided getters for the fields, even though we're not using them here yet. And I included the @Override annotation on the toString method, which isn't strictly necessary, but if you include it when you intend to override a method, the compile will warn you if you didn't, which could happen if I accidentally wrote tostring instead of toString.

Now that we have our cards, we can ask them to print themselves out using their toString method:

for (Card card : cards) {
    System.out.println(card);
}

One last note. In your code, you weren't using System.out.printf correctly. If you wanted to use something like that in your toString method, there is a related method in String, String.format, and its use would look like this:

    @Override
    public String toString() {
        return String.format("%s of %s", rank, suit);
    }

Or, when you print the cards, you could use it like this (%n produces a newline):

for (Card card : cards) {
    System.out.printf("Your card is the %s%n", card);
}


来源: stackexchange

问:
How can i change number Of Rows In each Components

How can i change number Of Rows In each Components
i have this:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}
</code>```

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

答:
You can change the number of rows for each component in the method

```<code>
- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 12 rows for example months
            return 12;
        case 1: // second component has 31 rows for example days

           return 31;
    }
}
</code>```

And about your second question to calculate how many rows(days) will be in the 2nd component, you have to keep a variable to store which month is selected. Base on the selected month you can keep a variable to store how many rows(days) will be in the 2nd component. Let the variable is days which you have to update when the selection of 1st component(month) changed. Then, you have to just changed the previous codes as follows:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 12 rows for example months
            return 12;
        case 1: // second component to show days
           return days;
    }
}
</code>```

Hope you will understand...

ContentLicense: CC BY-SA 3.0

Body:
How can i change number Of Rows In each Components
i have this:

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

Body:
You can change the number of rows for each component in the method

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 12 rows for example months
            return 12;
        case 1: // second component has 31 rows for example days

           return 31;
    }
}

And about your second question to calculate how many rows(days) will be in the 2nd component, you have to keep a variable to store which month is selected. Base on the selected month you can keep a variable to store how many rows(days) will be in the 2nd component. Let the variable is days which you have to update when the selection of 1st component(month) changed. Then, you have to just changed the previous codes as follows:

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 12 rows for example months
            return 12;
        case 1: // second component to show days
           return days;
    }
}

Hope you will understand...

ContentLicense: CC BY-SA 2.5


问:
Authorization when two ASP.NET MVC project instances work in parallel
I have one ASP.NET MVC project. I have several web sites as instances of that project working on the same server, e.g. on 8000 and 8001 ports. When I authorize on 8000, if I've been authorized on 8001, I am automatically logged out on 8001 site, and vice versa. What's the problem? Is it about cookies? What are the possible ways to solve it?</p>

答:
You can specify for each website a custom cookie name by putting into your web.config:

```<code><authtentication model="Forms">
    <forms name="Cookie_8000" loginUrl="urlhere" />
</authentication>
</code>```

ASP.NET MVC is using by default cookies to store information about the signed user. When the websites are in production it should not be a problem unless they run on the same domain

However running on development workspace you can simply specify the cookie name like i said a couple lines before. Is even a better solution to configure that cookie in your Startup.Auth.cs class.

Here is the default configuration when you create a new project:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});
</code>```

You can specify here how the cookie works and should be:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
    CookieName = "website1.cookie" // Specify the cookie name
});
</code>```

Body:
You can specify for each website a custom cookie name by putting into your web.config:

<authtentication model="Forms">
    <forms name="Cookie_8000" loginUrl="urlhere" />
</authentication>

ASP.NET MVC is using by default cookies to store information about the signed user. When the websites are in production it should not be a problem unless they run on the same domain

However running on development workspace you can simply specify the cookie name like i said a couple lines before. Is even a better solution to configure that cookie in your Startup.Auth.cs class.

Here is the default configuration when you create a new project:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

You can specify here how the cookie works and should be:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
    CookieName = "website1.cookie" // Specify the cookie name
});


问:
Query returning records with duplicate data because of the wrong data in one of the columns
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

```<code>ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street
</code>```

答:
if you can't the delete  one of the two
if you don't matter which address  the select return  you can  use an aggregation function for get one row only </p>

```<code>select ID , EMP_ID , EMP_LAST_NAME,   EMP_FIRST_NAME,  min(ADDRESS)
from my_table
group by ID , EMP_ID , EMP_LAST_NAME,   EMP_FIRST_NAME
</code>```

Body:
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street

Body:
if you can't the delete  one of the two
if you don't matter which address  the select return  you can  use an aggregation function for get one row only

select ID , EMP_ID , EMP_LAST_NAME,   EMP_FIRST_NAME,  min(ADDRESS)
from my_table
group by ID , EMP_ID , EMP_LAST_NAME,   EMP_FIRST_NAME


答:
If you want detect what employee have duplicates entries.</p>

```<code>SELECT *
FROM employees
WHERE EMP_ID IN (
     SELECT EMP_ID
     FROM employees
     GROUP BY EMP_ID
     HAVING COUNT(*) > 1
   )
</code>```

Title: Query returning records with duplicate data because of the wrong data in one of the columns

Body:
If you want detect what employee have duplicates entries.

SELECT *
FROM employees
WHERE EMP_ID IN (
     SELECT EMP_ID
     FROM employees
     GROUP BY EMP_ID
     HAVING COUNT(*) > 1
   )


问:
set div data attribute using a code behind value in an aspx page
On an .aspx page I need to set the data-attribute on a addthis div.
The value is an URL that is calculated in the code behind.

```<code><div class="addthis_sharing_toolbox" data-url="CodeBehindValue"></div>
</code>```

Is there a way to do this?

答:
If you choose your div to run at the server (runat="server") such as:

```<code><div id="divMyID" class="addthis_sharing_toolbox" data-url="CodeBehindValue" runat="server"></div>

divMyID.Attributes("data-url") = "http://www.test.com"
</code>```

Body:
On an .aspx page I need to set the data-attribute on a addthis div.
The value is an URL that is calculated in the code behind.

Is there a way to do this?

Body:
If you choose your div to run at the server (runat="server") such as:

<div id="divMyID" class="addthis_sharing_toolbox" data-url="CodeBehindValue" runat="server"></div>

divMyID.Attributes("data-url") = "http://www.test.com"


问:
sql2005- how to run a saves ssis package?
i used management studio to import data from Excel to a SQL table, and on the final step saved the ssis package to the database.

now i want to re-run the saved package on a new excel file i get as a data dump from another system.

the excel file is identical and only the data changes.

how can i re-run the saved ssis package on the new file?

i am just over-writing the old excel file with the new one and expect the ssis job to just pick up everything and run as it did the first time.

答: You should be able to run DTExecUI from the command prompt. From here select the server you want to use and the package. </p>


问:
Can I give an intermediate string to fetch from mysql table which values has that string in middle?
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

```<code>Select *
from orders
where date = "%03%"
</code>```

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

答:
```<code>Select * from orders where month(str_to_date(date,'%d%m%Y')) = 03
</code>```

Body:
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

Select *
from orders
where date = "%03%"

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?


问:
vbc.exe exited with code -2146232797
I am moving a solution with multiple projects to VS 2015. The base project builds just fine in VS 2013. But when I try to build in VS 2015 I get the error below.

C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.VisualBasic.Core.targets(56,5): error MSB6006: "vbc.exe" exited with code -2146232797.

Need help please

答:
I encountered this error when I had a post build event that was throwing an error.
There was no indication this was the problem, just the -2146232797 error.

So check this in the property pages of the project.  Go to Compile -> Build Events ... and check the Post-build event command line field.  I suppose this might happen with a Pre-build event so check that as well.

Title: vbc.exe exited with code -2146232797


答:
date is stored in "Y-m-d" format in MySQL, if you have stored your date as a text then you can try</p>

```<code> SELECT * FROM `orders` WHERE `date` LIKE "__03____";;
</code>```

Title: Can I give an intermediate string to fetch from mysql table which values has that string in middle?

Body:
date is stored in "Y-m-d" format in MySQL, if you have stored your date as a text then you can try

 SELECT * FROM `orders` WHERE `date` LIKE "__03____";;


问:
How to deploy web app directly from Visual Studio 2008?
I used to use discountasp.net and I can use Visual Studio 2008 to "publish" the website directly to the web host. I am using a dedicated server now (well, to be exact, Amazon EC2 Windows), how should I setup the web server so I can deploy the website directly from VS 2008? I tried to setup a FTP server but couldn't get it working.

Thanks!

答:
Here is a tutorial from the official Amazon EC2 deverloper site ("Deploy ASP.NET application to Amazon EC2 like a typical remote server. This tutorial shows you how")

If you need to deploy an ASP.NET
  application directly from Microsoft
  Visual Studio, you can use the Copy
  Web Site Wizard available in Microsoft
  Visual Studio 2005 and later.

The Copy
  Web Site Wizard allows you to deploy
  applications using File Transfer
  Protocol (FTP) or Microsoft Office
  FrontPage Server Extensions. To use
  FTP, you must install the FTP
  component of IIS as well as permit
  ports 20 and 21 through the firewall
  using the ec2-authorize command.

[...]

With Amazon EC2, you can deploy
  ASP.NET applications on dedicated
  Windows instances running in Amazon’s
  data centers. To deploy the
  application, you need to create an
  instance based on an AMI template.
  After creating the instance, you
  access the administrator password,
  then configure a firewall rule and
  Remote Desktop to the server. To
  provide persistent storage, you create
  an EBS volume, and then set up IIS and
  the ASP.NET application. You can
  deploy ASP.NET applications to the
  server with tools like Visual Studio
  or through FTP.

From: Deploying ASP.NET Applications on Amazon EC2 (via archive.org)

LastEditorDisplayName: splattne

OwnerDisplayName: splattne


问:
How can I implement a makefile-style algorithm in python
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

```<code>            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output
</code>```

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

```<code>a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready
</code>```

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

```<code>blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}
</code>```

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

答: For code in many languages, including Python try these Rosetta code links: Topological sort, and Topological sort/Extracted top item.</p>

Body:
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.


问:
Thread-safe List<T> property
I want an implementation of List<T> as a property which can be used thread-safely without any doubt.

Something like this:

```<code>private List<T> _list;

private List<T> MyT
{
    get { // return a copy of _list; }
    set { _list = value; }
}
</code>```

It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.

How to implement a thread-safe collection property?

答:
Even accepted answer is ConcurrentBag, I don't think it's real replacement of list in all cases, as Radek's comment to the answer says: "ConcurrentBag is unordered collection, so unlike List it does not guarantee ordering. Also you cannot access items by index".

So if you use .NET 4.0 or higher, a workaround could be to use ConcurrentDictionary with integer TKey as array index and TValue as array value. This is recommended way of replacing list in Pluralsight's C# Concurrent Collections course. ConcurrentDictionary solves both problems mentioned above: index accessing and ordering (we can not rely on ordering as it's hash table under the hood, but current .NET implementation saves order of elements adding).

Title: Thread-safe List<T> property

Body:
I want an implementation of List<T> as a property which can be used thread-safely without any doubt.

Something like this:

private List<T> _list;

private List<T> MyT
{
    get { // return a copy of _list; }
    set { _list = value; }
}

It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.

How to implement a thread-safe collection property?


问:
How to enter different types parameters into function to return one type data?
l want to enter different types parameters (such as:int,float,double,long) into function to return one type data(such as:string).

Here l just wanna make a function to turn different type data to be string data.

答:
It sounds like you want to:

Convert number types to data types

Return multiple strings

No. 1 can be achieved with:

```<code>double num = 123.123123;
return "" + num;
//or
int i = 5;
String s = "int: " + i;
return s;
</code>```

Number datatypes will "convert themselves" to strings on their own if you use "" + num, using it's built in .toString() method.

Based on your comment you want to return multiple strings of each input parameter.

public static getString (int i,float f,double d)---->return string i, string f, string d

In order to return multiple strings from one variable, typically we would split the function into several functions:

```<code>String intToString(int n) {
  return " + n;
}

String intToFloat(float n) {
  return "" + n;
}

String intToDouble(double n) {
  return "" + n;
}
</code>```

Alternatively if you really want to jam all these different functionalities into one function this can be achieved with an Array.

```<code>public static void main (String[] args) {
    int i = 1;
    //the f on the end of this number is an implicit cast
    float f = 5.5f;
    double d = 6.123;
    String[] a = getString(i,f,d);
    System.out.println("int: " + a[0]);
    System.out.println("float: " + a[1]);
    System.out.println("double: " + a[2]);
}
public static String[] getString(int i, float f, double d) {
    int numberOfReturns = 3;
    String[] a = new String[numberOfReturns];
    a[0] = "" + i;
    a[1] = "" + f;
    a[2] = "" + d;
    return a;
}
</code>```

Body:
It sounds like you want to:

Convert number types to data types

Return multiple strings

No. 1 can be achieved with:

double num = 123.123123;
return "" + num;
//or
int i = 5;
String s = "int: " + i;
return s;

Number datatypes will "convert themselves" to strings on their own if you use "" + num, using it's built in .toString() method.

Based on your comment you want to return multiple strings of each input parameter.

public static getString (int i,float f,double d)---->return string i, string f, string d

In order to return multiple strings from one variable, typically we would split the function into several functions:

String intToString(int n) {
  return " + n;
}

String intToFloat(float n) {
  return "" + n;
}

String intToDouble(double n) {
  return "" + n;
}

Alternatively if you really want to jam all these different functionalities into one function this can be achieved with an Array.

public static void main (String[] args) {
    int i = 1;
    //the f on the end of this number is an implicit cast
    float f = 5.5f;
    double d = 6.123;
    String[] a = getString(i,f,d);
    System.out.println("int: " + a[0]);
    System.out.println("float: " + a[1]);
    System.out.println("double: " + a[2]);
}
public static String[] getString(int i, float f, double d) {
    int numberOfReturns = 3;
    String[] a = new String[numberOfReturns];
    a[0] = "" + i;
    a[1] = "" + f;
    a[2] = "" + d;
    return a;
}


问:
flex vs flexGrow vs flexShrink vs flexBasis in React Native?
I finally upgraded react native to 0.42 which includes the introduction of flexGrow, flexShrink, and  flexBasis and the change (or fix) of how flex is rendered.

I keep getting errors like:

View was rendered with explicitly set width/height but with a 0 flexBasis. (This might be fixed by changing flex: to flexGrow:) View:

Can someone explain the difference between flex: 1 vs flexGrow: 1.  If I apply one or the other to a View it seems to do different things but shouldn't it do the same?

答:
Here's some test code to consider:

```<code>render() {
    return <View style={{flex: 1,backgroundColor: "cornflowerblue"}}>
        <View style={{backgroundColor: "chartreuse"}}><Text>Nothing (17px)</Text></View>

        <View style={{flex: 0, backgroundColor: "yellow"}}><Text>flex: 0 (17px)</Text></View>

        <View style={{flex: 0, flexBasis: 10, backgroundColor: "brown"}}><Text>flex: 0, flexBasis: 10 (10px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, backgroundColor: "orange"}}><Text>flex: 0, flexGrow: 1 (97px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, backgroundColor: "tan"}}><Text>flex: 0, flexShrink: 1 (17px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, flexBasis: 10, backgroundColor: "purple"}}><Text>flex: 0, flexGrow: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, flexBasis: 10, backgroundColor: "gray"}}><Text>flex: 0, flexShrink: 1, flexBasis: 10 (10px with 7px hidden below the next element)</Text></View>

        <View style={{flex: 1, backgroundColor: "blue"}}><Text>flex: 1 (80px)</Text></View>

        <View style={{flex: 1, flexBasis: 10, backgroundColor: "cornsilk"}}><Text>flex: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, backgroundColor: "red"}}><Text>flex: 1, flexGrow: 1 (80px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, backgroundColor: "green"}}><Text>flex: 1, flexShrink: 1 (80px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, flexBasis: 10, backgroundColor: "aqua"}}><Text>flex: 1, flexGrow: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, flexBasis: 10, backgroundColor: "pink"}}><Text>flex: 1, flexShrink: 1, flexBasis: 10 (90px)</Text></View>
    </View>;
}
</code>```

Here's a screenshot of the above code:

Added width and height:

```<code>render() {
    return <View style={{flex: 1,backgroundColor: "cornflowerblue"}}>
        <View style={{flex: 0, backgroundColor: "orange"}}><Text>flex: 0 (17px)</Text></View>
        <View style={{flex: 0, width: 700, height: 20, backgroundColor: "yellow"}}><Text>flex: 0, width: 700, height: 20 (20px)</Text></View>

        <View style={{flex: 0, flexBasis: 10, width: 700, height: 20, backgroundColor: "brown"}}><Text>flex: 0, flexBasis: 10, width: 700, height: 20 (10px with 7px hidden below the next element)</Text></View>
        <View style={{flex: 0, flexGrow: 1, width: 700, height: 20, backgroundColor: "orange"}}><Text>flex: 0, flexGrow: 1, width: 700, height: 20 (90px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, width: 700, height: 20, backgroundColor: "tan"}}><Text>flex: 0, flexShrink: 1, width: 700, height: 20 (20px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "purple"}}><Text>flex: 0, flexGrow: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "gray"}}><Text>flex: 0, flexShrink: 1, flexBasis: 10, width: 700, height: 20 (10px with 7px hidden below the next element)</Text></View>

        <View style={{flex: 1, backgroundColor: "orange"}}><Text>flex: 1 (70px)</Text></View>
        <View style={{flex: 1, width: 700, height: 20, backgroundColor: "blue"}}><Text>flex: 1, width: 700, height: 20 (70px)</Text></View>

        <View style={{flex: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "cornsilk"}}><Text>flex: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, width: 700, height: 20, backgroundColor: "red"}}><Text>flex: 1, flexGrow: 1, width: 700, height: 20 (70px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, width: 700, height: 20, backgroundColor: "green"}}><Text>flex: 1, flexShrink: 1, width: 700, height: 20 (70px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "aqua"}}><Text>flex: 1, flexGrow: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "pink"}}><Text>flex: 1, flexShrink: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
    </View>;
}
</code>```

Here's a screenshot of the above code:

flex: 0 (default)

flex: 0

Element takes the size of contents.  According to the documentation it should be sized by setting width and height props but it seems to fit to contents if those aren't set.

flex: 0, flexBasis: {{px}}

Element takes the size given by flexBasis

flex: 0, flexGrow: 1

With flex: 0 and flexGrow: 1; it's the same as adding the size of the contents (in the example above it's a ) to the size of an element that's set to flex: 1. It's similar to flex: 1, flexBasis: 10 except instead of adding a number of pixels you're adding the size of the content.

flex: 0, flexShrink: 1

With flex: 0 and flexShrink: 1, the element seems to take the size of the content, in other words it's the same as just flex: 0. I'll bet there are situations where it would be bigger than the content but I haven't see that yet.

flex: 0, flexGrow: 1, flexBasis: {{px}}

This is the same as flex: 0, flexGrow: 1 except instead of adding the content size to a flex: 1 element it adds the given number of pixels.

flex: 0, flexShrink: 1, flexBasis: {{px}}

This is the same as flex: 0, flexBasis: {{px}}.

flex: 0, height: {{px}}

With flex: 0, height is treated just like flexBasis.  If there is both a height and flexBasis are set, height is ignored.

flex: 1

flex: 1

Element takes available space. See Layout Props documentation for more details

flex: 1, flexBasis: {{px}}

With flex: 1 and flexBasis: {{px}}; the value of flexBasis is added to the element's size. In other words, it's like taking a flex: 1 element and adding on the number of pixels set by flexBasis. So if a flex: 1 element is 50px, and you add flexBasis: 20 the element will now be 70px.

flex: 1, flexGrow: 1

ignored

flex: 1, flexShrink: 1

ignored

flex: 1, flexGrow: 1, flexBasis: {{px}}

This is the same as flex: 1, flexBasis: {{px}} since flexGrow is ignored.

flex: 1, flexShrink: 1, flexBasis: {{px}}

This is the same as flex: 1, flexBasis: {{px}} since flexShrink is ignored.

flex: 1, height: {{px}}

With flex: 1, height is ignored.  Use flexBasis instead.

Here are my observations:

Trouble Shooting Tip: Make sure the parent view(s) are giving the children room to grow/shrink.  Notice the flex: 1 on the parent view, without it, all the children don't display as you'd expect.

Trouble Shooting Tip: Don't use Hot Reloading when testing these values, it can display elements incorrectly after it's reloaded a few times.  I recommend enabling Live Reload or using command + r (a lot).

The default flex value is flex: 0.  If you don't add a flex style value it defaults to 0.

Trouble Shooting Tip: if you're tryign to figure out why something isn't displaying like you think it should, start with the (most) parent element and make sure it's giving enough space to it's children to do what they need to do.  In other words, try setting it to flex:1 and see if that helps, then go to the next child and repeat.

It seems like width is always considered with flexDirection: "column" no matter the other flex props.  The same applies for height with flexDirection: "row".

After running these test, in general I would use flexBasis over height since flexBasis trumps height.

Body:
Here's some test code to consider:

render() {
    return <View style={{flex: 1,backgroundColor: "cornflowerblue"}}>
        <View style={{backgroundColor: "chartreuse"}}><Text>Nothing (17px)</Text></View>

        <View style={{flex: 0, backgroundColor: "yellow"}}><Text>flex: 0 (17px)</Text></View>

        <View style={{flex: 0, flexBasis: 10, backgroundColor: "brown"}}><Text>flex: 0, flexBasis: 10 (10px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, backgroundColor: "orange"}}><Text>flex: 0, flexGrow: 1 (97px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, backgroundColor: "tan"}}><Text>flex: 0, flexShrink: 1 (17px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, flexBasis: 10, backgroundColor: "purple"}}><Text>flex: 0, flexGrow: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, flexBasis: 10, backgroundColor: "gray"}}><Text>flex: 0, flexShrink: 1, flexBasis: 10 (10px with 7px hidden below the next element)</Text></View>

        <View style={{flex: 1, backgroundColor: "blue"}}><Text>flex: 1 (80px)</Text></View>

        <View style={{flex: 1, flexBasis: 10, backgroundColor: "cornsilk"}}><Text>flex: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, backgroundColor: "red"}}><Text>flex: 1, flexGrow: 1 (80px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, backgroundColor: "green"}}><Text>flex: 1, flexShrink: 1 (80px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, flexBasis: 10, backgroundColor: "aqua"}}><Text>flex: 1, flexGrow: 1, flexBasis: 10 (90px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, flexBasis: 10, backgroundColor: "pink"}}><Text>flex: 1, flexShrink: 1, flexBasis: 10 (90px)</Text></View>
    </View>;
}

Here's a screenshot of the above code:

Added width and height:

render() {
    return <View style={{flex: 1,backgroundColor: "cornflowerblue"}}>
        <View style={{flex: 0, backgroundColor: "orange"}}><Text>flex: 0 (17px)</Text></View>
        <View style={{flex: 0, width: 700, height: 20, backgroundColor: "yellow"}}><Text>flex: 0, width: 700, height: 20 (20px)</Text></View>

        <View style={{flex: 0, flexBasis: 10, width: 700, height: 20, backgroundColor: "brown"}}><Text>flex: 0, flexBasis: 10, width: 700, height: 20 (10px with 7px hidden below the next element)</Text></View>
        <View style={{flex: 0, flexGrow: 1, width: 700, height: 20, backgroundColor: "orange"}}><Text>flex: 0, flexGrow: 1, width: 700, height: 20 (90px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, width: 700, height: 20, backgroundColor: "tan"}}><Text>flex: 0, flexShrink: 1, width: 700, height: 20 (20px)</Text></View>
        <View style={{flex: 0, flexGrow: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "purple"}}><Text>flex: 0, flexGrow: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 0, flexShrink: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "gray"}}><Text>flex: 0, flexShrink: 1, flexBasis: 10, width: 700, height: 20 (10px with 7px hidden below the next element)</Text></View>

        <View style={{flex: 1, backgroundColor: "orange"}}><Text>flex: 1 (70px)</Text></View>
        <View style={{flex: 1, width: 700, height: 20, backgroundColor: "blue"}}><Text>flex: 1, width: 700, height: 20 (70px)</Text></View>

        <View style={{flex: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "cornsilk"}}><Text>flex: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, width: 700, height: 20, backgroundColor: "red"}}><Text>flex: 1, flexGrow: 1, width: 700, height: 20 (70px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, width: 700, height: 20, backgroundColor: "green"}}><Text>flex: 1, flexShrink: 1, width: 700, height: 20 (70px)</Text></View>
        <View style={{flex: 1, flexGrow: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "aqua"}}><Text>flex: 1, flexGrow: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
        <View style={{flex: 1, flexShrink: 1, flexBasis: 10, width: 700, height: 20, backgroundColor: "pink"}}><Text>flex: 1, flexShrink: 1, flexBasis: 10, width: 700, height: 20 (80px)</Text></View>
    </View>;
}

Here's a screenshot of the above code:

flex: 0 (default)

flex: 0

Element takes the size of contents.  According to the documentation it should be sized by setting width and height props but it seems to fit to contents if those aren't set.

flex: 0, flexBasis: {{px}}

Element takes the size given by flexBasis

flex: 0, flexGrow: 1

With flex: 0 and flexGrow: 1; it's the same as adding the size of the contents (in the example above it's a ) to the size of an element that's set to flex: 1. It's similar to flex: 1, flexBasis: 10 except instead of adding a number of pixels you're adding the size of the content.

flex: 0, flexShrink: 1

With flex: 0 and flexShrink: 1, the element seems to take the size of the content, in other words it's the same as just flex: 0. I'll bet there are situations where it would be bigger than the content but I haven't see that yet.

flex: 0, flexGrow: 1, flexBasis: {{px}}

This is the same as flex: 0, flexGrow: 1 except instead of adding the content size to a flex: 1 element it adds the given number of pixels.

flex: 0, flexShrink: 1, flexBasis: {{px}}

This is the same as flex: 0, flexBasis: {{px}}.

flex: 0, height: {{px}}

With flex: 0, height is treated just like flexBasis.  If there is both a height and flexBasis are set, height is ignored.

flex: 1

flex: 1

Element takes available space. See Layout Props documentation for more details

flex: 1, flexBasis: {{px}}

With flex: 1 and flexBasis: {{px}}; the value of flexBasis is added to the element's size. In other words, it's like taking a flex: 1 element and adding on the number of pixels set by flexBasis. So if a flex: 1 element is 50px, and you add flexBasis: 20 the element will now be 70px.

flex: 1, flexGrow: 1

ignored

flex: 1, flexShrink: 1

ignored

flex: 1, flexGrow: 1, flexBasis: {{px}}

This is the same as flex: 1, flexBasis: {{px}} since flexGrow is ignored.

flex: 1, flexShrink: 1, flexBasis: {{px}}

This is the same as flex: 1, flexBasis: {{px}} since flexShrink is ignored.

flex: 1, height: {{px}}

With flex: 1, height is ignored.  Use flexBasis instead.

Here are my observations:

Trouble Shooting Tip: Make sure the parent view(s) are giving the children room to grow/shrink.  Notice the flex: 1 on the parent view, without it, all the children don't display as you'd expect.

Trouble Shooting Tip: Don't use Hot Reloading when testing these values, it can display elements incorrectly after it's reloaded a few times.  I recommend enabling Live Reload or using command + r (a lot).

The default flex value is flex: 0.  If you don't add a flex style value it defaults to 0.

Trouble Shooting Tip: if you're tryign to figure out why something isn't displaying like you think it should, start with the (most) parent element and make sure it's giving enough space to it's children to do what they need to do.  In other words, try setting it to flex:1 and see if that helps, then go to the next child and repeat.

It seems like width is always considered with flexDirection: "column" no matter the other flex props.  The same applies for height with flexDirection: "row".

After running these test, in general I would use flexBasis over height since flexBasis trumps height.


问:
Problems connecting to an Access database from a Java application
I am trying to connect to an existing Access database using UCanAccess from NetBeans IDE 8.2 but am getting an error I can't figure out...

This is the code at this time (pStrFile is the full path to an existing Access file):

```<code>try {
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        String database = "jdbc:ucanaccess:" + pStrFile;
        Connection conn = DriverManager.getConnection(database);
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
</code>```

This is stack trace I'm getting...

```<code>java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at DevGSLibData01.DevGSLibData01.DoConnect(DevGSLibData01.java:28)
at DevGSLibData01.DevGSLibData01.main(DevGSLibData01.java:18)
</code>```

I have also added all the required libraries in the UCanAccess package:

答: Despite being listed in the Libraries of the NetBeans project, "ucanaccess-4.0.1.jar" was not found in the build path (classpath) when the application was launched. Removing "ucanaccess-4.0.1.jar" from the project Libraries and re-adding it seems to have solved the problem.</p>

Body:
I am trying to connect to an existing Access database using UCanAccess from NetBeans IDE 8.2 but am getting an error I can't figure out...

This is the code at this time (pStrFile is the full path to an existing Access file):

try {
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        String database = "jdbc:ucanaccess:" + pStrFile;
        Connection conn = DriverManager.getConnection(database);
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

This is stack trace I'm getting...

java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at DevGSLibData01.DevGSLibData01.DoConnect(DevGSLibData01.java:28)
at DevGSLibData01.DevGSLibData01.main(DevGSLibData01.java:18)

I have also added all the required libraries in the UCanAccess package:


问:
How to sort directly from the relationship in sqlalchemy
I have a one to many relationship between table company and table employee like companyA.employees and employeeA.company. And now I want to find the youngest employee in companyA.

I know I can achieve it by one of the followings

use order_by when declaring the relationship

use order_by with query

But does sqlalchemy have a builtin feature to sort it from companyA.employees directly without the penalty to get all employees from companyA first? Thanks!

答:
I think what you're asking is this:</p>

```<code>session.query(Employee).with_parent(companyA, Company.employees).order_by(Employee.age).limit(1)
</code>```

Body:
I think what you're asking is this:

session.query(Employee).with_parent(companyA, Company.employees).order_by(Employee.age).limit(1)


问:
Vue.js and Computed Properties
Here is my code:

```<code>  <div id="app">
  <p>here is the message: {{message}}</p>
  <p>{{a}}</p>
  <p>here is the reversed message: {{reversedMessage}}</p>

</div>
<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {
      message: 'Hello',
      a: 1,
    },
    computed: {
      reversedMessage: function () {
        this.a += 1;
         return this.message.split('').reverse().join('')
      }
    }
  });
</script>
</code>```

First of all, why the value for a becomes 2? I thought since a is before the computed property, it's value should be 1 and then in the next line and after calling the function for computed property, it's value would be 2. Could you please explain this to me?

and second: in the chrome DevTools, when I change the value for a (like below):

```<code>vm.a = 8
</code>```

in the p tag, the value for a becomes a+1. Why?! So every time I change the value for a in the DevTools Console, the value for a in p tag become a+1! why the function for computed property is called and changes the value for a?

答:
Because a is defined in your data, it becomes a reactive property. That means anytime you change it, the change will be reflected everywhere. That's why a == 2 initially in your text, because you change it in your computed value.

Secondly, if you change a in the devtools console, the reversedMessage will be recalculated because you reference a inside it. So the sequence is

Change a in devtools.

reversedMessage is triggered, because a is referenced inside it.

a now equals a + 1

Vue updates the DOM referencing a,
{{a}}

In summary, a is going to display it's current value everywhere you display it, and changing a via the console, causes a to be incremented.

Title: Vue.js and Computed Properties

Body:
Here is my code:

here is the message: {{message}}

{{a}}

here is the reversed message: {{reversedMessage}}

First of all, why the value for a becomes 2? I thought since a is before the computed property, it's value should be 1 and then in the next line and after calling the function for computed property, it's value would be 2. Could you please explain this to me?

and second: in the chrome DevTools, when I change the value for a (like below):

vm.a = 8

in the p tag, the value for a becomes a+1. Why?! So every time I change the value for a in the DevTools Console, the value for a in p tag become a+1! why the function for computed property is called and changes the value for a?

Body:
Because a is defined in your data, it becomes a reactive property. That means anytime you change it, the change will be reflected everywhere. That's why a == 2 initially in your text, because you change it in your computed value.

Secondly, if you change a in the devtools console, the reversedMessage will be recalculated because you reference a inside it. So the sequence is

Change a in devtools.

reversedMessage is triggered, because a is referenced inside it.

a now equals a + 1

Vue updates the DOM referencing a,  <p>{{a}}</p>

In summary, a is going to display it's current value everywhere you display it, and changing a via the console, causes a to be incremented.


问:
Jenkins: Command /usr/bin/codesign failed with exit code 1
I am able to archive ios project using below commands

cordova build ios --device --debug

and

cordova build ios --device --release

But when i try to do same from jenkins i am getting below error.

```<code>11:08:01 SecKey API returned: -25308, (null)/Users/Jenkins/Library/Developer/Xcode/DerivedData/GRC_Pulse-ebufuetkmalmfxbiegclmzuryhrm/Build/Intermediates/ArchiveIntermediates/GRC Pulse/InstallationBuildProductsLocation/Applications/GRC Pulse.app: unknown error -1=ffffffffffffffff
11:08:01 Command /usr/bin/codesign failed with exit code 1
11:08:01
11:08:01 ** ARCHIVE FAILED **
11:08:01
11:08:01
11:08:01 The following build commands failed:
11:08:01    CodeSign /Users/Jenkins/Library/Developer/Xcode/DerivedData/GRC_Pulse-ebufuetkmalmfxbiegclmzuryhrm/Build/Intermediates/ArchiveIntermediates/GRC\ Pulse/InstallationBuildProductsLocation/Applications/GRC\ Pulse.app
11:08:01 (1 failure)
11:08:01 Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/cordova/build-debug.xcconfig,-workspace,GRC Pulse.xcworkspace,-scheme,GRC Pulse,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,GRC Pulse.xcarchive,archive,CONFIGURATION_BUILD_DIR=/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/build/sharedpch
</code>```

答:
You should unlock your keychain before running the command when using ssh (connection from the master to a slave)

security unlock-keychain -p "" ${keychain}

Take a look on this link for more details

Body:
I am able to archive ios project using below commands

cordova build ios --device --debug

and

cordova build ios --device --release

But when i try to do same from jenkins i am getting below error.

11:08:01 SecKey API returned: -25308, (null)/Users/Jenkins/Library/Developer/Xcode/DerivedData/GRC_Pulse-ebufuetkmalmfxbiegclmzuryhrm/Build/Intermediates/ArchiveIntermediates/GRC Pulse/InstallationBuildProductsLocation/Applications/GRC Pulse.app: unknown error -1=ffffffffffffffff
11:08:01 Command /usr/bin/codesign failed with exit code 1
11:08:01
11:08:01 ** ARCHIVE FAILED **
11:08:01
11:08:01
11:08:01 The following build commands failed:
11:08:01    CodeSign /Users/Jenkins/Library/Developer/Xcode/DerivedData/GRC_Pulse-ebufuetkmalmfxbiegclmzuryhrm/Build/Intermediates/ArchiveIntermediates/GRC\ Pulse/InstallationBuildProductsLocation/Applications/GRC\ Pulse.app
11:08:01 (1 failure)
11:08:01 Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/cordova/build-debug.xcconfig,-workspace,GRC Pulse.xcworkspace,-scheme,GRC Pulse,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,GRC Pulse.xcarchive,archive,CONFIGURATION_BUILD_DIR=/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/Jenkins/projects/grc-pulse-hybrid-custom/platforms/ios/build/sharedpch


问:
Text on the left with line on the right in HTML and CSS
How can I create the following in HTML and CSS?

Some Text ---------------------------------------------------------

The line should be solid, no dotted

Thanks

答:
You can achieve what you want with the following code snippet:

```<code><style>
    .inline-hr {
        display: inline-block;
        width: 50px;
        vertical-align: middle;
    }
</style>
Some text <hr class="inline-hr"/>
</code>```

Then you can make the line as wide as you want by adjusting the width in style.

Body:
You can achieve what you want with the following code snippet:

<style>
    .inline-hr {
        display: inline-block;
        width: 50px;
        vertical-align: middle;
    }
</style>
Some text <hr class="inline-hr"/>

Then you can make the line as wide as you want by adjusting the width in style.


问:
Ruby on Rails Tutorial section 10.4.2 test fail
After completing listing Listing 10.40 and running rspec /spec/controllers/users_controller_spec.rb, I got 1 failure for section (all other tests in 'destroy' section are passed)

```<code>describe "DELETE 'destroy'" do

  before(:each) do
    @user = Factory(:user)
  end

  describe "as a non-signed-in user" do
    it "should deny access" do
      delete :destroy, :id => @user
      response.should redirect_to(signin_path)
    end
  end
end
</code>```

Here is the console output:

```<code>Failures:
  1) UsersController DELETE 'destroy' as a non-signed-in user should deny access
     Failure/Error: delete :destroy, :id => @user
     undefined method `admin?' for nil:NilClass
     # ./app/controllers/users_controller.rb:66:in `admin_user'
     # ./spec/controllers/users_controller_spec.rb:282:in `block (4 levels) in <top (required)>'
</code>```

I can't figure out whether there is an error in the tutorial's code or I made a mistake somewhere.

答:
Can't tell for sure, but it seems like this is the part of the tutorial code that's failing

```<code><% if current_user.admin? %>
</code>```

If nobody is signed in on that page, current_user is nil (I assume) and therefore can't have a admin? method called.

Try replacing that with

```<code><% if current_user && current_user.admin? %>
</code>```

(and replace other current_user logic on the page similarly).

Does that work?

Also, if you comment out this test, does the same test with a logged in user pass?

After looking into it more closely, disregard the above: the test is failing because in true TDD-style the test is written before the code. Sot the steps are:

Write the test

Watch it fail

Write the code to make the test pass

Watch the test pass

You haven't yet written the code to check is a user is admin. Write the code in section Listing 10.41 in the tutorial, and the test should pass.

However, it might be necessary to put

```<code>def admin_user
  redirect_to(root_path) unless current_user && current_user.admin?
end
</code>```

In the before filter (notice we check for a current_user before seeing if he's an admin).

Body:
After completing listing Listing 10.40 and running rspec /spec/controllers/users_controller_spec.rb, I got 1 failure for section (all other tests in 'destroy' section are passed)

describe "DELETE 'destroy'" do

  before(:each) do
    @user = Factory(:user)
  end

  describe "as a non-signed-in user" do
    it "should deny access" do
      delete :destroy, :id => @user
      response.should redirect_to(signin_path)
    end
  end
end

Here is the console output:

Failures:
  1) UsersController DELETE 'destroy' as a non-signed-in user should deny access
     Failure/Error: delete :destroy, :id => @user
     undefined method `admin?' for nil:NilClass
     # ./app/controllers/users_controller.rb:66:in `admin_user'
     # ./spec/controllers/users_controller_spec.rb:282:in `block (4 levels) in <top (required)>'

I can't figure out whether there is an error in the tutorial's code or I made a mistake somewhere.

Body:
Can't tell for sure, but it seems like this is the part of the tutorial code that's failing

<% if current_user.admin? %>

If nobody is signed in on that page, current_user is nil (I assume) and therefore can't have a admin? method called.

Try replacing that with

<% if current_user && current_user.admin? %>

(and replace other current_user logic on the page similarly).

Does that work?

Also, if you comment out this test, does the same test with a logged in user pass?

After looking into it more closely, disregard the above: the test is failing because in true TDD-style the test is written before the code. Sot the steps are:

Write the test

Watch it fail

Write the code to make the test pass

Watch the test pass

You haven't yet written the code to check is a user is admin. Write the code in section Listing 10.41 in the tutorial, and the test should pass.

However, it might be necessary to put

def admin_user
  redirect_to(root_path) unless current_user && current_user.admin?
end

In the before filter (notice we check for a current_user before seeing if he's an admin).


问:
sql query search by anchored field
Help me plz, this sql not workin

```<code> SELECT *
 FROM p_pl
 WHERE (`sid` = '25' AND `value` = 'zxc')
   AND (`sшd` = '22' AND `value` = 'cxz')
</code>```

this sql workin:

```<code> SELECT * FROM p_pl WHERE (`sid` = '25' AND `value` = 'zxc')
</code>```

How make query? thanks

答:
Maybe you want OR ?

```<code>SELECT *
FROM p_pl
WHERE (`sid` = '25' AND `value` = 'zxc')
   OR (`sid` = '22' AND `value` = 'cxz')
</code>```

Title: sql query search by anchored field

Body:
Help me plz, this sql not workin

 SELECT *
 FROM p_pl
 WHERE (`sid` = '25' AND `value` = 'zxc')
   AND (`sшd` = '22' AND `value` = 'cxz')

this sql workin:

 SELECT * FROM p_pl WHERE (`sid` = '25' AND `value` = 'zxc')

How make query? thanks

Body:
Maybe you want OR ?

SELECT *
FROM p_pl
WHERE (`sid` = '25' AND `value` = 'zxc')
   OR (`sid` = '22' AND `value` = 'cxz')


答:
Should you be using 'OR' instead of 'AND'?</p>

```<code> SELECT *
 FROM p_pl
 WHERE (`sid` = '25' AND `value` = 'zxc')
   OR(`sшd` = '22' AND `value` = 'cxz')
</code>```

Title: sql query search by anchored field

Body:
Should you be using 'OR' instead of 'AND'?

 SELECT *
 FROM p_pl
 WHERE (`sid` = '25' AND `value` = 'zxc')
   OR(`sшd` = '22' AND `value` = 'cxz')


答:
I think you want to use OR:

```<code>select *
from p_pl
where  (`sid` = '25' and `value` = 'zxc')
    or (`sid` = '22' and `value` = 'cxz')
</code>```

Or simply:

```<code>select *
from p_pl
where (sid, value) in(('25','zxc'),('22','cxz'));
</code>```

Title: sql query search by anchored field

Body:
I think you want to use OR:

select *
from p_pl
where  (`sid` = '25' and `value` = 'zxc')
    or (`sid` = '22' and `value` = 'cxz')

Or simply:

select *
from p_pl
where (sid, value) in(('25','zxc'),('22','cxz'));


问:
Spring Boot DevTools not working in Eclipse
I built an application using Spring, JPA, MySQL and Web. I developed a static page in template folder normally and it works.

But, when I change something on static page, I can't reload it with changes. Then, I open the pom.xml and added

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
</code>```

I restart the application, but, still not working when I make some changes on the static page.

Is there something more to do?

My POM.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.engsoftware</groupId>
    <artifactId>cobranca</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Cobranca</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
According to the Spring Boot docs:

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.

http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart

Templates and static assets do not need a restart.  Most likely your browser is caching the templates and using the cached version instead of requesting the new template.  If you clear the browsers cache, you should see the updated template.

EDIT:

Depending on your template technology you're using, you will need to set a property in your properties file to disable the template cache

```<code># Thymeleaf
spring.thymeleaf.cache = false

#FreeMarker
spring.freemarker.cache = false

#Groovy
spring.groovy.template.cache = false
</code>```

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html#howto-reload-static-content

Body:
I built an application using Spring, JPA, MySQL and Web. I developed a static page in template folder normally and it works.

But, when I change something on static page, I can't reload it with changes. Then, I open the pom.xml and added

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

I restart the application, but, still not working when I make some changes on the static page.

Is there something more to do?

My POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.engsoftware</groupId>
    <artifactId>cobranca</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Cobranca</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
According to the Spring Boot docs:

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.

http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-restart

Templates and static assets do not need a restart.  Most likely your browser is caching the templates and using the cached version instead of requesting the new template.  If you clear the browsers cache, you should see the updated template.

EDIT:

Depending on your template technology you're using, you will need to set a property in your properties file to disable the template cache

# Thymeleaf
spring.thymeleaf.cache = false

#FreeMarker
spring.freemarker.cache = false

#Groovy
spring.groovy.template.cache = false

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html#howto-reload-static-content


问:
Is there a way to access the iteration number in Postman REST Client?
I'm using postman for API testing. I'm running a large number of tests and I want to print the iteration number to the console on some of them. Is there a way to get the iteration number as an environment-like variable?</p>

答: It is possible now! You can access the iteration variable, in the same way you access other variables like responseBody.


问:
Performance of a trimming function
My old Trimming function:

```<code>string TailTrimString (const string & sSource, const char *chars) {
  size_t End = sSource.find_last_not_of(chars);
  if (End == string::npos) {
    // only "*chars"
    return "";
  }
  if (End == sSource.size() - 1) {
    // noting to trim
    return sSource;
  }
  return sSource.substr(0, End + 1);
}
</code>```

Instead of it I've decided to use boost, and wrote the trivial:

```<code>string TailTrimString (const string & sSource, const char *chars) {
    return boost::algorithm::trim_right_copy_if(sSource,boost::algorithm::is_any_of(chars));
}
</code>```

And I was amazed to find out that the new function works much slower.
I've done some profiling, and I see that the function is_any_of is very slow.

Is it possible that boost's implementation works slower than my quite straightforward implementation? Is there anything I should use instead of is_any_of in order to improve the performance?

I also found a discussion on this matter in the boost's mailing list, but I am still not sure on how can I improve the performance of my code.

The boost version that I use is 1.38, which is quite old, but I guess this code didn't change too much since then.

Thank you.

答:
it possible that boost's implementation works slower than my quite straightforward implementation?

Of course.

Is there anything I should use instead of is_any_of in order to improve the performance?

Yeah -- your original code.  You said nothing about it having a defect, or the reason why you re-implemented it using boost.  If there was no defect in the original code, then there was no valid reason to chuck the original implementation.

Introducing Boost to a codebase makes sense.  It brings a lot of functionality that can be helpful.  But gutting a function for the sole purpose of using a new technology is a big rookie mistake.

EDIT:

In response to your comment:

I still don't understand, why boost's performance is worse.

A hand-crafted function that is designed to do one specific job for one specific application will often be faster than a generic solution.  Boost is a great library of generic tools that can save a lot of programming and a lot of defects.  But its generic.  You may only need to trim your string in a specific way, but Boost handles everything.  That takes time.

Title: Performance of a trimming function

Body:
My old Trimming function:

string TailTrimString (const string & sSource, const char *chars) {
  size_t End = sSource.find_last_not_of(chars);
  if (End == string::npos) {
    // only "*chars"
    return "";
  }
  if (End == sSource.size() - 1) {
    // noting to trim
    return sSource;
  }
  return sSource.substr(0, End + 1);
}

Instead of it I've decided to use boost, and wrote the trivial:

string TailTrimString (const string & sSource, const char *chars) {
    return boost::algorithm::trim_right_copy_if(sSource,boost::algorithm::is_any_of(chars));
}

And I was amazed to find out that the new function works much slower.
I've done some profiling, and I see that the function is_any_of is very slow.

Is it possible that boost's implementation works slower than my quite straightforward implementation? Is there anything I should use instead of is_any_of in order to improve the performance?

I also found a discussion on this matter in the boost's mailing list, but I am still not sure on how can I improve the performance of my code.

The boost version that I use is 1.38, which is quite old, but I guess this code didn't change too much since then.

Thank you.


问:
MultiThreaded Libcurl
I need to execute parallel HTTP requests using Libcurl.

From what I understand I need to create a new handle for each thread
and use CURLOPT_WRITEDATA with some kind of Thread Local Storage.
Does the multi interface makes this task a little easier?

I'm also using cookies, does using CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR will make
Libcurl load the cookie file for each thread?

答:
Also check out libcurl share interface. It was designed for this purpose, i.e. to share data between requests:

You can have multiple easy handles share data between them. Have them
  update and use the same cookie database, DNS cache, TLS session cache!
  This way, each single transfer will take advantage from data updates
  made by the other transfer(s). The sharing interface, however, does
  not share active or persistent connections between different easy
  handles.

Title: MultiThreaded Libcurl


问:
Command line - Convert any string into an identifier?
Often I'd like to be able to take a string at the command line (bash), and convert it into an identifier. Usually this is for use in a filename, branch name, or variable name, and I prefer that it:

has no spaces in it

has no special characters in it

So for example, I could take a string like so:

bug fix for #PROJECT1 item 52, null pointer

and convert it to something like this:

bug_fix_for_PROJECT1_item_52__null_pointer

I'm open to solutions in any language, e.g. bash, node, perl, python, etc, but prefer languages that are installed by default on most linux/osx machines.

答:
Did you try tr?</p>

```<code>echo 'bug fix for #PROJECT1 item 52, null pointer' |  tr -d [:punct:] | tr '[:blank:]' '_'

bug_fix_for_PROJECT1_item_52_null_pointer
</code>```

Body:
Did you try tr?

echo 'bug fix for #PROJECT1 item 52, null pointer' |  tr -d [:punct:] | tr '[:blank:]' '_'

bug_fix_for_PROJECT1_item_52_null_pointer


问:
Refreshing Dagger 2 instance from Android Application class
I have a set of @Singleton and @Provides method in my module class for the purpose of creating Singleton instance throughout the application. Everything works fine except few bottle neck scenarios like as follows:

STEP 1. I am creating a Retrofit instance from OKHttpClient with Auth token in it to make a authenticated api calls each time (Auth token retrieval and insertion is handled through SharedPreferences). But the problem starts at the time of relaunching the activity after when i logout the application by clearing databases and shared preferences values.

STEP 2. After logout, am making an another request to fetch auth tokens and inserting into SharedPreferences again for future use.

STEP 3: Now if i proceed with the rest of api calls, the previous instance of the Dagger @Singleton and @Provides method remains same unless and until if i relaunch the app by clearing it from the recent task. (New auth token is not updated)

Fixes Needed:

How to trigger the Dagger provider methods forcibly to trigger or revoke it again?

Is there any method to refresh the application class data as similar behaviour like when the app relaunches.?

Please find my Dagger 2 architecture used in my project:

NetworkModule.java (Dagger Module class)

```<code>@Module
public class NetworkModule {

  private Context context;

    public NetworkModule(Application app) {
        this.context = app;
    }

    @Provides
    @Named("network.context")
    Context providesContext() {
        return context;
    }

 @Singleton
    @Provides
    OkHttpClient providesOkHttpClient(@Named("network.context")final Context context) {

        final UserProfile userProfile = GsonUtils.createPojo(SharedPrefsUtils.getString(Constants.SHARED_PREFS.USERS_PROFILE, "",context), UserProfile.class);

        Logger.i(userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "----OAuth token empty---");

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .header("Api-Version", "application/vnd.addo-v1+json")
                        .header("Access-Token", userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "")
                        .header("App-Version", Utils.getVersionName(context))
                        .header("Device-Platform","android")
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }

        });

        return httpClient.build();
    }

    @Provides
    @Named(Constants.INJECTION.BASE_URL)
    String providebaseURL() {
        return Constants.URL.BASE_URL;
    }

    @Singleton
    @Provides

    Retrofit providesRetrofit(@Named("network.context")Context context, @Named(Constants.INJECTION.BASE_URL) String baseURL, OkHttpClient okHttpClient) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }

@Singleton
    @Provides
     NetworkApiService providesNetworkApiService(Retrofit retrofit){
        return retrofit.create(NetworkApiService.class);
    }

 @Singleton
    @Provides
    ProjectPresenter providesProjectPresenter(NetworkApiService networkApiService){
        return new ProjectPresenterImpl(networkApiService);
    }

}
</code>```

AppComponent.java (Dagger component class)

```<code>@Singleton
@Component(modules =  {NetworkModule.class})
public interface AppComponent {

    //ACtivity
    void inject(AuthenticationActivity authenticationActivity);

    void inject(MainActivity mainActivity);

    //Fragments

    void inject(ProjectsListFragment projectsListFragment);

}
</code>```

Application.java (Class used to create Dagger component)

```<code>   public class Application extends Application {

        private AppComponent appComponent ;

        @Override
        public void onCreate() {
            super.onCreate();

            Realm.init(this);

            ButterKnife.setDebug(BuildConfig.DEBUG);

            appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).networkModule(new NetworkModule(this)).build();

        }

        public AppComponent getAppComponent() {
            return appComponent;
        }

    }
</code>```

Kindly help me with your suggestions or tips to resolve this weird behaviour of Dagger 2. Any kind of solutions will be much helpful to me since I am completely stuck up with this for the past 6 days. I am clueless and perplexed because my complete architecture is built on top of this. Please forgive me for typos and corrections. Ping me if there are any clarifications required regarding the same. Thanks in advance.

答:
Your problem is @Singleton. @Singleton tells Dagger that you want Dagger to cache and manage the instance state, and you don't get a lot of control to refresh instances when you do so. However, you're welcome to drop @Singleton from the @Provides method and manage that instance yourself. Without a scope, Dagger will call your @Provides method for every single injection request, which will let you return whichever instance you wish and invalidate it when appropriate.

See this answer from yesterday, which incidentally is also about a Retrofit-serving NetworkModule and the scope troubles with refreshing instances on an AppComponent. (You two aren't on the same team, are you?)

```<code>/* Module fields */
OkHttpClient myClient;
String lastToken;

/** Not @Singleton */
@Provides
OkHttpClient providesOkHttpClient(
    @Named("network.context") final Context context, TokenManager tokenManager) {
  String currentToken = getToken();  // gets token from UserProfile

  if (myInstance == null || !lastToken.equals(currentToken)) {
    lastToken = currentToken;
    myInstance = createInstance(currentToken);  // As you have it above

  }
  return myInstance;
}
</code>```

There is not a way to automatically refresh shared preferences, but with the above create-on-demand structure, you could easily write it to a data holder whenever the current token changes. At that point, it may make sense to extract a NetworkManager as in the other answer.

Body:
I have a set of @Singleton and @Provides method in my module class for the purpose of creating Singleton instance throughout the application. Everything works fine except few bottle neck scenarios like as follows:

STEP 1. I am creating a Retrofit instance from OKHttpClient with Auth token in it to make a authenticated api calls each time (Auth token retrieval and insertion is handled through SharedPreferences). But the problem starts at the time of relaunching the activity after when i logout the application by clearing databases and shared preferences values.

STEP 2. After logout, am making an another request to fetch auth tokens and inserting into SharedPreferences again for future use.

STEP 3: Now if i proceed with the rest of api calls, the previous instance of the Dagger @Singleton and @Provides method remains same unless and until if i relaunch the app by clearing it from the recent task. (New auth token is not updated)

Fixes Needed:

How to trigger the Dagger provider methods forcibly to trigger or revoke it again?

Is there any method to refresh the application class data as similar behaviour like when the app relaunches.?

Please find my Dagger 2 architecture used in my project:

NetworkModule.java (Dagger Module class)

@Module
public class NetworkModule {

  private Context context;

    public NetworkModule(Application app) {
        this.context = app;
    }

    @Provides
    @Named("network.context")
    Context providesContext() {
        return context;
    }

 @Singleton
    @Provides
    OkHttpClient providesOkHttpClient(@Named("network.context")final Context context) {

        final UserProfile userProfile = GsonUtils.createPojo(SharedPrefsUtils.getString(Constants.SHARED_PREFS.USERS_PROFILE, "",context), UserProfile.class);

        Logger.i(userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "----OAuth token empty---");

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json")
                        .header("Api-Version", "application/vnd.addo-v1+json")
                        .header("Access-Token", userProfile != null && !TextUtils.isEmpty(userProfile.getAuth_token()) ? userProfile.getAuth_token() : "")
                        .header("App-Version", Utils.getVersionName(context))
                        .header("Device-Platform","android")
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }

        });

        return httpClient.build();
    }

    @Provides
    @Named(Constants.INJECTION.BASE_URL)
    String providebaseURL() {
        return Constants.URL.BASE_URL;
    }

    @Singleton
    @Provides

    Retrofit providesRetrofit(@Named("network.context")Context context, @Named(Constants.INJECTION.BASE_URL) String baseURL, OkHttpClient okHttpClient) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }

@Singleton
    @Provides
     NetworkApiService providesNetworkApiService(Retrofit retrofit){
        return retrofit.create(NetworkApiService.class);
    }

 @Singleton
    @Provides
    ProjectPresenter providesProjectPresenter(NetworkApiService networkApiService){
        return new ProjectPresenterImpl(networkApiService);
    }

}

AppComponent.java (Dagger component class)

@Singleton
@Component(modules =  {NetworkModule.class})
public interface AppComponent {

    //ACtivity
    void inject(AuthenticationActivity authenticationActivity);

    void inject(MainActivity mainActivity);

    //Fragments

    void inject(ProjectsListFragment projectsListFragment);

}

Application.java (Class used to create Dagger component)

   public class Application extends Application {

        private AppComponent appComponent ;

        @Override
        public void onCreate() {
            super.onCreate();

            Realm.init(this);

            ButterKnife.setDebug(BuildConfig.DEBUG);

            appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).networkModule(new NetworkModule(this)).build();

        }

        public AppComponent getAppComponent() {
            return appComponent;
        }

    }

Kindly help me with your suggestions or tips to resolve this weird behaviour of Dagger 2. Any kind of solutions will be much helpful to me since I am completely stuck up with this for the past 6 days. I am clueless and perplexed because my complete architecture is built on top of this. Please forgive me for typos and corrections. Ping me if there are any clarifications required regarding the same. Thanks in advance.

Body:
Your problem is @Singleton. @Singleton tells Dagger that you want Dagger to cache and manage the instance state, and you don't get a lot of control to refresh instances when you do so. However, you're welcome to drop @Singleton from the @Provides method and manage that instance yourself. Without a scope, Dagger will call your @Provides method for every single injection request, which will let you return whichever instance you wish and invalidate it when appropriate.

See this answer from yesterday, which incidentally is also about a Retrofit-serving NetworkModule and the scope troubles with refreshing instances on an AppComponent. (You two aren't on the same team, are you?)

/* Module fields */
OkHttpClient myClient;
String lastToken;

/** Not @Singleton */
@Provides
OkHttpClient providesOkHttpClient(
    @Named("network.context") final Context context, TokenManager tokenManager) {
  String currentToken = getToken();  // gets token from UserProfile

  if (myInstance == null || !lastToken.equals(currentToken)) {
    lastToken = currentToken;
    myInstance = createInstance(currentToken);  // As you have it above

  }
  return myInstance;
}

There is not a way to automatically refresh shared preferences, but with the above create-on-demand structure, you could easily write it to a data holder whenever the current token changes. At that point, it may make sense to extract a NetworkManager as in the other answer.