问:
Is it possible to access children/parent widgets from a given widget, in a Flutter test?
I'm writing unit and integration tests for Flutter. Is it possible to access children/parent widgets from a given widget?</p>

答:
Yes, you can use find.descendant and Element.ancestorWidgetOfExactType.

Examples:

```<code>// Finds a RichText widget that a descendant (child/grand-child/etc) of a
// tab widget with text "Tab 1"
find.descendant(of: find.text('Tab 1'), matching: find.byType(RichText));

// Finds a parent widget of type MyParentWidget.
tester.element(find.byType(MyChildWidget))
  .ancestorWidgetOfExactType(MyParentWidget);
</code>```

Body:
Yes, you can use find.descendant and Element.ancestorWidgetOfExactType.

Examples:

// Finds a RichText widget that a descendant (child/grand-child/etc) of a
// tab widget with text "Tab 1"
find.descendant(of: find.text('Tab 1'), matching: find.byType(RichText));

// Finds a parent widget of type MyParentWidget.
tester.element(find.byType(MyChildWidget))
  .ancestorWidgetOfExactType(MyParentWidget);


来源: stackexchange

问:
How can I cluster/group the output of a supervised classifier?
This is a model of my problem:

I start with a list of datapoints

```<code>X = ['Apple','Peach','Orange','Dog','Elephant','Fox','Cat','Mango']
</code>```

Then I have the output of a supervised classifier which leads me to classes such as:

```<code>Y = clf.predict(X) # 'FRUIT','FRUIT','FRUIT','ANIMAL','0','ANIMAL','ANIMAL','FRUIT'
</code>```

Even in a perfect world where my classifier has no FN I'd like to be able to group my classes into higher order classes

```<code>Z = cluster(Y)  # 'LIST_OF_FRUITS','LIST_OF_ANIMALS','LIST_OF_FRUITS'
</code>```

I'm struggling to find something which can do something like this, with or without labeled examples because without defining how large the group I cant see how this could be done.

Also an extension of this which is what I'm actually trying to solve is what if the desired groupings are containing of a few classes of different types not just a concurrent list of "FRUIT" but say a "DINNER" which often will be 0+ "MEATS", 0+ "VEG" etc the ideal solution would be one that knows the atypical dinner and could deduce/correct false negatives and find a dinner grouping from the classified data i.e:

```<code>Y = ['MEAT','0','0','0','0','MEAT','0','VEG','MEAT'] -> ['DINNER'] (1 instance)
</code>```

Some bag of words encoding of the problem should work but I don't get how to partition the output of classifier 1 such that partitions aren't forced to be a certain size

Is there something that I could use for this?

答:
It sounds like you just need to use a classifier with multiple outputs dimensions. This is supported at the low levels, but you won't be able to use a lot of the convenience functions.

For example, I have a model that is a Bag-Of-Words which outputs 4 vectors - classifications - for the Bag-Of-Words vecor list (sentence) at once. They are all linearly independent outputs.

The alternative is to create multiple models for each output dimension.

ContentLicense: CC BY-SA 3.0

Body:
This is a model of my problem:

I start with a list of datapoints

X = ['Apple','Peach','Orange','Dog','Elephant','Fox','Cat','Mango']

Then I have the output of a supervised classifier which leads me to classes such as:

Y = clf.predict(X) # 'FRUIT','FRUIT','FRUIT','ANIMAL','0','ANIMAL','ANIMAL','FRUIT'

Even in a perfect world where my classifier has no FN I'd like to be able to group my classes into higher order classes

Z = cluster(Y)  # 'LIST_OF_FRUITS','LIST_OF_ANIMALS','LIST_OF_FRUITS'

I'm struggling to find something which can do something like this, with or without labeled examples because without defining how large the group I cant see how this could be done.

Also an extension of this which is what I'm actually trying to solve is what if the desired groupings are containing of a few classes of different types not just a concurrent list of "FRUIT" but say a "DINNER" which often will be 0+ "MEATS", 0+ "VEG" etc the ideal solution would be one that knows the atypical dinner and could deduce/correct false negatives and find a dinner grouping from the classified data i.e:

Y = ['MEAT','0','0','0','0','MEAT','0','VEG','MEAT'] -> ['DINNER'] (1 instance)

Some bag of words encoding of the problem should work but I don't get how to partition the output of classifier 1 such that partitions aren't forced to be a certain size

Is there something that I could use for this?


问:
How would I print the fav_genre field for a specific user
So the code below saves the variables username pass etc into a text file with the colons to separate each field. say I wanted to print out the favourite genre of a particular user, how would that be possible as my attempts so far to do so have failed. this is all in python btw. ive edited to add my attempt but its not woking.Any ideas??

```<code>usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()
</code>```

my attempt:

```<code>textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
    with open(textfile, 'r') as textIn:
        for line in textIn:
            information = line.split(' : ')
            if information[0] == username:
                return information[5]
    return 'Failed to find user.'

getUsersFavouriteGenre()
</code>```

答:
Your code looks good. I'm assuming the issue is your program doesn't output anything, in which case the only issue I see is change your last line getUsersFavouriteGenre() to print(getUsersFavouriteGenre())

If you are getting a specific error or undesired output then you can let us know and we can help you more specifically.

Body:
So the code below saves the variables username pass etc into a text file with the colons to separate each field. say I wanted to print out the favourite genre of a particular user, how would that be possible as my attempts so far to do so have failed. this is all in python btw. ive edited to add my attempt but its not woking.Any ideas??

usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()

my attempt:

textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
    with open(textfile, 'r') as textIn:
        for line in textIn:
            information = line.split(' : ')
            if information[0] == username:
                return information[5]
    return 'Failed to find user.'

getUsersFavouriteGenre()


问:
How can I get parent class to access child class in angular 2?
I've got an Angular 2 application with Typescript. I'm wondering how to access a child class from a parent class.

The parent class is like this:

```<code>@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')]
})
export class AllDataPageComponent implements OnInit {
...
}
</code>```

Its selector looks like this:

```<code><all-data-page [allData]="results.top3.Rows" type="Safeguards" *ngIf="!!results.AllDataSafeguards">
</all-data-page>
</code>```

The child looks like this:

```<code>@Component({
  selector: 'all-data-row',
  templateUrl: './all-data-row.component.html',
  styles: [ require('./all-data-row.style.scss') ],
  encapsulation: ViewEncapsulation.None
})
export class AllDataRowComponent implements OnInit {
...
}
</code>```

And its selector looks like this:

```<code> <div class="data-list">
        <all-data-row *ngFor="let item of categoryRows; let last=last"
                      relativeWidth="100"
                      [item]="item.chartData"
                      [last]="last"
                      [ChartLabel]="item.chartData.ChartLabel"
                      [acmCat1]="item.chartData.acmCat1"
                      [acmCat2]="item.chartData.acmCat2"
                      [acmCat3]="item.chartData.acmCat3"
                      [acmCat4]="item.chartData.acmCat4"
                      [acmCat5]="item.chartData.acmCat5"
                      (click)="selectCategory(item.fullObject)"
                      [selected]="selected">
        </all-data-row>
    </div>
</code>```

I would like to know how to reference the child class from the parent class.

Various sites that come up on google suggest using @ViewChildren but that doesn't work for me. The Chrome console just tells me "ViewChildren is not defined".

What must I do to get the parent class to access the child class?

Thanks.

答:
I'm not using @ViewChildren. When I DID use @ViewChildren (and got the error) I did it like so:

```<code>@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')]
})
export class AllDataPageComponent implements OnInit {
@ViewChildren(AllDataRowComponent) AllDataRowComponent : safeguardRow;
...
}
</code>```

I get the same error with the link you provided.

Body:
I've got an Angular 2 application with Typescript. I'm wondering how to access a child class from a parent class.

The parent class is like this:

@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')]
})
export class AllDataPageComponent implements OnInit {
...
}

Its selector looks like this:

<all-data-page [allData]="results.top3.Rows" type="Safeguards" *ngIf="!!results.AllDataSafeguards">
</all-data-page>

The child looks like this:

@Component({
  selector: 'all-data-row',
  templateUrl: './all-data-row.component.html',
  styles: [ require('./all-data-row.style.scss') ],
  encapsulation: ViewEncapsulation.None
})
export class AllDataRowComponent implements OnInit {
...
}

And its selector looks like this:

        <all-data-row *ngFor="let item of categoryRows; let last=last"
                      relativeWidth="100"
                      [item]="item.chartData"
                      [last]="last"
                      [ChartLabel]="item.chartData.ChartLabel"
                      [acmCat1]="item.chartData.acmCat1"
                      [acmCat2]="item.chartData.acmCat2"
                      [acmCat3]="item.chartData.acmCat3"
                      [acmCat4]="item.chartData.acmCat4"
                      [acmCat5]="item.chartData.acmCat5"
                      (click)="selectCategory(item.fullObject)"
                      [selected]="selected">
        </all-data-row>

I would like to know how to reference the child class from the parent class.

Various sites that come up on google suggest using @ViewChildren but that doesn't work for me. The Chrome console just tells me "ViewChildren is not defined".

What must I do to get the parent class to access the child class?

Thanks.

Body:
I'm not using @ViewChildren. When I DID use @ViewChildren (and got the error) I did it like so:

@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')]
})
export class AllDataPageComponent implements OnInit {
@ViewChildren(AllDataRowComponent) AllDataRowComponent : safeguardRow;
...
}

I get the same error with the link you provided.


问:
Truncate a string without ending in the middle of a word
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.

For example:

```
Original:          "This is really awesome."
"Dumb" truncate:   "This is real..."
"Smart" truncate:  "This is really..."
```

I'm looking for a way to accomplish the "smart" truncate from above.

答:
From Python 3.4+ you can use textwrap.shorten. With the OP example:

```<code>>>> import textwrap
>>> original = "This is really awesome."
>>> textwrap.shorten(original, width=20, placeholder="...")
'This is really...'
</code>```

textwrap.shorten(text, width, **kwargs)

Collapse and truncate the given text to fit in the given width.

First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is
  returned. Otherwise, enough words are dropped from the end so that the
  remaining words plus the placeholder fit within width:

OwnerDisplayName: jacktasia

Body:
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.

For example:

Original:          "This is really awesome."
"Dumb" truncate:   "This is real..."
"Smart" truncate:  "This is really..."

I'm looking for a way to accomplish the "smart" truncate from above.

Body:
From Python 3.4+ you can use textwrap.shorten. With the OP example:

>>> import textwrap
>>> original = "This is really awesome."
>>> textwrap.shorten(original, width=20, placeholder="...")
'This is really...'

textwrap.shorten(text, width, **kwargs)

Collapse and truncate the given text to fit in the given width.

First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is
  returned. Otherwise, enough words are dropped from the end so that the
  remaining words plus the placeholder fit within width:


问:
Bash, cut word with dot character from string
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

```<code>echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5
</code>```

But I ended up with:

2017.11.13

How can I get the result I want?

答:
awk to the rescue! a non-standard approach to break the monotony...

define the to be removed text as field separator and parse and print the input line.

```<code>$ echo Log for: squid.log.2017.11.13 | awk -F' squid\\.log\\.' '{$1=$1}1'

Log for: 2017.11.13
</code>```

Body:
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5

But I ended up with:

2017.11.13

How can I get the result I want?

Body:
awk to the rescue! a non-standard approach to break the monotony...

define the to be removed text as field separator and parse and print the input line.

$ echo Log for: squid.log.2017.11.13 | awk -F' squid\\.log\\.' '{$1=$1}1'

Log for: 2017.11.13


问:
Can I create a game for webgl without the Unity logo?
Can I create a game for webgl without the Unity logo when I download and without title "Unity webGL"?
 . example</p>

答:
With the personal license you are unable to legally remove the Unity splash screen. You need the Plus or Pro license. Plus costs $35 a month, Pro is $125 a month.

The majority of the features of Plus and Pro are not needed for smaller projects and with no hurt your development. All engine features are the same across the board, so you can always develop you game with a personal license.

When it comes time to launch you can buy Plus or Pro and remove the splash screen and take advantage of the performance reporting and analytics features that come with it.


问:
User.Identity.Name is empty when API is called through Azure API Management
If I call my API from a client (example is a native Console app) through API Management, my User.Identity.Name is empty and IsAuthenticated is False in the back-end API.

If I call my API through the API Management portal webpage (the Try It test portal), my server-side API code is able to see my User.Identity (User.Identity.Name, User.Identity.IsAuthenticated).

On my client side, I am getting a token and then calling an API that is exposed via Azure API Management.

```<code>HttpClientHandler handler = new HttpClientHandler
{
    UseDefaultCredentials = true
};

client = new HttpClient(handler);
authContext = new AuthenticationContext(AADInstance);

PlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto);
AuthenticationResult authResult = await authContext.AcquireTokenAsync(apiResourceId, clientId, redirectUrl, platformParameters);

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Connection.Add("Keep-Alive");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
client.DefaultRequestHeaders.Add("Host", "...");

client.BaseAddress = new Uri(baseAddress);

var response = await GetResponseAsync(baseAddress + "Diagnostics");
</code>```

On the server, I am trying to get the User.Identity that called the API (my API, of course, doesn't know that it is being called through the API Management portal). The User.Identity.Name is empty, the AuthenticationType is empty, the IsAuthenticated flag is False. These values are populated correctly if I call my API via the API Management portal "Try It" function.

```<code>HttpContext context = HttpContext.Current;
userName = User.Identity.Name; //is empty
ClaimsIdentity claimsIdentity = (ClaimsIdentity)User.Identity;
items.Add($"Authentication Type: '{claimsIdentity.AuthenticationType}'"); // is empty
items.Add($"Is Authenticated: {claimsIdentity.IsAuthenticated}"); // is False
</code>```

答: The issue was the resource ID that was passed in as part of the request for the Bearer token. It must be the App ID URI of the backend API, not the API Management portal.

Body:
If I call my API from a client (example is a native Console app) through API Management, my User.Identity.Name is empty and IsAuthenticated is False in the back-end API.

If I call my API through the API Management portal webpage (the Try It test portal), my server-side API code is able to see my User.Identity (User.Identity.Name, User.Identity.IsAuthenticated).

On my client side, I am getting a token and then calling an API that is exposed via Azure API Management.

HttpClientHandler handler = new HttpClientHandler
{
    UseDefaultCredentials = true
};

client = new HttpClient(handler);
authContext = new AuthenticationContext(AADInstance);

PlatformParameters platformParameters = new PlatformParameters(PromptBehavior.Auto);
AuthenticationResult authResult = await authContext.AcquireTokenAsync(apiResourceId, clientId, redirectUrl, platformParameters);

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Connection.Add("Keep-Alive");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
client.DefaultRequestHeaders.Add("Host", "...");

client.BaseAddress = new Uri(baseAddress);

var response = await GetResponseAsync(baseAddress + "Diagnostics");

On the server, I am trying to get the User.Identity that called the API (my API, of course, doesn't know that it is being called through the API Management portal). The User.Identity.Name is empty, the AuthenticationType is empty, the IsAuthenticated flag is False. These values are populated correctly if I call my API via the API Management portal "Try It" function.

HttpContext context = HttpContext.Current;
userName = User.Identity.Name; //is empty
ClaimsIdentity claimsIdentity = (ClaimsIdentity)User.Identity;
items.Add($"Authentication Type: '{claimsIdentity.AuthenticationType}'"); // is empty
items.Add($"Is Authenticated: {claimsIdentity.IsAuthenticated}"); // is False


问:
Branch.io params is always empty when my app is on background (opened)
I have a pretty straight forward setting, setup

my intent filters for my main activity on the manifest

singleTask mode for all my activities (it just have two)

My app have two entry points: one the intent filter will call my MainActivity which start the branch session return the values on the referringParams and I go to the SecondActivity, everyone is happy

the another entry point is the launcher, when I click open the MainActivity do somethhing different because intent.data is empty and Go to SecondActivity, the problem is as follows, after the app is in the SecondActivity and the app goes background (e.g. touch home button) and then tap on some link the MainActivity is launched intent.data is not empty there's a valid url but when my callback is called I got referringParams empty {}

I dont know what is wrong with this. i have spend some hours without success

```<code>@Override
public void onStart() {
    super.onStart();
    Branch branch = Branch.getInstance();

    branch.initSession(new Branch.BranchReferralInitListener(){
        @Override
        public void onInitFinished(JSONObject referringParams, BranchError error) {
            if (error == null) {
                // here referringParams is a empty {} object
            } else {
                Log.i("MyApp", error.getMessage());
            }
        }
    }, this.getIntent().getData(), this);
}

@Override
public void onNewIntent(Intent intent) {
    this.setIntent(intent);
}
</code>```

答:
I am not sure what processing you are doing in your Main Activity. The use case you mentioned, should return the Branch link parameters correctly,

If you have the intent filters and the launchMode of the MainActivity, correctly defined

You are overriding the onNewIntent() method in your MainActivity (which I can see from the code snippet you shared)

I created a sample app, which is uploaded here. If you follow the test case you mentioned with this app(i.e. App is backgrounded with the SecondActivity), clicking on a Branch link returns the link parameters correctly.

Body:
I have a pretty straight forward setting, setup

my intent filters for my main activity on the manifest

singleTask mode for all my activities (it just have two)

My app have two entry points: one the intent filter will call my MainActivity which start the branch session return the values on the referringParams and I go to the SecondActivity, everyone is happy

the another entry point is the launcher, when I click open the MainActivity do somethhing different because intent.data is empty and Go to SecondActivity, the problem is as follows, after the app is in the SecondActivity and the app goes background (e.g. touch home button) and then tap on some link the MainActivity is launched intent.data is not empty there's a valid url but when my callback is called I got referringParams empty {}

I dont know what is wrong with this. i have spend some hours without success

@Override
public void onStart() {
    super.onStart();
    Branch branch = Branch.getInstance();

    branch.initSession(new Branch.BranchReferralInitListener(){
        @Override
        public void onInitFinished(JSONObject referringParams, BranchError error) {
            if (error == null) {
                // here referringParams is a empty {} object
            } else {
                Log.i("MyApp", error.getMessage());
            }
        }
    }, this.getIntent().getData(), this);
}

@Override
public void onNewIntent(Intent intent) {
    this.setIntent(intent);
}


问:
Python inaccurate curve fit
```<code>Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26
</code>```

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()
</code>```

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

答:
This is a sensitive problem (as is typical when exponentials are involved).  For a problem like this, it is important to have a pretty good initial guess for the parameters.

If you experiment with the parameters, you'll find that A has to be very small.  The default initial guess that is used by curve_fit for all the parameters is 1, and 1 is far too big for A.  If I use 1e-10 for the initial guess for A

```<code>popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1))
</code>```

I get the following error from curve_fit:

```<code>RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.
</code>```

So let's increase maxfev to, say, 2000:

```<code>popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1), maxfev=2000)
</code>```

I got the same error.  When I increased it to 100000, the function succeeded.

Here's a script that includes the updated call to curve_fit, followed by the plot generated by the script.

```<code>import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

T = np.array([298, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800,
              850, 900, 950, 1000])
kt = np.array([6.66e-63, 1.48e-62, 3.58e-55, 1.25e-49, 2.57e-45, 7.30e-42,
               4.90e-39, 1.12e-36, 1.11e-34, 5.72e-33, 1.75e-31, 3.49e-30,
               4.92e-29, 5.17e-28, 4.24e-27, 2.83e-26])

def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))

popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1), maxfev=100000)

plt.plot(T, kt, '.', label='data')
tt = np.linspace(T[0], T[-1], 160)
kk = reacKine(tt, *popt)
semilogy = True
if semilogy:
    plt.semilogy(tt, kk, 'k-', alpha=0.3, label='fit')
    results_xy = (700, 1e-45)
else:
    plt.plot(tt, kk, 'k-', alpha=0.3, label='fit')
    results_xy = (300, 1.5e-26)

plt.annotate(xy=results_xy,
            s=('Fit Results:\n  $A\,$  = %.4g\n  $n\,$  = %.4g\n  $E_{a}$ = %.4g' %
               tuple(popt)))
plt.xlabel('T')
plt.ylabel('k(T)')
plt.legend(framealpha=1, shadow=True)
plt.show()
</code>```

P.S. @MNewville might be able to suggest a better way to do this fit using lmfit.

Title: Python inaccurate curve fit

Body:
Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

Body:
This is a sensitive problem (as is typical when exponentials are involved).  For a problem like this, it is important to have a pretty good initial guess for the parameters.

If you experiment with the parameters, you'll find that A has to be very small.  The default initial guess that is used by curve_fit for all the parameters is 1, and 1 is far too big for A.  If I use 1e-10 for the initial guess for A

popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1))

I get the following error from curve_fit:

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

So let's increase maxfev to, say, 2000:

popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1), maxfev=2000)

I got the same error.  When I increased it to 100000, the function succeeded.

Here's a script that includes the updated call to curve_fit, followed by the plot generated by the script.

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

T = np.array([298, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800,
              850, 900, 950, 1000])
kt = np.array([6.66e-63, 1.48e-62, 3.58e-55, 1.25e-49, 2.57e-45, 7.30e-42,
               4.90e-39, 1.12e-36, 1.11e-34, 5.72e-33, 1.75e-31, 3.49e-30,
               4.92e-29, 5.17e-28, 4.24e-27, 2.83e-26])

def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))

popt, pcov = curve_fit(reacKine, T, kt, p0=(1e-10, 1, 1), maxfev=100000)

plt.plot(T, kt, '.', label='data')
tt = np.linspace(T[0], T[-1], 160)
kk = reacKine(tt, *popt)
semilogy = True
if semilogy:
    plt.semilogy(tt, kk, 'k-', alpha=0.3, label='fit')
    results_xy = (700, 1e-45)
else:
    plt.plot(tt, kk, 'k-', alpha=0.3, label='fit')
    results_xy = (300, 1.5e-26)

plt.annotate(xy=results_xy,
            s=('Fit Results:\n  $A\,$  = %.4g\n  $n\,$  = %.4g\n  $E_{a}$ = %.4g' %
               tuple(popt)))
plt.xlabel('T')
plt.ylabel('k(T)')
plt.legend(framealpha=1, shadow=True)
plt.show()

P.S. @MNewville might be able to suggest a better way to do this fit using lmfit.


问:
Displaying images based on dynamic array
I have a server generated Array, which can return one up to six array items. These array items are "categories," based on category, they will display a different image (There are eight custom images that can be selected from per category, but this happens behind the scenes). So only one image is being established per category. However, there can also be a "custom" image uploaded, which takes priority if present. So in reality, the server will return one or two images, per category. On top of that, a user can fall into multiple categories, so I need to add a priority level based on category so one overrides the other, I'm trying to figure out how to handle this efficiently and struggling. Particularly in the priority area; should I add another namespace to the array to specify priority level and designate based on lowest value? What is the most efficient way to compare array values and return results?

Edit: By efficient, I mean, scalable and maintainable, not necessarily performant.

console.clear();
// banner element
var banner = document.getElementById('banner');
// 3s timout
window.setTimeout(function() {
  // add class (class handles fade transition)
  banner.classList.add('fade-in');
}, 3000);

// Array generated from "Architecture Priorities" field, not all will display, but more than one can.
var arc = [
    'Collaboration',
    'Data Center',/*
    'Enterprise Networks',
    'Security',
    'Services',*/
    'Cross Architecture'
  ],

  // manual array and image defaults (will need to utilize zval() for "path")
  img = [{
    name: 'Collaboration',
    path: '//placehold.it/1200x400/fa4/fff', // value returned from server based on user input.
    customPath: '' // value returned from server based on user input
  }, {
    name: 'Data Center',
    path: '//placehold.it/1200x400/4af/fff',
    customPath: ''
  }, {
    name: 'Enterprise Networks',
    path: '//placehold.it/1200x400/af4/fff',
    customPath: ''
  }, {
    name: 'Security',
    path: '//placehold.it/1200x400/4fa/fff',
    customPath: ''
  }, {
    name: 'Services',
    path: '//placehold.it/1200x400/f4a/fff',
    customPath: ''
  }, {
    name: 'Cross Architecture',
    path: '//placehold.it/1200x400/a4f/fff',
    customPath: '//placehold.it/1200x400/222/fff?text=custom'
  }];

for (var prop in img) {
  if (img.hasOwnProperty(prop)) {
    for(var i = 0; i < arc.length; i++) {
      if(img[prop].name === arc[i]){
        if (img[prop].customPath !== '') {
         banner.setAttribute('src', img[prop].customPath);
        } else {
          banner.setAttribute('src', img[prop].path);
        }
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.banner-wrapper {
  max-width: 1200px;
  background: transparent url('//placehold.it/1200x400/222/fff') no-repeat center center / cover;
}

img {
  vertical-align: baseline;
  display: block;
  max-width: 100%;
  height: auto;
  opacity: 0;
  transition: opacity 2s;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
}

img.fade-in {
  opacity: 1;
}</code>```

```

答:
I would try that.
I add priority key in your img collection then i take img with the highest priority.

```<code>var arc = [
  "Collaboration",
  "Data Center" /*
    'Enterprise Networks',
    'Security',
    'Services',*/,
  "Cross Architecture"
];
var imgs = [
  {
    name: "Collaboration",
    path: "//placehold.it/1200x400/fa4/fff", // value returned from server based on user input.
    customPath: "", // value returned from server based on user input,
    priority: 0
  },
  {
    name: "Data Center",
    path: "//placehold.it/1200x400/4af/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Enterprise Networks",
    path: "//placehold.it/1200x400/af4/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Security",
    path: "//placehold.it/1200x400/4fa/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Services",
    path: "//placehold.it/1200x400/f4a/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Cross Architecture",
    path: "//placehold.it/1200x400/a4f/fff",
    customPath: "//placehold.it/1200x400/222/fff?text=custom",
    priority: 0
  },
  {
    name: "Collaboration",
    path: "//placehold.it/1200x400/fa4/fff", // value returned from server based on user input.
    customPath: "", // value returned from server based on user input,
    priority: 1
  },
  {
    name: "Data Center",
    path: "//placehold.it/1200x400/4af/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Enterprise Networks",
    path: "//placehold.it/1200x400/af4/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Security",
    path: "//placehold.it/1200x400/4fa/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Services",
    path: "//placehold.it/1200x400/f4a/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Cross Architecture",
    path: "//placehold.it/1200x400/a4f/fff",
    customPath: "//placehold.it/1200x400/222/fff?text=custom",
    priority: 1
  }
];
var priotiziredImgs = {};
imgs.forEach(img => {
  if (arc.indexOf(img.name) > -1) {
    let name = img.name;
    if (priotiziredImgs[name]) {
      priotiziredImgs[name] =
        img.priority > priotiziredImgs[name].priority
          ? img
          : priotiziredImgs[name];
    } else {
      priotiziredImgs[name] = img;
    }
  }
});
</code>```

With this you get images with the highest priority for a given category. And then you can
do a loop again to append them to the dom.

```<code>Object.keys(priotiziredImgs).forEach(name => {
  let src = priotiziredImgs[name].customPath.length
    ? priotiziredImgs[name].customPath
    : priotiziredImgs[name].path;
  banner.setAttribute("src", src);
});
</code>```

Body:
I have a server generated Array, which can return one up to six array items. These array items are "categories," based on category, they will display a different image (There are eight custom images that can be selected from per category, but this happens behind the scenes). So only one image is being established per category. However, there can also be a "custom" image uploaded, which takes priority if present. So in reality, the server will return one or two images, per category. On top of that, a user can fall into multiple categories, so I need to add a priority level based on category so one overrides the other, I'm trying to figure out how to handle this efficiently and struggling. Particularly in the priority area; should I add another namespace to the array to specify priority level and designate based on lowest value? What is the most efficient way to compare array values and return results?

Edit: By efficient, I mean, scalable and maintainable, not necessarily performant.

console.clear();
// banner element
var banner = document.getElementById('banner');
// 3s timout
window.setTimeout(function() {
  // add class (class handles fade transition)
  banner.classList.add('fade-in');
}, 3000);

// Array generated from "Architecture Priorities" field, not all will display, but more than one can.
var arc = [
    'Collaboration',
    'Data Center',/*
    'Enterprise Networks',
    'Security',
    'Services',*/
    'Cross Architecture'
  ],

  // manual array and image defaults (will need to utilize zval() for "path")
  img = [{
    name: 'Collaboration',
    path: '//placehold.it/1200x400/fa4/fff', // value returned from server based on user input.
    customPath: '' // value returned from server based on user input
  }, {
    name: 'Data Center',
    path: '//placehold.it/1200x400/4af/fff',
    customPath: ''
  }, {
    name: 'Enterprise Networks',
    path: '//placehold.it/1200x400/af4/fff',
    customPath: ''
  }, {
    name: 'Security',
    path: '//placehold.it/1200x400/4fa/fff',
    customPath: ''
  }, {
    name: 'Services',
    path: '//placehold.it/1200x400/f4a/fff',
    customPath: ''
  }, {
    name: 'Cross Architecture',
    path: '//placehold.it/1200x400/a4f/fff',
    customPath: '//placehold.it/1200x400/222/fff?text=custom'
  }];

for (var prop in img) {
  if (img.hasOwnProperty(prop)) {
    for(var i = 0; i < arc.length; i++) {
      if(img[prop].name === arc[i]){
        if (img[prop].customPath !== '') {
         banner.setAttribute('src', img[prop].customPath);
        } else {
          banner.setAttribute('src', img[prop].path);
        }
      }
    }
  }
}

.banner-wrapper {
  max-width: 1200px;
  background: transparent url('//placehold.it/1200x400/222/fff') no-repeat center center / cover;
}

img {
  vertical-align: baseline;
  display: block;
  max-width: 100%;
  height: auto;
  opacity: 0;
  transition: opacity 2s;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
}

img.fade-in {
  opacity: 1;
}

Body:
I would try that.
I add priority key in your img collection then i take img with the highest priority.

var arc = [
  "Collaboration",
  "Data Center" /*
    'Enterprise Networks',
    'Security',
    'Services',*/,
  "Cross Architecture"
];
var imgs = [
  {
    name: "Collaboration",
    path: "//placehold.it/1200x400/fa4/fff", // value returned from server based on user input.
    customPath: "", // value returned from server based on user input,
    priority: 0
  },
  {
    name: "Data Center",
    path: "//placehold.it/1200x400/4af/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Enterprise Networks",
    path: "//placehold.it/1200x400/af4/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Security",
    path: "//placehold.it/1200x400/4fa/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Services",
    path: "//placehold.it/1200x400/f4a/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Cross Architecture",
    path: "//placehold.it/1200x400/a4f/fff",
    customPath: "//placehold.it/1200x400/222/fff?text=custom",
    priority: 0
  },
  {
    name: "Collaboration",
    path: "//placehold.it/1200x400/fa4/fff", // value returned from server based on user input.
    customPath: "", // value returned from server based on user input,
    priority: 1
  },
  {
    name: "Data Center",
    path: "//placehold.it/1200x400/4af/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Enterprise Networks",
    path: "//placehold.it/1200x400/af4/fff",
    customPath: "",
    priority: 1
  },
  {
    name: "Security",
    path: "//placehold.it/1200x400/4fa/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Services",
    path: "//placehold.it/1200x400/f4a/fff",
    customPath: "",
    priority: 0
  },
  {
    name: "Cross Architecture",
    path: "//placehold.it/1200x400/a4f/fff",
    customPath: "//placehold.it/1200x400/222/fff?text=custom",
    priority: 1
  }
];
var priotiziredImgs = {};
imgs.forEach(img => {
  if (arc.indexOf(img.name) > -1) {
    let name = img.name;
    if (priotiziredImgs[name]) {
      priotiziredImgs[name] =
        img.priority > priotiziredImgs[name].priority
          ? img
          : priotiziredImgs[name];
    } else {
      priotiziredImgs[name] = img;
    }
  }
});

With this you get images with the highest priority for a given category. And then you can
do a loop again to append them to the dom.

Object.keys(priotiziredImgs).forEach(name => {
  let src = priotiziredImgs[name].customPath.length
    ? priotiziredImgs[name].customPath
    : priotiziredImgs[name].path;
  banner.setAttribute("src", src);
});


问:
ag-Grid adding css classes
I have this simple requirement for my Angular application...namely adding a css class when expanding or collapsing a row for the purpose of highlighting said row.  I have tried using gridOptions.getRowClass as per the docs https://www.ag-grid.com/javascript-grid-row-styles/#gsc.tab=0 but that appears to have no effect.

My html I have added an event handler that will fire a method once the row expands/collapses. My html looks as follows:

```<code><ag-grid-angular #agGrid style="width: 100%; height:85vh" class="ag-material grid-Holdings"
  [gridOptions]="gridOptions"
  [rowData]="rowData"
  ...
  (rowGroupOpened)="addRowClass($event)">
</ag-grid-angular>
</code>```

...and in my grid.component.ts I have the method which should add/remove a css class:

```<code>addRowClass(params) {
  this.gridOptions.getRowClass = (params) => {
    if (params.node.expanded) {
      return 'my-css-class';
    }
  }
}
</code>```

One interesting thing is that when I add break points in Chrome dev console I see that it never executes return 'my-css-class' but I cannot find any information in the official documentation as to why.  I am really struggling with ag-Grid in general, and Angular integration with ag-Grid in particular.  If this does not work is it better to just do this in vanilla JS somehow... If so, how might I go about this without ag-Grid api?

答: ag-grid already toggles some css classes for you: ag-row-group-expanded (when expanded) and ag-row-group-contracted (when not expanded). You should be able to accomplish your goal by applying the necessary styles to these classes.

Title: ag-Grid adding css classes

Body:
I have this simple requirement for my Angular application...namely adding a css class when expanding or collapsing a row for the purpose of highlighting said row.  I have tried using gridOptions.getRowClass as per the docs https://www.ag-grid.com/javascript-grid-row-styles/#gsc.tab=0 but that appears to have no effect.

My html I have added an event handler that will fire a method once the row expands/collapses. My html looks as follows:

<ag-grid-angular #agGrid style="width: 100%; height:85vh" class="ag-material grid-Holdings"
  [gridOptions]="gridOptions"
  [rowData]="rowData"
  ...
  (rowGroupOpened)="addRowClass($event)">
</ag-grid-angular>

...and in my grid.component.ts I have the method which should add/remove a css class:

addRowClass(params) {
  this.gridOptions.getRowClass = (params) => {
    if (params.node.expanded) {
      return 'my-css-class';
    }
  }
}

One interesting thing is that when I add break points in Chrome dev console I see that it never executes return 'my-css-class' but I cannot find any information in the official documentation as to why.  I am really struggling with ag-Grid in general, and Angular integration with ag-Grid in particular.  If this does not work is it better to just do this in vanilla JS somehow... If so, how might I go about this without ag-Grid api?


问:
How to set column height equal to longest column in Bulma (flexbox)?
I'm using Bulma 0.4.0, though the answer may not be associated with Bulma itself.

How can I set column height equal to others? (see screenshots below)

Edit: codepen with more text that presents actual behavior: https://codepen.io/anon/pen/vmKVbx

Expected behavior:

Actual behavior:

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" />
<div class="columns">
  <div class="column">
    <p class="notification is-info">First column</p>
  </div>
  <div class="column">
    <p class="notification is-success">Second column</p>
  </div>
  <div class="column">
    <p class="notification is-warning">Third column</p>
  </div>
  <div class="column">
    <p class="notification is-danger">Fourth</p>
  </div>
</div>
</code>```

答:
This works fine for me with this code:

```<code><div class="columns">
    <div class="column my-class">
        one thing
    </div>
    <div class="column my-class">
        many other <br><br><br> etc. things
    </div>
</div>

<style>
.column.my-class {
    display: inline-flex;
}

.column.my-class > div {
    width: 100%; // only Edge needed this nonsense
}
</style>
</code>```

Worked in Chrome 61.0.3163.100 (of course), Edge 40.15063.674.0, Firefox 57.0.

Body:
I'm using Bulma 0.4.0, though the answer may not be associated with Bulma itself.

How can I set column height equal to others? (see screenshots below)

Edit: codepen with more text that presents actual behavior: https://codepen.io/anon/pen/vmKVbx

Expected behavior:

Actual behavior:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" />

First column

Second column

Third column

Fourth

Body:
This works fine for me with this code:

<div class="columns">
    <div class="column my-class">
        one thing
    </div>
    <div class="column my-class">
        many other <br><br><br> etc. things
    </div>
</div>

<style>
.column.my-class {
    display: inline-flex;
}

.column.my-class > div {
    width: 100%; // only Edge needed this nonsense
}
</style>

Worked in Chrome 61.0.3163.100 (of course), Edge 40.15063.674.0, Firefox 57.0.


问:
Why does Python numpy float32 / int division gives a float64 result?
I have a numpy.float32 matrix V, then I did a division with a integer scalar value:

```<code>V = V/num
</code>```

where num is an integer. The outcome is somewhat surprising that V is converted to a numpy.float64 matrix.

Can anyone help understand why this is so?

Thanks!

答:
According to Numpy.result_type, numpy.float32 can not hold int32 losslessly. When the operation is with an int32, numpy will promotes the resulting value as a float64. Also according to @Eric, the actual int type may change in different environment, so a pre-test is a good practice to avoid some potential surprise.

A previous similar question is suggested for further reading:Numpy casting float32 to float64
. Numpy has a different treatment for purely scalar operations and the operations involving an array. In this case, the division operation involves a ndarray, so when num is smaller than 65536 but larger thant 255, numpy converts it as int16. Numpy determines int16 can be cast to float32 losslessly while int32 can't. This is shown by np.can_cast(np.int16, np.float32) gives True but np.can_cast(np.int32, np.float32) gives False.

Thanks for the insightful comments under the question. This answer is a short summary of these comments.

Body:
I have a numpy.float32 matrix V, then I did a division with a integer scalar value:

V = V/num

where num is an integer. The outcome is somewhat surprising that V is converted to a numpy.float64 matrix.

Can anyone help understand why this is so?

Thanks!


问:
Create cron job in PHP
Is there a way I can create a cron job in php to be run by a specific user. By default it runs as wwww-data and this doesn't work. Can I change the user and run it ? The following is what I am doing. Please tell me where I am going wrong. </p>

```<code>shell_exec('(crontab -u username -l 2>/dev/null; echo "* * * * * /usr/bin/php filename.php") | crontab -');
</code>```

答: There're /etc/cron.XXX/ folders nowadays (i.e.  cron.daily, cron.hourly etc) where you can simply drop your job as new file w/o bothering other config files.

Title: Create cron job in PHP

Body:
Is there a way I can create a cron job in php to be run by a specific user. By default it runs as wwww-data and this doesn't work. Can I change the user and run it ? The following is what I am doing. Please tell me where I am going wrong.

shell_exec('(crontab -u username -l 2>/dev/null; echo "* * * * * /usr/bin/php filename.php") | crontab -');


问:
My SQL Query Won't work for some reason (ReCAPTCHA 2.0)
So I'm using RECAPTCHA 2.0 and I can't seem to get this form to work without getting a SQL Query Error, If you can find a solution please reply and thanks.
(I've made the secret key secret)

Can't seem to post PHP Code here so here is a pastebin link - https://pastebin.com/CbMhKVPf

```<code><?php
$link = "https://pastebin.com/CbMhKVPf";
?>
</code>```

答: I can get it to work, just had some logic errors.</p>

Body:
So I'm using RECAPTCHA 2.0 and I can't seem to get this form to work without getting a SQL Query Error, If you can find a solution please reply and thanks.
(I've made the secret key secret)

Can't seem to post PHP Code here so here is a pastebin link - https://pastebin.com/CbMhKVPf

<?php
$link = "https://pastebin.com/CbMhKVPf";
?>


问:
Why does the Spring application save logs in two places?
When the application is started (spring-boot), the application saves the logs from the console in two places. How to change it?

This is a multi-module application, and this is the configuration of one of the modules.

pom.xml:

```<code>...
<properties>
    <logs.path>${basedir}/logs</logs.path>
</properties>
...
</code>```

application.yml:

```<code>...
logging.path: @logs.path@
...
</code>```

logback.xml:

```<code><configuration>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/console.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/console/console.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>90</maxHistory>
    </rollingPolicy>
    <encoder>
        <charset>utf-8</charset>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36}.%M: %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="CONSOLE_FILE"/>
</root>

</configuration>
</code>```

When I run the application logs are saved in the following locations:

modules/LOG_PATH_IS_UNDEFINED/console.log

and

modules/singleModule/logs/console.log

How to fix it.

答: Remove logging.path from application.yml and check if LOG_PATH variable is properly set.

Body:
When the application is started (spring-boot), the application saves the logs from the console in two places. How to change it?

This is a multi-module application, and this is the configuration of one of the modules.

pom.xml:

...
<properties>
    <logs.path>${basedir}/logs</logs.path>
</properties>
...

application.yml:

...
logging.path: @logs.path@
...

logback.xml:

<configuration>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/console.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/console/console.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>90</maxHistory>
    </rollingPolicy>
    <encoder>
        <charset>utf-8</charset>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36}.%M: %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="CONSOLE_FILE"/>
</root>

</configuration>

When I run the application logs are saved in the following locations:

modules/LOG_PATH_IS_UNDEFINED/console.log

and

modules/singleModule/logs/console.log

How to fix it.


问:
Passing a closure to a function expecting a std::ops::Fn
I'm trying to use a closure to call a function on a bunch of feature vectors.  The most important code lines here are the first line, where we say what type query must be and the last line, where we try to give a closure.

```<code>fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
    // takes in a dataset of feature vectors and a query,
    // returns the average of the query on the dataset
    if dataset.len() == 0 {
        0.
    } else {
        dataset.iter().map(|ref fv| query(&fv)).sum() / (dataset.len() as f64)
    }
}

fn main() {
    // build dataset
    let fv1: Vec<i32> = vec![1, 1, 1, 1, 1];
    let fv2: Vec<i32> = vec![1, 0, 1, 0, 1];
    let my_dataset = vec![fv1, fv2];

    // query checks whether sum of features is greater than a threshold
    fn my_query(ref fv: &Vec<i32>, threshold: i32) -> f64 {
        if fv.iter().sum() > threshold {
            1.
        } else {
            0.
        }
    }

    // run query on dataset with threshold 3
    println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
}
</code>```

When I run this, I get an error:

error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:1:40
  |
1 | fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
  |                                        ^^^^^ `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
  = note: all local variables must have a statically known size

error[E0308]: mismatched types
  --> src/main.rs:27:44
   |
27 |     println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
   |                                            ^^^^^^^^^^^^^^^^^^^^^^^^ expected trait std::ops::Fn, found closure
   |
   = note: expected type `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
              found type `[closure@src/main.rs:27:44: 27:68]`
```

I thought closures implemented Fn (or FnOnce or FnMut)?  Is it not valid to provide a closure when you expect a Fn? I assume I need to specify something else about the Fn in the first line?  But what?

I assume I have incorrectly specified the type of either the query: Fn(&Vec<i32>) -> f64 parameter of my first function, or have written the closure wrong |ref fv| my_query(fv, 3).

I read Passing closure to trait method: expected type parameter, found closure, but that seems to be more about passing a closure that isn't the only kind of thing the function is accepting.

答:
The second error was the more important one:

```<code>error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static: std::marker::Sized` is not satisfied
</code>```

In short: Fn(&Vec<i32>) -> f64 is not a sized type, and cannot be passed by value.  You can only pass trait objects (references or boxes), or values of (sized) types implementing a trait.  In this case you probably want the latter:

Playground

```<code>fn stat_query<F>(dataset: &Vec<Vec<i32>>, query: F) -> f64
where
    F: Fn(&Vec<i32>) -> f64,
{
    // takes in a dataset of feature vectors and a query,
    // returns the average of the query on the dataset
    if dataset.len() == 0 {
        0.
    } else {
        dataset.iter().map(|ref fv| query(&fv)).sum::<f64>() / (dataset.len() as f64)
    }
}

fn main() {
    // build dataset
    let fv1: Vec<i32> = vec![1, 1, 1, 1, 1];
    let fv2: Vec<i32> = vec![1, 0, 1, 0, 1];
    let my_dataset = vec![fv1, fv2];

    // query checks whether sum of features is greater than a threshold
    fn my_query(ref fv: &Vec<i32>, threshold: i32) -> f64 {
        if fv.iter().sum::<i32>() > threshold {
            1.
        } else {
            0.
        }
    }

    // run query on dataset with threshold 3
    println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
}
</code>```

Body:
I'm trying to use a closure to call a function on a bunch of feature vectors.  The most important code lines here are the first line, where we say what type query must be and the last line, where we try to give a closure.

fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
    // takes in a dataset of feature vectors and a query,
    // returns the average of the query on the dataset
    if dataset.len() == 0 {
        0.
    } else {
        dataset.iter().map(|ref fv| query(&fv)).sum() / (dataset.len() as f64)
    }
}

fn main() {
    // build dataset
    let fv1: Vec<i32> = vec![1, 1, 1, 1, 1];
    let fv2: Vec<i32> = vec![1, 0, 1, 0, 1];
    let my_dataset = vec![fv1, fv2];

    // query checks whether sum of features is greater than a threshold
    fn my_query(ref fv: &Vec<i32>, threshold: i32) -> f64 {
        if fv.iter().sum() > threshold {
            1.
        } else {
            0.
        }
    }

    // run query on dataset with threshold 3
    println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
}

When I run this, I get an error:

error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:1:40
  |
1 | fn stat_query(dataset: &Vec<Vec<i32>>, query: Fn(&Vec<i32>) -> f64) -> f64 {
  |                                        ^^^^^ `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
  = note: all local variables must have a statically known size

error[E0308]: mismatched types
  --> src/main.rs:27:44
   |
27 |     println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
   |                                            ^^^^^^^^^^^^^^^^^^^^^^^^ expected trait std::ops::Fn, found closure
   |
   = note: expected type `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static`
              found type `[closure@src/main.rs:27:44: 27:68]`

I thought closures implemented Fn (or FnOnce or FnMut)?  Is it not valid to provide a closure when you expect a Fn? I assume I need to specify something else about the Fn in the first line?  But what?

I assume I have incorrectly specified the type of either the query: Fn(&Vec<i32>) -> f64 parameter of my first function, or have written the closure wrong |ref fv| my_query(fv, 3).

I read Passing closure to trait method: expected type parameter, found closure, but that seems to be more about passing a closure that isn't the only kind of thing the function is accepting.

Body:
The second error was the more important one:

error[E0277]: the trait bound `for<'r> std::ops::Fn(&'r std::vec::Vec<i32>) -> f64 + 'static: std::marker::Sized` is not satisfied

In short: Fn(&Vec<i32>) -> f64 is not a sized type, and cannot be passed by value.  You can only pass trait objects (references or boxes), or values of (sized) types implementing a trait.  In this case you probably want the latter:

Playground

fn stat_query<F>(dataset: &Vec<Vec<i32>>, query: F) -> f64
where
    F: Fn(&Vec<i32>) -> f64,
{
    // takes in a dataset of feature vectors and a query,
    // returns the average of the query on the dataset
    if dataset.len() == 0 {
        0.
    } else {
        dataset.iter().map(|ref fv| query(&fv)).sum::<f64>() / (dataset.len() as f64)
    }
}

fn main() {
    // build dataset
    let fv1: Vec<i32> = vec![1, 1, 1, 1, 1];
    let fv2: Vec<i32> = vec![1, 0, 1, 0, 1];
    let my_dataset = vec![fv1, fv2];

    // query checks whether sum of features is greater than a threshold
    fn my_query(ref fv: &Vec<i32>, threshold: i32) -> f64 {
        if fv.iter().sum::<i32>() > threshold {
            1.
        } else {
            0.
        }
    }

    // run query on dataset with threshold 3
    println!("{}", stat_query(&my_dataset, |ref fv| my_query(fv, 3)));
}


问:
Running Java Spark program on AWS EMR
I'm having problem running Java written spark application on AWS EMR.
Locally, everything runs fine. When I submit a job to EMR, I always get "Completed" withing 20 seconds even though job should take minutes. There is no output being produced, no log messages are being printed.

I'm still confused as weather it should be ran as Spark application or CUSTOM_JAR type.

Look of my main method:

```<code>public static void main(String[] args) throws Exception {
    SparkSession spark = SparkSession
            .builder()
            .appName("RandomName")
            .getOrCreate();

    //process stuff
    String from_path = args[0];
    String to_path = args[1];
    Dataset<String> dataInput = spark.read().json(from_path).toJSON();
    JavaRDD<ResultingClass> map = dataInput.toJavaRDD().map(row -> convertData(row)); //provided function didn't include here

    Dataset<Row> dataFrame = spark.createDataFrame(map, ResultingClass.class);

    dataFrame
            .repartition(1)
            .write()
            .mode(SaveMode.Append)
            .partitionBy("year", "month", "day", "hour")
            .parquet(to_path);

    spark.stop();
}
</code>```

I've tried these:

1)

```<code>aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=Spark,Name=MyApp,Args=[--deploy-mode,cluster,--master,yarn, \
--conf,spark.yarn.submit.waitAppCompletion=false, \
--class,com.my.class.with.main.Foo,s3://mybucket/script.jar, \
s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE --region us-west-2 --profile default
</code>```

Completes in 15 sec without error, output result or logs I've added.

2)

```<code>aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=CUSTOM_JAR, \
Jar=s3://mybucket/script.jar, \
MainClass=com.my.class.with.main.Foo, \
Name=MyApp, \
Args=[--deploy-mode,cluster, \
--conf,spark.yarn.submit.waitAppCompletion=true, \
s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE \
--region us-west-2 --profile default
</code>```

Reads parameters wrongly, sees --deploy-mode as first parameter and cluster as second instead of buckets

3)

```<code>aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=CUSTOM_JAR, \
Jar=s3://mybucket/script.jar, \
MainClass=com.my.class.with.main.Foo, \
Name=MyApp, \
Args=[s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE \
--region us-west-2 --profile default
</code>```

I get this: Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.SparkSession

When I include all dependencies (which I do not need to locally)

I get: Exception in thread "main" org.apache.spark.SparkException: A master URL must be set in your configuration
I do not want to hardcode the "yarn" into the app.

I find AWS documentation very confusing as to what is the proper way to run this.

Update:

Running command directly on the server does work. So the problem must be in the way I'm defining a cli command.

```<code>spark-submit --class com.my.class.with.main.Foo \
    s3://mybucket/script.jar \
    "s3://partitioned-input-data/*/*/*/*/*.txt" \
    "s3://output-bucket/table-name"
</code>```

答:
The 1) was working.

The step overview on the aws console said that the task was finished within 15 seconds, but in reality it was still running on the cluster. It took him an hour to do the work and I can see the result.

I do not know why the step is misreporting the result. I'm using emr-5.9.0 with Ganglia 3.7.2, Spark 2.2.0, Zeppelin 0.7.2.

Title: Running Java Spark program on AWS EMR

Body:
I'm having problem running Java written spark application on AWS EMR.
Locally, everything runs fine. When I submit a job to EMR, I always get "Completed" withing 20 seconds even though job should take minutes. There is no output being produced, no log messages are being printed.

I'm still confused as weather it should be ran as Spark application or CUSTOM_JAR type.

Look of my main method:

public static void main(String[] args) throws Exception {
    SparkSession spark = SparkSession
            .builder()
            .appName("RandomName")
            .getOrCreate();

    //process stuff
    String from_path = args[0];
    String to_path = args[1];
    Dataset<String> dataInput = spark.read().json(from_path).toJSON();
    JavaRDD<ResultingClass> map = dataInput.toJavaRDD().map(row -> convertData(row)); //provided function didn't include here

    Dataset<Row> dataFrame = spark.createDataFrame(map, ResultingClass.class);

    dataFrame
            .repartition(1)
            .write()
            .mode(SaveMode.Append)
            .partitionBy("year", "month", "day", "hour")
            .parquet(to_path);

    spark.stop();
}

I've tried these:

1)

aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=Spark,Name=MyApp,Args=[--deploy-mode,cluster,--master,yarn, \
--conf,spark.yarn.submit.waitAppCompletion=false, \
--class,com.my.class.with.main.Foo,s3://mybucket/script.jar, \
s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE --region us-west-2 --profile default

Completes in 15 sec without error, output result or logs I've added.

2)

aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=CUSTOM_JAR, \
Jar=s3://mybucket/script.jar, \
MainClass=com.my.class.with.main.Foo, \
Name=MyApp, \
Args=[--deploy-mode,cluster, \
--conf,spark.yarn.submit.waitAppCompletion=true, \
s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE \
--region us-west-2 --profile default

Reads parameters wrongly, sees --deploy-mode as first parameter and cluster as second instead of buckets

3)

aws emr add-steps --cluster-id j-XXXXXXXXX --steps \
Type=CUSTOM_JAR, \
Jar=s3://mybucket/script.jar, \
MainClass=com.my.class.with.main.Foo, \
Name=MyApp, \
Args=[s3://partitioned-input-data/*/*/*/*/*.txt, \
s3://output-bucket/table-name], \
ActionOnFailure=CONTINUE \
--region us-west-2 --profile default

I get this: Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.SparkSession

When I include all dependencies (which I do not need to locally)

I get: Exception in thread "main" org.apache.spark.SparkException: A master URL must be set in your configuration
I do not want to hardcode the "yarn" into the app.

I find AWS documentation very confusing as to what is the proper way to run this.

Update:

Running command directly on the server does work. So the problem must be in the way I'm defining a cli command.

spark-submit --class com.my.class.with.main.Foo \
    s3://mybucket/script.jar \
    "s3://partitioned-input-data/*/*/*/*/*.txt" \
    "s3://output-bucket/table-name"


问:
Future Proof DALs
We are in the beginning of a really long development project with several sub projects. Basically each sub-project will take several months to develop. The code itself will be split up into several C# projects, but the physical database will be shared by all projects.

The problem is maintainability. If we add a column to a table, or split a table into two smaller tables, we'll have to go back and modify our C# DAL to support these changes. This is not acceptable, as we'll constantly be adapting the DB conform to the needs of the company as a whole, and not just the needs of a single program. Constantly changing old code would be a neverending task.

Our DB people suggested a different view. We do all our CRUD through stored procedures, and use Linq across several tables to perform our SELECT statements. Then if we restructure the DB several years from now, we can simply supply the same stored procs and views and not have to modify our older code.

The question we have, is what ORM should be used for something like this? EF seems a bit overkill (maybe it's not). Would something like SubSonic with it's T4 templating allow for a simpiler (and perhaps faster) DAL?

Or perhaps someone has an idea on how to make this entire process less painful? We'd rather not add another layer to our application, but neither do we want to go back and modify code everytime we make a db change.

Edit 1:
So when I said "I don't really want to add more layers". This is mostly because we already have several layers. We have Silverlight views, view-models, BLL objects (via CSLA) then we have the DAL, and finally the SQL tables themseleves.

答:
I have started to use BLToolkit based on the performance info from http://ormeter.net/

You can define your model in simple class files, add some methods with attributes applied and presto you have a DAL. Split a table in two and you can maintain the original class file while creating the new ones to support the split tables. Just make sure you create a testing project that hits every method to make sure they all work with each release

Class

```<code>    public class DirectoryListing
    {
        [PrimaryKey, Identity]
        public Int64 Id { get; set; }
        public Int64? OldId { get; set; }
        public Int32 CategoryId { get; set; }
        [Nullable]
        public String CompanyName { get; set; }
}
</code>```

General select or table valued function:

```<code>[SqlQuery("SELECT * FROM Ajax_CategorySearch(@SearchString, @ResultCount)")]
[Cache(MaxCacheTime = 10, IsWeak = false)]
public abstract List<String> AjaxCategorySearch(String @SearchString, Int32 @ResultCount = 10);
</code>```

Or to use a stored proc:

```<code>[ActionName("SelectById")]
public abstract Model.DirectoryListing SelectById(Int64 @Id);
</code>```

This will call the SP DirectoryListing_SelectById

Oh, and doing things in a more classic way is easy too

```<code>    using (BIFDbManager db = new BIFDbManager())
    {
        var output = db.SetCommand(
            "SQL GOES HERE",
            db.Parameter("@Id", 1))
            .ExecuteList<DAL.Model.DirectoryListing>();

        totalrecords = output.Count();

        return output;
    }
</code>```

The last piece of the puzzle is the db manager, which also enables LINQ support.

```<code>public class BIFDbManager : DbManager
{
    public BIFDbManager() : base("Connection string name") { }

    public Table<DirectoryListing> DirectoryListings { get { return GetTable<DirectoryListing>(); } }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Future Proof DALs

Body:
I have started to use BLToolkit based on the performance info from http://ormeter.net/

You can define your model in simple class files, add some methods with attributes applied and presto you have a DAL. Split a table in two and you can maintain the original class file while creating the new ones to support the split tables. Just make sure you create a testing project that hits every method to make sure they all work with each release

Class

    public class DirectoryListing
    {
        [PrimaryKey, Identity]
        public Int64 Id { get; set; }
        public Int64? OldId { get; set; }
        public Int32 CategoryId { get; set; }
        [Nullable]
        public String CompanyName { get; set; }
}

General select or table valued function:

[SqlQuery("SELECT * FROM Ajax_CategorySearch(@SearchString, @ResultCount)")]
[Cache(MaxCacheTime = 10, IsWeak = false)]
public abstract List<String> AjaxCategorySearch(String @SearchString, Int32 @ResultCount = 10);

Or to use a stored proc:

[ActionName("SelectById")]
public abstract Model.DirectoryListing SelectById(Int64 @Id);

This will call the SP DirectoryListing_SelectById

Oh, and doing things in a more classic way is easy too

    using (BIFDbManager db = new BIFDbManager())
    {
        var output = db.SetCommand(
            "SQL GOES HERE",
            db.Parameter("@Id", 1))
            .ExecuteList<DAL.Model.DirectoryListing>();

        totalrecords = output.Count();

        return output;
    }

The last piece of the puzzle is the db manager, which also enables LINQ support.

public class BIFDbManager : DbManager
{
    public BIFDbManager() : base("Connection string name") { }

    public Table<DirectoryListing> DirectoryListings { get { return GetTable<DirectoryListing>(); } }
}


问:
C: How to find the day name for a given day of the year input by user
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

```<code>int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}
</code>```

答:
Since you're currently only interested in working with the year 2017, you can easily figure out the day of the week by taking countDays() modulo 7. You can extend what you currently print in main():

```<code>printf("There are %d days \n", countDays(day, month, daysInMonth));
</code>```

With:

```<code>int days = countDays(day, month, daysInMonth);
char *c[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

printf("There are %d days; day of the week: %s \n", days, c[(days - 1) % 7]);
</code>```

Body:
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}

Body:
Since you're currently only interested in working with the year 2017, you can easily figure out the day of the week by taking countDays() modulo 7. You can extend what you currently print in main():

printf("There are %d days \n", countDays(day, month, daysInMonth));

With:

int days = countDays(day, month, daysInMonth);
char *c[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

printf("There are %d days; day of the week: %s \n", days, c[(days - 1) % 7]);


问:
Mapstruct: update individual models in collection
I am trying to update a collection using mapstruct like this:

```<code>List<Passenger> updatePassengers(@MappingTarget List<Passenger> passengers, List<Passenger> sourcePassenger);
Passenger updatePassenger(@MappingTarget Passenger passenger, Passenger sourcePassenger);
</code>```

Now in generated sources updatePassenger method is generated as below:

```<code>public List<Passenger> updatePassengers(List<Passenger> passengers, List<Passenger> sourcePassenger) {
    if ( sourcePassenger == null ) {
        return null;
    }

    passengers.clear();
    for ( Passenger passenger : sourcePassenger ) {
        passengers.add( passenger );
    }

    return passengers;
}
</code>```

Here its removing the passenger from the destination and setting passengers from source. I want to update individual passenger objects.

I went through the mapstruct docs and it says that it clears collection before updating.

Is there a way mapstruct could call updatePassenger method for each passenger?

答:
In case you don't want the default behaviour of MapStruct kicking in you should write your own custom method that would perform the update.

```<code>default List<Passenger updatePassengers(List<Passenger> passenger, Lit<Passenger> sourcePassengers) {
    //Do your logic here
}
</code>```

On top of that, MapStruct cannot generate the code you need it doesn't know which passenger should be linked with which passenger.

In your definition you are saying that you want the passenger list to be update with the sourcePassengers list.

Body:
I am trying to update a collection using mapstruct like this:

List<Passenger> updatePassengers(@MappingTarget List<Passenger> passengers, List<Passenger> sourcePassenger);
Passenger updatePassenger(@MappingTarget Passenger passenger, Passenger sourcePassenger);

Now in generated sources updatePassenger method is generated as below:

public List<Passenger> updatePassengers(List<Passenger> passengers, List<Passenger> sourcePassenger) {
    if ( sourcePassenger == null ) {
        return null;
    }

    passengers.clear();
    for ( Passenger passenger : sourcePassenger ) {
        passengers.add( passenger );
    }

    return passengers;
}

Here its removing the passenger from the destination and setting passengers from source. I want to update individual passenger objects.

I went through the mapstruct docs and it says that it clears collection before updating.

Is there a way mapstruct could call updatePassenger method for each passenger?

Body:
In case you don't want the default behaviour of MapStruct kicking in you should write your own custom method that would perform the update.

default List<Passenger updatePassengers(List<Passenger> passenger, Lit<Passenger> sourcePassengers) {
    //Do your logic here
}

On top of that, MapStruct cannot generate the code you need it doesn't know which passenger should be linked with which passenger.

In your definition you are saying that you want the passenger list to be update with the sourcePassengers list.


问:
Check if file exists by checking two different naming conventions using jQuery/JS
I am trying to to build out profile pages for multiple users which include  personalized photos/items that are stored are on a server. These items are labeled/named using the users' name. A user has a FirstName & LastName, with the option of using a PreferredName.

Initially, the items were named using PreferredName over Firstname if a Preferred Name existed. (ex: Fname: Robert; Lname: Smith; Pname: Bobby; FileName = SmithBobby.file)

Unfortunately, the user now has the ability to change their name on their profile from PreferredName back to FirstName, leading to a large portion of profiles to look for the incorrect file (item is actually named SmithBobby.file, while the profile is looking for SmithRobert.file.)

This being said, I would like to check for the item using both naming conventions (FirstLast.file & PreferredLast.file), if neither exists, it should default to use the default/generic photo. (default.file)

The below example is how I currently check to see if the user has a CV and profile picture on file. If no CV exists, it removes the element from the page. if the image doesn't exist, it defaults to default.jpg.

if (($.PageData.PreferredName == "") || ($.PageData.PreferredName == null)) {
  $("#Name").text($.PageData.FirstName + " " + $.PageData.LastName);
  document.title = ($.PageData.FirstName + " " + $.PageData.LastName + " | Profile");
  $("#BioPageTitle").text($.PageData.FirstName + " " + $.PageData.LastName);
} else {
  $("#Name").text($.PageData.PreferredName + " " + $.PageData.LastName);
  document.title = ($.PageData.PreferredName + " " + $.PageData.LastName + " | Profile");
  $("#BioPageTitle").text($.PageData.PreferredName + " " + $.PageData.LastName);
}

//FILENAME BUILD
var file_name = ($.PageData.LastName + $.PageData.FirstName);
var second_fname = ($.PageData.LastName + $.PageData.PreferredName);

file_name = file_name.replace(/[^0-9a-z]/gi, '');
second_fname = second_fname.replace(/[^0-9a-z]/gi, '');

var vita = $('#Vita');
var vita_url = "vita/" + file_name + ".pdf";
var second_vitaURL = "vita/" + second_fname + ".pdf";

var VitaLink = $("").attr({
  href: vita_url,
  target: '_blank'
}).html("Curriculum Vitae");
$.get(vita_url)
  .done(function() {
    vita.html(VitaLink);
  }).fail(function() {

    vita.remove();

  });

/*PHOTO BUILD/CHECK */
//PROFILE PICTURE
var img = $('#ProfilePicture');
var default_url = "photos/default.jpg";
var img_url = "photos/" + file_name + ".jpg";
img.error(function() {
  $(this).attr('src', default_url);
});
img.attr('src', img_url);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
You should be able to extend your current function that checks the first link by checking for the second one if the first one fails.  If the second one fails too, then you can remove the entry.</p>

```<code>$.get(vita_url)
  .done(function() {
    vita.html(VitaLink);
  }).fail(function() {
    $.get(second_vitaURL)
      .done(function() {
        //modify the VitaLink with the correct url, if this doesn't work make a separate vitaLink type variable
        VitaLink.attr('href', second_vitaURL);
        vita.html(VitaLink);
      }).fail(function() {
        vita.remove();
      });
  });
</code>```

Body:
You should be able to extend your current function that checks the first link by checking for the second one if the first one fails.  If the second one fails too, then you can remove the entry.

$.get(vita_url)
  .done(function() {
    vita.html(VitaLink);
  }).fail(function() {
    $.get(second_vitaURL)
      .done(function() {
        //modify the VitaLink with the correct url, if this doesn't work make a separate vitaLink type variable
        VitaLink.attr('href', second_vitaURL);
        vita.html(VitaLink);
      }).fail(function() {
        vita.remove();
      });
  });


问:
What does OSStatus Error -50 mean?
I am writing some keychain code on iOS. When I try to insert an item in keychain I get error -50.

What does OSStatus error -50 mean?

答:
If you are adding a password to the keychain make sure you pass it as Data and not String, otherwise you will get an OSStatus error -50.</p>

```<code>static func savePassword(password: Data, account: String) throws -> OSStatus {
    let query = [
        kSecClass as String: kSecClassGenericPassword as String,
        kSecAttrAccount as String: account,
        kSecValueData as String: password
        ] as [String: Any]

    SecItemDelete(query as CFDictionary)

    return SecItemAdd(query as CFDictionary, nil)
}
</code>```

Title: What does OSStatus Error -50 mean?

Body:
If you are adding a password to the keychain make sure you pass it as Data and not String, otherwise you will get an OSStatus error -50.

static func savePassword(password: Data, account: String) throws -> OSStatus {
    let query = [
        kSecClass as String: kSecClassGenericPassword as String,
        kSecAttrAccount as String: account,
        kSecValueData as String: password
        ] as [String: Any]

    SecItemDelete(query as CFDictionary)

    return SecItemAdd(query as CFDictionary, nil)
}


答:
Your command seems to be wrong.

echo "* * * * * /usr/bin/php filename.php" | crontab - is enoguh because crontab maintains crontab files for individual users. So if you launch it as www-data it will be created an entry for www-data user.

Hope it will help!

Title: Create cron job in PHP


问:
How can I determine what my database's connection limits should be?
At my organization, PostgreSQL databases are created with a 20-connection limit as a matter of policy. This tends to interact poorly when multiple applications are in play that use connection pools, since many of those open up their full suite of connections and hold them idle.

As soon as there are more than a couple of applications in contact with the DB, we run out of connections, as you'd expect.

Pooling behaviour is a new thing here; until now we've managed pooled connections by serializing access to them through a web-based DB gateway (?!) or by not pooling anything at all. As a consequence, I'm having to explain (literally, 5 trouble tickets from one person over the course of the project) over and over again how the pooling works.

What I want is one of the following:

A solid, inarguable rationale for increasing the number of available connections to the database in order to play nice with pools.

If so, what's a safe limit? Is there any reason to keep the limit to 20?

A reason why I'm wrong and we should cut the size of the pools down or eliminate them altogether.

For what it's worth, here are the components in play. If it's relevant how one of these is configured, please weigh in:

DB: PostgreSQL 8.2.  No, we won't be upgrading it as part of this.

Web server: Python 2.7, Pylons 1.0, SQLAlchemy 0.6.5, psycopg2

This is complicated by the fact that some aspects of the system access data using SQLAlchemy ORM using a manually configured engine, while others access data using a different engine factory (Still sqlalchemy) written by one of my associates that wraps the connection in an object that matches an old PHP API.

Task runner: Python 2.7, celery 2.1.4, SQLAlchemy 0.6.5, psycopg2

答:
I think it's reasonable to require one connection per concurrent activity, and it's reasonable to assume that concurrent HTTP requests are concurrently executed.

Now, the number of concurrent HTTP requests you want to process should scale with a) the load on your server, and b) the number of CPUs you have available. If all goes well, each request will consume CPU time somewhere (in the web server, in the application server, or in the database server), meaning that you couldn't process more requests concurrently than you have CPUs. In practice, it's not that all goes well: some requests will wait for IO at some point, and not consume any CPU. So it's ok to process some more requests concurrently than you have CPUs.

Still, assuming that you have, say, 4 CPUs, allowing 20 concurrent requests is already quite some load. I'd rather throttle HTTP requests than increasing the number of requests that can be processed concurrently. If you find that a single request needs more than one connection, you have a flaw in your application.

So my recommendation is to cope with the limit, and make sure that there are not too many idle connections (compared to the number of requests that you are actually processing concurrently).


问:
Can I get the text, or other attributes of a widget, once I find it?
I'm writing a unit or integration test for Flutter. Can I get the text, or other attributes of a widget, once I find it?</p>

答:
Yes, WidgetTester provides multiple methods for probing into the UI tree (widgets, states, elements, render objects). Here's an example of how you can use it to read out the text out of a Text widget:

```<code>tester.widget(find.byType(Text)).data;
</code>```

See also https://flutter.io/testing/#widget-testing, which explains how to write widget tests in Flutter.

Body:
Yes, WidgetTester provides multiple methods for probing into the UI tree (widgets, states, elements, render objects). Here's an example of how you can use it to read out the text out of a Text widget:

tester.widget(find.byType(Text)).data;

See also https://flutter.io/testing/#widget-testing, which explains how to write widget tests in Flutter.


问:
.NET Core build with dll reference
I am trying to get .NET core to work with the build system at my work, which had been designed with Java in mind. But it is sadly so integrated into our pipelines that there is no way we can be without it. So if I want to use .NET at work will it have to be with this build system.

Each project is built into a package, with their own git repository.

Given a program like below where MyConsoleApp has a dependency on MyLibrary.

```<code>MyProgram-Solution
 - MyConsoleApp
 - MyLibrary
</code>```

At build time the source code would be placed in

```<code>/build/packages/MyConsoleApp/
/build/packages/MyLibrary/
</code>```

However I can only build one at the time, and I cannot move the source code.
Which means that I would need to build MyLibrary first, with the DLL ending up in

```<code>/build/packages/MyLibrary/out/MyLibrary.1.0.dll
</code>```

When I then build MyConsoleApp, I need a way to tell the .NET Core build tool that the MyLibrary.1.0.dll file can be found at

```<code>/build/packages/MyLibrary/out/MyLibrary.1.0.dll
</code>```

Storing packages in Nuget is not an option, as the package may not be ready for release at the build time, and the build system works in a sandbox mode, meaning it has no external connections.

I can edit the MyConsoleApp.csproj if that makes it possible.

答:
You can add assembly references using Visual Studio, same as with .NET Framework projects.

If you want to modify the project file by hand, you'll need something like the following:

```<code><ItemGroup>
  <Reference Include="MyLibrary">
    <HintPath>..\..\..\MyLibrary\out\MyLibrary.1.0.dll</HintPath>
  </Reference>
</ItemGroup>
</code>```

Title: .NET Core build with dll reference

Body:
I am trying to get .NET core to work with the build system at my work, which had been designed with Java in mind. But it is sadly so integrated into our pipelines that there is no way we can be without it. So if I want to use .NET at work will it have to be with this build system.

Each project is built into a package, with their own git repository.

Given a program like below where MyConsoleApp has a dependency on MyLibrary.

MyProgram-Solution
 - MyConsoleApp
 - MyLibrary

At build time the source code would be placed in

/build/packages/MyConsoleApp/
/build/packages/MyLibrary/

However I can only build one at the time, and I cannot move the source code.
Which means that I would need to build MyLibrary first, with the DLL ending up in

/build/packages/MyLibrary/out/MyLibrary.1.0.dll

When I then build MyConsoleApp, I need a way to tell the .NET Core build tool that the MyLibrary.1.0.dll file can be found at

/build/packages/MyLibrary/out/MyLibrary.1.0.dll

Storing packages in Nuget is not an option, as the package may not be ready for release at the build time, and the build system works in a sandbox mode, meaning it has no external connections.

I can edit the MyConsoleApp.csproj if that makes it possible.

Body:
You can add assembly references using Visual Studio, same as with .NET Framework projects.

If you want to modify the project file by hand, you'll need something like the following:

<ItemGroup>
  <Reference Include="MyLibrary">
    <HintPath>..\..\..\MyLibrary\out\MyLibrary.1.0.dll</HintPath>
  </Reference>
</ItemGroup>

ContentLicense: CC BY-SA 4.0


问:
Can somebody explain this javascript fragment?

// JavaScript source code
var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();```

What is going on? Is foo an object? Is it a named function?
This looks like a hideous way to provide the class concept of private data members....

答:
foo is an object. It is the object following the return statement.

This code is declaring a function within those parentheses and then immediately calling it. foo is then assigned whatever value that function returns.

Body:
// JavaScript source code
var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();

What is going on? Is foo an object? Is it a named function?
This looks like a hideous way to provide the class concept of private data members....