问:
Git LFS setup in jenkins
I have an issue with git LFS use in Jenkins. What I am doing now is that

I am building a war from maven through Jenkins that war contains a jar file

through Git LFS we have converted that jar file into a pointer file. But during checkout from Jenkins that jar is not converting into its original size rather it is included in the war as a pointer.

We have used git plugin and git-client plugin with version 3.3.0 and 2.4.2 respectively in Jenkins.

What is happening:

A.war -> a.jar(whose original size is 1234 kb but it's coming 3 kb (which is the size of pointer file)

so my questions are:

how to use git LFS in the Jenkins?

is there any separate Git Lfs plugin for Jenkins?

How should the file convert to its original size during checkout when one use Git LfS?

答:
This can be done using the regular Git+Plugin for Jenkins (version 3.1.0 onwards).

If you are using Jenkins Pipelines (i.e. with a Jenkinsfile in the root of your repo), the key thing is to include the extension [$class: 'GitLFSPull'] in your checkout() call. Here is an (edited) example taken from one of our repos:

```<code>checkout([  $class: 'GitSCM',
    branches: [[name: 'refs/heads/'+env.BRANCH_NAME]],
        doGenerateSubmoduleConfigurations: false,
        extensions: [
            [$class: 'GitLFSPull'],
            [$class: 'CheckoutOption', timeout: 20],
            [$class: 'CloneOption',
                    depth: 0,
                    noTags: false,
                    reference: '/other/optional/local/reference/clone',
                    shallow: false,
                    timeout: 120]
        ],
        submoduleCfg: [],
        userRemoteConfigs: [
            [credentialsId: 'foobar',
            url: 'https://github.com/foo/bar.git']
        ]
    ])
</code>```

Using the Snippet Generator it is possible to generate this code, by selecting "Git LFS pull after checkout" from the "Additional Behaviours" menu. See screenshot here

Title: Git LFS setup in jenkins

Body:
This can be done using the regular Git+Plugin for Jenkins (version 3.1.0 onwards).

If you are using Jenkins Pipelines (i.e. with a Jenkinsfile in the root of your repo), the key thing is to include the extension [$class: 'GitLFSPull'] in your checkout() call. Here is an (edited) example taken from one of our repos:

checkout([  $class: 'GitSCM',
    branches: [[name: 'refs/heads/'+env.BRANCH_NAME]],
        doGenerateSubmoduleConfigurations: false,
        extensions: [
            [$class: 'GitLFSPull'],
            [$class: 'CheckoutOption', timeout: 20],
            [$class: 'CloneOption',
                    depth: 0,
                    noTags: false,
                    reference: '/other/optional/local/reference/clone',
                    shallow: false,
                    timeout: 120]
        ],
        submoduleCfg: [],
        userRemoteConfigs: [
            [credentialsId: 'foobar',
            url: 'https://github.com/foo/bar.git']
        ]
    ])

Using the Snippet Generator it is possible to generate this code, by selecting "Git LFS pull after checkout" from the "Additional Behaviours" menu. See screenshot here

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Plotting mean lines for different 'hue' data on a Seaborn FacetGrid plot
I am working with the Titanic passenger dataset (from Kaggle) as part of a Udacity course. I am using a Seaborn FacetGrid to look at passenger age distribution profiles by Travel class and Gender - with hue as 'Survived' (1/0).

The plot is working well, and I want to add vertical mean lines to each subplot - but in different colours (and with different annotation) for each of the two 'hues' in each subplot (1/0). The ' vertical_mean_line ' function in code below works great on plots without the multiple 'hue' data - but I can't find a way to plot different lines for each hue

Any ideas if it is possible to do this within Seaborn?

Current Seaborn FacetGrid plot output:

Code:

```<code>sns.set()
sns.set_context('talk')
sns.set_style('darkgrid')
grid = sns.FacetGrid(titanic_data.loc[titanic_data['is_child_def'] == False], col='Sex', row = 'Pclass', hue='Survived' ,size=3.2, aspect=2)
grid.map(sns.kdeplot, 'Age', shade=True)
grid.set(xlim=(14, titanic_data['Age'].max()), ylim=(0,0.06))
grid.add_legend()

# Add vertical lines for mean age on each plot
def vertical_mean_line_survived(x, **kwargs):
    plt.axvline(x.mean(), linestyle = '--', color = 'g')
    #plt.text(x.mean()+1, 0.052, 'mean = '+str('%.2f'%x.mean()), size=12)
    #plt.text(x.mean()+1, 0.0455, 'std = '+str('%.2f'%x.std()), size=12)

grid.map(vertical_mean_line_survived, 'Age')

# Add text to each plot for relevant popultion size
# NOTE - don't need to filter on ['Age'].isnull() for children, as 'is_child'=True only possible for children with 'Age' data
for row in range(grid.axes.shape[0]):
    grid.axes[row, 0].text(60.2, 0.052, 'Survived n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==1]['is_male'].sum()), size = 12)
    grid.axes[row, 1].text(60.2, 0.052, 'Survived n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==1]['is_female'].sum()), size = 12)
    grid.axes[row, 0].text(60.2, 0.047, 'Perished n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==0]['is_male'].sum()), size = 12)
    grid.axes[row, 1].text(60.2, 0.047, 'Perished n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==0]['is_female'].sum()), size = 12)

grid.set_ylabels('Frequency density', size=12)

# Squash down a little and add title to facetgrid
plt.subplots_adjust(top=0.9)
grid.fig.suptitle('Age distribution of adults by Pclass and Sex for Survived vs. Perished')
</code>```

答:
The kwargs contain the label and the color of the respective hue. Therefore, using

```<code>def vertical_mean_line_survived(x, **kwargs):
    ls = {"0":"-","1":"--"}
    plt.axvline(x.mean(), linestyle =ls[kwargs.get("label","0")],
                color = kwargs.get("color", "g"))
    txkw = dict(size=12, color = kwargs.get("color", "g"), rotation=90)
    tx = "mean: {:.2f}, std: {:.2f}".format(x.mean(),x.std())
    plt.text(x.mean()+1, 0.052, tx, **txkw)
</code>```

we would get

ContentLicense: CC BY-SA 3.0

Body:
I am working with the Titanic passenger dataset (from Kaggle) as part of a Udacity course. I am using a Seaborn FacetGrid to look at passenger age distribution profiles by Travel class and Gender - with hue as 'Survived' (1/0).

The plot is working well, and I want to add vertical mean lines to each subplot - but in different colours (and with different annotation) for each of the two 'hues' in each subplot (1/0). The ' vertical_mean_line ' function in code below works great on plots without the multiple 'hue' data - but I can't find a way to plot different lines for each hue

Any ideas if it is possible to do this within Seaborn?

Current Seaborn FacetGrid plot output:

Code:

sns.set()
sns.set_context('talk')
sns.set_style('darkgrid')
grid = sns.FacetGrid(titanic_data.loc[titanic_data['is_child_def'] == False], col='Sex', row = 'Pclass', hue='Survived' ,size=3.2, aspect=2)
grid.map(sns.kdeplot, 'Age', shade=True)
grid.set(xlim=(14, titanic_data['Age'].max()), ylim=(0,0.06))
grid.add_legend()

# Add vertical lines for mean age on each plot
def vertical_mean_line_survived(x, **kwargs):
    plt.axvline(x.mean(), linestyle = '--', color = 'g')
    #plt.text(x.mean()+1, 0.052, 'mean = '+str('%.2f'%x.mean()), size=12)
    #plt.text(x.mean()+1, 0.0455, 'std = '+str('%.2f'%x.std()), size=12)

grid.map(vertical_mean_line_survived, 'Age')

# Add text to each plot for relevant popultion size
# NOTE - don't need to filter on ['Age'].isnull() for children, as 'is_child'=True only possible for children with 'Age' data
for row in range(grid.axes.shape[0]):
    grid.axes[row, 0].text(60.2, 0.052, 'Survived n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==1]['is_male'].sum()), size = 12)
    grid.axes[row, 1].text(60.2, 0.052, 'Survived n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==1]['is_female'].sum()), size = 12)
    grid.axes[row, 0].text(60.2, 0.047, 'Perished n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==0]['is_male'].sum()), size = 12)
    grid.axes[row, 1].text(60.2, 0.047, 'Perished n = '+str(titanic_data.loc[titanic_data['Pclass']==row+1].loc[titanic_data['is_child_def']==False].loc[titanic_data['Age'].isnull()==False].loc[titanic_data['Survived']==0]['is_female'].sum()), size = 12)

grid.set_ylabels('Frequency density', size=12)

# Squash down a little and add title to facetgrid
plt.subplots_adjust(top=0.9)
grid.fig.suptitle('Age distribution of adults by Pclass and Sex for Survived vs. Perished')

Body:
The kwargs contain the label and the color of the respective hue. Therefore, using

def vertical_mean_line_survived(x, **kwargs):
    ls = {"0":"-","1":"--"}
    plt.axvline(x.mean(), linestyle =ls[kwargs.get("label","0")],
                color = kwargs.get("color", "g"))
    txkw = dict(size=12, color = kwargs.get("color", "g"), rotation=90)
    tx = "mean: {:.2f}, std: {:.2f}".format(x.mean(),x.std())
    plt.text(x.mean()+1, 0.052, tx, **txkw)

we would get


问:
How to fetch data about current user in ASP .NET MVC?
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

```<code>@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</code>```

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?

答:
Hi Here is the link to solve your problem exactly. Its seems that you can get the output by using the simple extension method.

Kindly follow the below link , in that asker had a same problem and finally provided the good solution. Hope it will be helpful for you too.

https://forums.asp.net/t/1957500.aspx?How+to+access+custom+Identity+or+ApplicationUser+properties+

Body:
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?


问:
IE7 problems with displaying text in TD
I can not figure out why the text inside the TD is not displayed in IE7. I am frustrated to the core cuz it works in FF! All I am trying to do is dynamically build a table onload... Any help will be greatly appreciated.
The complete script is at pastebin </p>

答:
User insertRow and insertCell to add Rows and Cells

Ex:

```<code>var row = table.insertRow();
row.id= rowid;

var headerCell = row.insertCell();
headerCell.colSpan = colspan;
headerCell.className = "rightAligned";
headerCell.innerHTML = "Header Text";
</code>```

ContentLicense: CC BY-SA 2.5

Title: IE7 problems with displaying text in TD

Body:
User insertRow and insertCell to add Rows and Cells

Ex:

var row = table.insertRow();
row.id= rowid;

var headerCell = row.insertCell();
headerCell.colSpan = colspan;
headerCell.className = "rightAligned";
headerCell.innerHTML = "Header Text";


问:
Using sed to extract element content of an XML file
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Header>
<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>
</Header>
<Body>
</Body>
</Envelope>
</code>```

so i want to get

```<code><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</code>```

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

```<code>sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt
</code>```

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

答:
The simplest solution to this particular problem that's independent of white space is to use GNU awk for multi-char RS:

```<code>$ gawk -v RS='\\s*</?Transport_key>\\s*' 'NR==2' file
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

$ tr -d '\n' < file
<?xml version="1.0" encoding="utf-8"?><Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><Header><Security><Transport_key><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" /><CipherData><CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue></CipherData></EncryptedKey></Transport_key></Security></Header><Body></Body></Envelope>

$ tr -d '\n' < file | gawk -v RS='\\s*</?Transport_key>\\s*' 'NR==2'
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" /><CipherData><CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue></CipherData></EncryptedKey>
</code>```

The reason to use an XML parser, though, is to handle things like the tag value showing up inside a string, etc. properly.

Body:
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>

</Envelope>

so i want to get

<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

Body:
The simplest solution to this particular problem that's independent of white space is to use GNU awk for multi-char RS:

$ gawk -v RS='\\s*</?Transport_key>\\s*' 'NR==2' file
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

$ tr -d '\n' < file
<?xml version="1.0" encoding="utf-8"?><Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><Header><Security><Transport_key><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" /><CipherData><CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue></CipherData></EncryptedKey></Transport_key></Security></Header><Body></Body></Envelope>

$ tr -d '\n' < file | gawk -v RS='\\s*</?Transport_key>\\s*' 'NR==2'
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" /><CipherData><CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue></CipherData></EncryptedKey>

The reason to use an XML parser, though, is to handle things like the tag value showing up inside a string, etc. properly.


问:
Python: remove row when a row element consists of string within row name
I have dataframe:

```<code>        Col1   Col2
Rowab1   3     5
Rowbc2   4     6
Rowxy3   7     2
</code>```

I want to search the dataframe and only keep the row where the row name contains "bc" like this while deleting rest of the rows:

```<code>        Col1   Col2
Rowab1   3     5
Rowxy3   7     2
</code>```

I have the following piece of code:

```<code>df.loc[df.index.isin(['bc'])]
</code>```

However, this does not search for "bc" within a string but it searches for an entire independent string "bc". Is there any "like" operator that I can possibly incorporate such as

```<code>df.loc[df.index.isin(['%bc%'])]  ?
</code>```

Thank you!

答:
An alternative with pd.Series.str.find:

```<code>In [41]: df
Out[41]:
        Col1  Col2
Rowab1     3     5
Rowbc2     4     6
Rowxy3     7     2

In [42]: df[df.index.str.find('bc') > -1]
Out[42]:
        Col1  Col2
Rowbc2     4     6
</code>```

Body:
I have dataframe:

        Col1   Col2
Rowab1   3     5
Rowbc2   4     6
Rowxy3   7     2

I want to search the dataframe and only keep the row where the row name contains "bc" like this while deleting rest of the rows:

        Col1   Col2
Rowab1   3     5
Rowxy3   7     2

I have the following piece of code:

df.loc[df.index.isin(['bc'])]

However, this does not search for "bc" within a string but it searches for an entire independent string "bc". Is there any "like" operator that I can possibly incorporate such as

df.loc[df.index.isin(['%bc%'])]  ?

Thank you!

Body:
An alternative with pd.Series.str.find:

In [41]: df
Out[41]:
        Col1  Col2
Rowab1     3     5
Rowbc2     4     6
Rowxy3     7     2

In [42]: df[df.index.str.find('bc') > -1]
Out[42]:
        Col1  Col2
Rowbc2     4     6


问:
PHP Class on Class, get Parent
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

```<code>class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}
</code>```

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

答:
A classic case of dependency injection.

```<code>class root {

   function root() {
      $this->son = new son($this);
      $this->daughter = new daughter($this);
   }

}

class son {

   function __construct($parent) {
       $this->parent = $parent;
   }

   function foo() {
       $this->parent->daughter->bar();
   }

}
</code>```

Just be careful not to create rigid dependencies between classes that shouldn't have them. Inheritance may be the better way to go. Alternatives include the registry pattern and factory patterns.

Title: PHP Class on Class, get Parent

Body:
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

Body:
A classic case of dependency injection.

class root {

   function root() {
      $this->son = new son($this);
      $this->daughter = new daughter($this);
   }

}

class son {

   function __construct($parent) {
       $this->parent = $parent;
   }

   function foo() {
       $this->parent->daughter->bar();
   }

}

Just be careful not to create rigid dependencies between classes that shouldn't have them. Inheritance may be the better way to go. Alternatives include the registry pattern and factory patterns.


问:
How to fix Country-State-Select gem undefined method issue?
In a implementation of gem:  https://github.com/arvindvyas/Country-State-Select

When i go to Post Job new page show this error on the log

```<code>undefined method `country' for #<Job:0x007f8c07092320>
</code>```

I've tried to put the

```<code>accepts_nested_attributes_for
</code>```

in the job model, but did not worked.

Someone have any hint to spare?

Job Model

```<code>class Job < ActiveRecord::Base
  belongs_to :user
  belongs_to :location
  accepts_nested_attributes_for :location, allow_destroy: true
  default_scope -> { order(created_at: :desc) }
end
</code>```

Location Model

```<code>class Location < ActiveRecord::Base
  has_many :users
  has_many :jobs
end
</code>```

Job new view

```<code><%= simple_form_for @job do |f| %>
  <%= f.simple_fields_for :location do |l| %>
    <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
    <%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>
    <%= l.input :city, CountryStateSelect.city_options(label: "City ", form: f, field_names: {  :state => :state, :city => :city } ) %>
  <% end %>
  <%= f.input :name, label: 'Name', error: 'Name is mandatory' %>
  <%= f.input :description, placeholder: 'user@domain.com' %>
  <%= f.button :submit %>
<% end %>
</code>```

答:
Looks like you're missing a country field in your Job model. Add it using a migration:

```<code>add_column :jobs, :country, :string
</code>```

Body:
In a implementation of gem:  https://github.com/arvindvyas/Country-State-Select

When i go to Post Job new page show this error on the log

undefined method `country' for #<Job:0x007f8c07092320>

I've tried to put the

accepts_nested_attributes_for

in the job model, but did not worked.

Someone have any hint to spare?

Job Model

class Job < ActiveRecord::Base
  belongs_to :user
  belongs_to :location
  accepts_nested_attributes_for :location, allow_destroy: true
  default_scope -> { order(created_at: :desc) }
end

Location Model

class Location < ActiveRecord::Base
  has_many :users
  has_many :jobs
end

Job new view

<%= simple_form_for @job do |f| %>
  <%= f.simple_fields_for :location do |l| %>
    <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
    <%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>
    <%= l.input :city, CountryStateSelect.city_options(label: "City ", form: f, field_names: {  :state => :state, :city => :city } ) %>
  <% end %>
  <%= f.input :name, label: 'Name', error: 'Name is mandatory' %>
  <%= f.input :description, placeholder: 'user@domain.com' %>
  <%= f.button :submit %>
<% end %>

Body:
Looks like you're missing a country field in your Job model. Add it using a migration:

add_column :jobs, :country, :string


问:
Storing passwords in Jupyter notebooks
Is there a way to store secrets/access secrets/passwords in notebooks? I have an api endpoint where I pull data from, and I dont want to expose the apiKey to everyone who can view the notebook. </p>

答:
cco's answer is good, but if you're looking for a simpler solution, many people use environmental variables to keep secrets segregated from source code.

For example, you can provide them when executing your script in the shell:

```<code>$ API_TOKEN=abc123 python script.py
</code>```

In your source code:

```<code>import os
API_TOKEN = os.environ.get("API_TOKEN")
</code>```

For your Jupyter notebooks, you can use python-dotenv or a similar package to "retrieve" a .env file that contains your project's secrets and is ignored by your version control system.

Once you've created your .env file (either manually, or using the package's command line tool), you can use python-dotenv in Jupyter (or IPython) like so:

```<code>%load_ext dotenv
%dotenv
import os
os.environ.get("API_TOKEN")
</code>```

Title: Storing passwords in Jupyter notebooks

Body:
cco's answer is good, but if you're looking for a simpler solution, many people use environmental variables to keep secrets segregated from source code.

For example, you can provide them when executing your script in the shell:

$ API_TOKEN=abc123 python script.py

In your source code:

import os
API_TOKEN = os.environ.get("API_TOKEN")

For your Jupyter notebooks, you can use python-dotenv or a similar package to "retrieve" a .env file that contains your project's secrets and is ignored by your version control system.

Once you've created your .env file (either manually, or using the package's command line tool), you can use python-dotenv in Jupyter (or IPython) like so:

%load_ext dotenv
%dotenv
import os
os.environ.get("API_TOKEN")


问:
Stripe subscription plan with trial but immediate payment and with end date
I am using Stripe payment gateway. I am working on a project having recurring payments.

Basically I have three plans created on Stripe,

```<code>1) Free  - 14 days, $0.00 , No trial, Should NOT be auto renewed
2) Basic - 1 Month, $15.00, No trial, auto renewed
3) Pro   - 1 Month, $25.00, No trial, auto renewed
</code>```

I have some doubts as following:

1) Is it required to provide the credit card details while subscribing a customer to a Free plan? What if I don't want to provide it for now and still subscribe him to Free plan?

2) I don't want the Free plan to be auto-renewed. So subscribing any customer to Free plan, how can I identify the end of the period or cycle using webhook since there is NO end date/period is there for plan? I want to cancel the customers' subscription (having Free plan) after 14 days and redirect them to choose Basic or Pro plan with credit card details.

3) For Basic and Pro plans there is no trial period has set. But still I want to provide 14 days trial to some specific customers. Is it possible by setting trial_end while subscribing a customer to a plan (i.e. For Basic or Pro)?

4) If I specify the trial_end attribute while subscribing a customer to a plan (i.e. Basic or Pro), the charge will be created after the trial period ends. Correct me? If yes, what if I want to charge them immediate but still they must have the trial period?

答:
1) No, it's not. Credit card information is not required. So, you can subscribe without credit card data. Credit card information is stored in source, and it's optional. I have tried it. Create a subscription

2) The subscription is always auto renew. If you don't want the subscription to be auto renew, you can subsribe without credit card. So, when the system tried to renew and failed, it will be as canceled or unpaid.  See The subscription object in status attribute.

3) Yes, it is possible. You can set / update the trial_end.

4) Yes. But I think, you can not to charge them immediate with still they must have the trial period.

My question: Why you have 3 plans with no trial at all?

My suggestion is, you should have 3 plans, and for the Free plan, it should has trial 14 days. So when user choose Free plan, it will have 14 days trial, and without credit card. Then when trial period is up, and it will auto renew and payment to renew the subscription will fails (because of no credit card). So then user should change plan to Basic or Pro with the credit card data. And for these plans, it should charge them immediately, without trial (trial_end = now).

Without a credit card, the subscription charge attempt will fail after that trial, and the subscription will be marked as delinquent. You may consider that to be useful

For more information about Stripe Trial, you can follow this link Using Trial Periods on Subscriptions

Body:
I am using Stripe payment gateway. I am working on a project having recurring payments.

Basically I have three plans created on Stripe,

1) Free  - 14 days, $0.00 , No trial, Should NOT be auto renewed
2) Basic - 1 Month, $15.00, No trial, auto renewed
3) Pro   - 1 Month, $25.00, No trial, auto renewed

I have some doubts as following:

1) Is it required to provide the credit card details while subscribing a customer to a Free plan? What if I don't want to provide it for now and still subscribe him to Free plan?

2) I don't want the Free plan to be auto-renewed. So subscribing any customer to Free plan, how can I identify the end of the period or cycle using webhook since there is NO end date/period is there for plan? I want to cancel the customers' subscription (having Free plan) after 14 days and redirect them to choose Basic or Pro plan with credit card details.

3) For Basic and Pro plans there is no trial period has set. But still I want to provide 14 days trial to some specific customers. Is it possible by setting trial_end while subscribing a customer to a plan (i.e. For Basic or Pro)?

4) If I specify the trial_end attribute while subscribing a customer to a plan (i.e. Basic or Pro), the charge will be created after the trial period ends. Correct me? If yes, what if I want to charge them immediate but still they must have the trial period?


问:
How can I store the conversation of LINE Bot using LINE API and HEROKU?
I created line bot using LINE API and HEROKU.
My bot works perfectly(echo example) but I wanna store the conversation with bot.
So I added the code using bufferedwriter and filewriter but txt file doesn't be created..

If I run my code on Spring boot app, the txt file created properly in the path. But if I run my code on Heroku, it doesn't.

what should I do?

答:
I guess your Heroku doesn't have the directory of C drive. Can you try this?

```<code>String path = "test.txt";
</code>```

You also need to replace Path with path

Body:
I guess your Heroku doesn't have the directory of C drive. Can you try this?

String path = "test.txt";

You also need to replace Path with path


问:
Missing com.CorePlot.Framework.docset bundle for core-plot documentation install into xCode
I am very new to both Objective-C and iOS programming. I am working my way through creating some graphs using core-plot and want to access some documentation that might help explain the examples given.

The readme file says in order to install the documentation I must:

Quit Xcode

Copy the com.CorePlot.Framework.docset bundle into ~/Library/Developer/Shared/Documentation/DocSets/

Launch Xcode, and browse Core Plot documentation in the Documentation browser

This looks easy but I am having a problem locating the "CorePlot.Framework.docset" bundle. Perhaps I am missing something simple?

Thanks.

答:
Are you using one of the release packages or building from source?

If you're using a release package without the installer, the docset is in "CorePlot x.x.x/Documentation" after unzipping the archive.

If you're using the installer, it should have placed the docset in the right place.

If you're building from source, follow the instructions here to install Doxygen and Graphviz. Open the CorePlot-CocoaTouch project and build the Documentation target. The build script will install the docset automatically.

Eric


问:
accordion button unhidden text
hi I am building a button where hide/show content when click on, however when I apply some styles to the content it won't hide anymore, I suspect it has got something to do with the css position, but can't figure it out why, could someone please help me? thanks in advance

    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
    panel.style.maxHeight = null;
    } else {
    panel.style.maxHeight = panel.scrollHeight + "px";
    }
    }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    button.accordion {
    background-color: #13294b;
    border: 2px solid #59cbe8;
    border-radius: 0px 10px 0px 10px;
    box-shadow: 7px 7px 5px #cccccc;
    color: #fff;
    cursor: pointer;
    padding: 10px 15px 10px 15px;
    margin: 4px 0px 7px 0px;
    width: 100%;
    font-size: 18px;
    transition: 0.4s;
    outline: none;
    text-align: left;
    }

    button.accordion.active, button.accordion:hover {
    background-color: #1f447b;
    }

    button.accordion:after {
    content: '\002B';
    color: #59cbe8;
    font-weight: bold;
    float: right;
    }

    button.accordion.active:after {
    content: "\2212";
    }

    .panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    }

    .action1 {
    position: absolute;
    margin-top: -115px;
    margin-left: 35px;
    width: 100%;
    color: #c1c1c1;
    font-size: 14px;
    font-weight: bold;
    }

    .action2 {
    position: absolute;
    margin-top: -115px;
    margin-left: 175px;
    width: 100%;
    color: #c1c1c1;
    font-size: 14px;
    font-weight: bold;
    }</code>```

    <button class="accordion">This is the button</button>

Recognise

Remove from play

```

答: Your paragraphs are absolutely positioned, but not relative to the panel that is hiding/showing. To position those relative to .panel, add position: relative to .panel, and the paragraphs will hide/show with `.panel.

Title: accordion button unhidden text

Body:
hi I am building a button where hide/show content when click on, however when I apply some styles to the content it won't hide anymore, I suspect it has got something to do with the css position, but can't figure it out why, could someone please help me? thanks in advance

    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
    panel.style.maxHeight = null;
    } else {
    panel.style.maxHeight = panel.scrollHeight + "px";
    }
    }
    }

    button.accordion {
    background-color: #13294b;
    border: 2px solid #59cbe8;
    border-radius: 0px 10px 0px 10px;
    box-shadow: 7px 7px 5px #cccccc;
    color: #fff;
    cursor: pointer;
    padding: 10px 15px 10px 15px;
    margin: 4px 0px 7px 0px;
    width: 100%;
    font-size: 18px;
    transition: 0.4s;
    outline: none;
    text-align: left;
    }

    button.accordion.active, button.accordion:hover {
    background-color: #1f447b;
    }

    button.accordion:after {
    content: '\002B';
    color: #59cbe8;
    font-weight: bold;
    float: right;
    }

    button.accordion.active:after {
    content: "\2212";
    }

    .panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    }

    .action1 {
    position: absolute;
    margin-top: -115px;
    margin-left: 35px;
    width: 100%;
    color: #c1c1c1;
    font-size: 14px;
    font-weight: bold;
    }

    .action2 {
    position: absolute;
    margin-top: -115px;
    margin-left: 175px;
    width: 100%;
    color: #c1c1c1;
    font-size: 14px;
    font-weight: bold;
    }

    <button class="accordion">This is the button</button>

Recognise

Remove from play


问:
Parsing a string to date gives a completely different date in Android
The string is of the format dd/mm/yyyy

I am parsing using the following code:-

```<code>Dateformat dateformatter = new SimpleDateFormat("EEE, MMM d, ''yy");
dateformatter.setLenient(false );

String temp = "7/07/2017"
Date date = null;
try {
  date = new SimpleDateFormat("dd/mm/yyyy").parse(temp);
}
catch(ParseException e){
  e.printStackTrace();
}

dateformatter.format(date);
</code>```

The value that I get for date is Sat Jan 07 00:07:00 GMT + 10:00 2017

After formatting I get Sat, Jan 7, '17

The value I expect is FRI Jul 07, '17

答:
The issue is in this line

```<code>date = new SimpleDateFormat("dd/mm/yyyy").parse(temp);
</code>```

In the SimpleDateFormat, Month is denoted with M and not m.

M - Month in year (context sensitive)

m - Minute in hour

Change this to

```<code>date = new SimpleDateFormat("dd/MM/yyyy").parse(temp);
</code>```

For more details, check the official documentation of SimpleDateFormat

Body:
The string is of the format dd/mm/yyyy

I am parsing using the following code:-

Dateformat dateformatter = new SimpleDateFormat("EEE, MMM d, ''yy");
dateformatter.setLenient(false );

String temp = "7/07/2017"
Date date = null;
try {
  date = new SimpleDateFormat("dd/mm/yyyy").parse(temp);
}
catch(ParseException e){
  e.printStackTrace();
}

dateformatter.format(date);

The value that I get for date is Sat Jan 07 00:07:00 GMT + 10:00 2017

After formatting I get Sat, Jan 7, '17

The value I expect is FRI Jul 07, '17

Body:
The issue is in this line

date = new SimpleDateFormat("dd/mm/yyyy").parse(temp);

In the SimpleDateFormat, Month is denoted with M and not m.

M - Month in year (context sensitive)

m - Minute in hour

Change this to

date = new SimpleDateFormat("dd/MM/yyyy").parse(temp);

For more details, check the official documentation of SimpleDateFormat


问:
Replacing N-level for loops with recursion in C++
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

```<code>HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World
</code>```

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

```<code>#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}
</code>```

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?

答:
You can do this pretty efficiently by using all combinations from k=1 to k=N for a vector of N elements. Using Howard Hinnant's library available here, you can use it fairly effectively. In my case, I've named the library sampling.h, which is the only external dependency and can be viewed in it's entirety here.

```<code>#include "sampling.h"
#include <iostream>
#include <vector>

/**
 *  This function can take any container that has a bidirectional
 *  iterator (std::list, std::deque, std::vector) that contains elements
 *  of type std::string or similar, that must implement an `operator+`
 *  and `operator<<` for printing.
 */
template <typename BiDirStringContainer>
void print_combinations(BiDirStringContainer& container)
{
    auto first = container.begin();
    auto last = container.end();
    for (size_t i = 1; i <= container.size(); ++i) {
        auto mid = first + i;
        for_each_combination(first, mid, last, [](auto f, auto l) {
            std::string w;
            for (; f != l; ++f) {
                w += *f;
            }
            std::cout << w << std::endl;
            return false;
        });
    }
}

int main(void)
{
    std::vector<std::string> words = {
        "Hello",
        "New",
        "World",
    };
    print_combinations(words);

    return 0;
}
</code>```

Compiling this with the C++14 standard and running it outputs:

```<code>Hello
New
World
HelloNew
HelloWorld
NewWorld
HelloNewWorld
</code>```

This is exactly what your post described. Since the lambda is a custom functor, and can store state, you can do whatever you would like with the combinations: store a copy, print them, etc.

This is dramatically faster than anything you can get in the standard library without major work, or from suggestions made for the standard library. For example, std::next_combination and std::next_permutation (the former was not included, but was suggested here). I highly suggest reading Howard Hinnant's entirely blog post: it is enlightening. The time complexity on his implementations, and brute speed beats most other suggestions. If you need high performance combinations or permutations, he's already done the work for you.

Body:
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?

Body:
You can do this pretty efficiently by using all combinations from k=1 to k=N for a vector of N elements. Using Howard Hinnant's library available here, you can use it fairly effectively. In my case, I've named the library sampling.h, which is the only external dependency and can be viewed in it's entirety here.

#include "sampling.h"
#include <iostream>
#include <vector>

/**
 *  This function can take any container that has a bidirectional
 *  iterator (std::list, std::deque, std::vector) that contains elements
 *  of type std::string or similar, that must implement an `operator+`
 *  and `operator<<` for printing.
 */
template <typename BiDirStringContainer>
void print_combinations(BiDirStringContainer& container)
{
    auto first = container.begin();
    auto last = container.end();
    for (size_t i = 1; i <= container.size(); ++i) {
        auto mid = first + i;
        for_each_combination(first, mid, last, [](auto f, auto l) {
            std::string w;
            for (; f != l; ++f) {
                w += *f;
            }
            std::cout << w << std::endl;
            return false;
        });
    }
}

int main(void)
{
    std::vector<std::string> words = {
        "Hello",
        "New",
        "World",
    };
    print_combinations(words);

    return 0;
}

Compiling this with the C++14 standard and running it outputs:

Hello
New
World
HelloNew
HelloWorld
NewWorld
HelloNewWorld

This is exactly what your post described. Since the lambda is a custom functor, and can store state, you can do whatever you would like with the combinations: store a copy, print them, etc.

This is dramatically faster than anything you can get in the standard library without major work, or from suggestions made for the standard library. For example, std::next_combination and std::next_permutation (the former was not included, but was suggested here). I highly suggest reading Howard Hinnant's entirely blog post: it is enlightening. The time complexity on his implementations, and brute speed beats most other suggestions. If you need high performance combinations or permutations, he's already done the work for you.


问:
Want to edit the HTML/PHP of a Wordpress Widget
Basically, in my theme there is called a top-widget which allows you to add a menu, which is made up of
 and
 tags. I really want to edit the HTML of this
 setup it has going, and add a few more things (like custom fields to them).

The farthest I was able to trace it was this line:

```<code><?php if ( is_front_page() ) : ?>
  <div class="container">
    <div class="row">
      <div class="col-md-4">
        <?php dynamic_sidebar( 'top_widget_left' ); ?>
      </div>
      <div class="col-md-4">
       <?php dynamic_sidebar( 'top_widget_middle' ); ?>
     </div>
     <div class="col-md-4">
      <?php dynamic_sidebar( 'top_widget_right' ); ?>
    </div>
  </div>
</div>
<?php endif; ?>
</code>```

More specifically the <?php dynamic_sidebar( 'top_widget_left' ); ?>. Any possible idea what file/location this is calling?

答:
It's depend on how it's regireted. For more detail: https://codex.wordpress.org/Function_Reference/register_sidebars

If you want to find it, use TextCrawler to find where it's registered in your script

Body:
Basically, in my theme there is called a top-widget which allows you to add a menu, which is made up of
 and
 tags. I really want to edit the HTML of this
 setup it has going, and add a few more things (like custom fields to them).

The farthest I was able to trace it was this line:

<?php if ( is_front_page() ) : ?>

        <?php dynamic_sidebar( 'top_widget_left' ); ?>

       <?php dynamic_sidebar( 'top_widget_middle' ); ?>

      <?php dynamic_sidebar( 'top_widget_right' ); ?>

<?php endif; ?>

More specifically the <?php dynamic_sidebar( 'top_widget_left' ); ?>. Any possible idea what file/location this is calling?


问:
Ruby Sinatra-settings undefined method when accessing config file
I'm developing a ruby website using sinatra/sinatra-settings, I'm getting the following error while trying to access the variables from config.yml.
My main application is:

```<code>require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/config_file'
require_relative 'web_data'

class Main < Sinatra::Base
  register Sinatra::ConfigFile
  config_file 'config.yml'

  puts settings.inspect
  c = Marshal.load(File.read(settings.svp)) rescue WebData.new(0)

  get '/a/:name' do
     c.increment
     File.open(settings.svp, 'w') {|f| f.write(Marshal.dump(c)) }
     "Hello, #{params[:name] ? params[:name] : 'world'}!"+c.getcount.to_s
  end

end
</code>```

My config.yaml is:

```<code>svp: app/systemvalues
</code>```

Error thrown is:

```<code>2016-01-13 15:35:17 - NoMethodError - undefined method `svp' for Main:Class:

/home/miguel/workspace/personal_website/app/app.rb:16:in `block in <class:Main>'
</code>```

I've tried adding the register Sinatra::ConfigFile, to no avail.

Oh and puts settings.inspect prints out Main (the class name)

答:
Verify that your YAML file has the svp value set for the three basic environments of "development", "test", "production":

```<code>svp:
  development: app/development-values
  test: app/test-values
  production: app/production-values
</code>```

Body:
I'm developing a ruby website using sinatra/sinatra-settings, I'm getting the following error while trying to access the variables from config.yml.
My main application is:

require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/config_file'
require_relative 'web_data'

class Main < Sinatra::Base
  register Sinatra::ConfigFile
  config_file 'config.yml'

  puts settings.inspect
  c = Marshal.load(File.read(settings.svp)) rescue WebData.new(0)

  get '/a/:name' do
     c.increment
     File.open(settings.svp, 'w') {|f| f.write(Marshal.dump(c)) }
     "Hello, #{params[:name] ? params[:name] : 'world'}!"+c.getcount.to_s
  end

end

My config.yaml is:

svp: app/systemvalues

Error thrown is:

2016-01-13 15:35:17 - NoMethodError - undefined method `svp' for Main:Class:

/home/miguel/workspace/personal_website/app/app.rb:16:in `block in <class:Main>'

I've tried adding the register Sinatra::ConfigFile, to no avail.

Oh and puts settings.inspect prints out Main (the class name)

Body:
Verify that your YAML file has the svp value set for the three basic environments of "development", "test", "production":

svp:
  development: app/development-values
  test: app/test-values
  production: app/production-values


问:
How to use specific repo tool version
I installed repo on my system, but why can't I see its version using 'repo --version' until 'repo init' is run!
Also to suppress repo init to connect to android repo git, I have to pass --repo-url. Is it possible to suppress this behaviour, because it forces me to use repo version from --repo-url and not the one I installed??</p>

答:
In order to ensure you use the newest version (or for compatibility), when you run repo init, repo tool will download a new version of repo in your .repo/repo. So by default, repo --version is designed to check the version in your .repo/repo.

If you want to avoid using --repo-url, you can download repo source and add the directory of repo source to your PATH environment variable.

Title: How to use specific repo tool version


问:
for and while loop confusion from brackeys 7th tutorial video
```<code>using System;

namespace SeventhConsoleProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Random NumGen = new Random ();
            int diceRoll = 0;   // The variable used to roll the dice
            int attempts = 0;   // The amount of times it takes Tom to get a 6
            int amountmodifier = 10;    //To edit the amount of times that the program loops so that I can get a more accurate average

            Console.Write ("Tom wants to roll a dice multiple times and see how long it takes to get a 6.\nTom wants to get the average of " + amountmodifier + " successful attempts ");
            Console.ReadKey ();
            Console.WriteLine ();

            for (int amount = 1; amount <= amountmodifier; amount++) {
                while (diceRoll != 6) {
                    diceRoll = NumGen.Next (1, 7);
                    attempts++;
                }
            }
            int averageafter = attempts / amountmodifier;

            Console.WriteLine ("Over " + amountmodifier + " successful attempts it took Tom an average of " + averageafter + " attempts to get a 6");
            Console.ReadKey ();
        }
    }
}
</code>```

I just recently watched Brackey's 7th video in his tutorial series on c#. I am trying to complete the challenge he left in the comments.

The initial task was to create a program in which "Tom" rolls a dice and he keeps rolling the dice until he gets a 6. The user is then suppose to be informed on how many times it took "Tom" to roll the dice before he got a 6. That part I figured out.

However, the challenge part is you have to figure out how to find the average of 10 successful attempts of "Tom" rolling a 6. This part is confusing me. My logic behind my code is that the for loop will repeat 10 times or whatever amount of times I change the variable amountmodifier to be. Every time the for loop goes through its loop it will go through a while loop which will continue until the "Tom" rolls a 6 once "Tom" rolls a 6 the while loops will exit and the for loop will run another time and that will repeat 10 times.

My idea is that the amount of "attempts" will have the information of 10 successful attempts after the for loop is complete and it will be divided by the amountmodifier to create the average of those attempts. However it will not work. From what I can conclude either the for loop is not repeating 10 times or the attempts amount is constantly resetting. I can't understand why. If anyone would explain I'd genuinely be so appreciative.

答:
The problem is here:

```<code>for (int amount = 1; amount <= amountmodifier; amount++) {
    // Add this line:
    diceRoll = 0;

    while (diceRoll != 6) {
        diceRoll = NumGen.Next (1, 7);
        attempts++;
    }
}
</code>```

The issue is that after a 6 is rolled, the value of diceRoll is 6. So the next time through the for loop, you never enter the while loop at all, since diceRoll is already 6.

The fix is to add the line I suggested to make sure diceRoll is reset to 0 (as you have it originally).

Even better, since you don't need to use diceRoll anywhere else, would be to just declare it right there:

```<code>for (int amount = 1; amount <= amountmodifier; amount++) {
    int diceRoll = 0; // and get rid of the similar line at the top of Main
</code>```

Body:
using System;

namespace SeventhConsoleProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Random NumGen = new Random ();
            int diceRoll = 0;   // The variable used to roll the dice
            int attempts = 0;   // The amount of times it takes Tom to get a 6
            int amountmodifier = 10;    //To edit the amount of times that the program loops so that I can get a more accurate average

            Console.Write ("Tom wants to roll a dice multiple times and see how long it takes to get a 6.\nTom wants to get the average of " + amountmodifier + " successful attempts ");
            Console.ReadKey ();
            Console.WriteLine ();

            for (int amount = 1; amount <= amountmodifier; amount++) {
                while (diceRoll != 6) {
                    diceRoll = NumGen.Next (1, 7);
                    attempts++;
                }
            }
            int averageafter = attempts / amountmodifier;

            Console.WriteLine ("Over " + amountmodifier + " successful attempts it took Tom an average of " + averageafter + " attempts to get a 6");
            Console.ReadKey ();
        }
    }
}

I just recently watched Brackey's 7th video in his tutorial series on c#. I am trying to complete the challenge he left in the comments.

The initial task was to create a program in which "Tom" rolls a dice and he keeps rolling the dice until he gets a 6. The user is then suppose to be informed on how many times it took "Tom" to roll the dice before he got a 6. That part I figured out.

However, the challenge part is you have to figure out how to find the average of 10 successful attempts of "Tom" rolling a 6. This part is confusing me. My logic behind my code is that the for loop will repeat 10 times or whatever amount of times I change the variable amountmodifier to be. Every time the for loop goes through its loop it will go through a while loop which will continue until the "Tom" rolls a 6 once "Tom" rolls a 6 the while loops will exit and the for loop will run another time and that will repeat 10 times.

My idea is that the amount of "attempts" will have the information of 10 successful attempts after the for loop is complete and it will be divided by the amountmodifier to create the average of those attempts. However it will not work. From what I can conclude either the for loop is not repeating 10 times or the attempts amount is constantly resetting. I can't understand why. If anyone would explain I'd genuinely be so appreciative.

Body:
The problem is here:

for (int amount = 1; amount <= amountmodifier; amount++) {
    // Add this line:
    diceRoll = 0;

    while (diceRoll != 6) {
        diceRoll = NumGen.Next (1, 7);
        attempts++;
    }
}

The issue is that after a 6 is rolled, the value of diceRoll is 6. So the next time through the for loop, you never enter the while loop at all, since diceRoll is already 6.

The fix is to add the line I suggested to make sure diceRoll is reset to 0 (as you have it originally).

Even better, since you don't need to use diceRoll anywhere else, would be to just declare it right there:

for (int amount = 1; amount <= amountmodifier; amount++) {
    int diceRoll = 0; // and get rid of the similar line at the top of Main


问:
Why listview showing the last item twice?
My listview is showing the last item twice.

I want to show the members from database with volley and MySQL, sending request from android to API which is programmed in PHP and the API returns

JSON data.

Here is my code:

```<code>String email, member_id, member_type;
ListView community_member_list;
Context context = this;

MemberAdapter memberAdapter;
List<Model> modelList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_community);

    SharedPreferences SP = getSharedPreferences("MemberSession", MODE_PRIVATE);
    Boolean member_logged_in = SP.getBoolean("member_logged_in", false);
    email = SP.getString("email", null);
    member_id = SP.getString("member_id", null);
    member_type = SP.getString("member_type", null);

    if (!member_logged_in)
    {
        Intent intent = new Intent(this, Login.class);
        startActivity(intent);
        finish();

    }else{

        community_member_list = (ListView) findViewById(R.id.community_members_list);

        memberAdapter = new MemberAdapter(getApplicationContext(), R.layout.community_list_item, modelList);
        community_member_list.setAdapter(memberAdapter);

        get_community_members();
    }

}

public void get_community_members()
{
    StringRequest stringRequest = new StringRequest(Request.Method.POST, new Login().site_url+"community",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model);
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(context, "Error "+error, Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();

            params.put("member_id", member_id);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private class MemberAdapter extends ArrayAdapter {

    private List<Model> memberList;
    private int resource;
    private LayoutInflater inflater;

    MemberAdapter(Context context, int resource, List<Model> objects) {
        super(context, resource, objects);
        memberList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {

        if(convertView == null)
        {
            convertView = inflater.inflate(resource, null);
        }

        final ImageView imageView;
        TextView textView, textView2;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textView = (TextView)convertView.findViewById(R.id.textView);
        textView2 = (TextView) convertView.findViewById(R.id.textView2);

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("http://www.plexusd.com/uploads/specialist/" + memberList.get(position).getProfile_photo(), imageView, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setImageResource(R.mipmap.avatar);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                imageView.setImageResource(R.mipmap.avatar);
            }
        });

        textView.setText("Dr. "+memberList.get(position).getFirst_name()+" "+memberList.get(position).getLast_name());
        textView2.setText(""+memberList.get(position).getDesignation()+",\n"+memberList.get(position).getOrganization());

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

Here is the picture of list from mobile.

答: you added model twice , one of it in the loop ,not of it after the loop</p>

Body:
My listview is showing the last item twice.

I want to show the members from database with volley and MySQL, sending request from android to API which is programmed in PHP and the API returns

JSON data.

Here is my code:

String email, member_id, member_type;
ListView community_member_list;
Context context = this;

MemberAdapter memberAdapter;
List<Model> modelList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_community);

    SharedPreferences SP = getSharedPreferences("MemberSession", MODE_PRIVATE);
    Boolean member_logged_in = SP.getBoolean("member_logged_in", false);
    email = SP.getString("email", null);
    member_id = SP.getString("member_id", null);
    member_type = SP.getString("member_type", null);

    if (!member_logged_in)
    {
        Intent intent = new Intent(this, Login.class);
        startActivity(intent);
        finish();

    }else{

        community_member_list = (ListView) findViewById(R.id.community_members_list);

        memberAdapter = new MemberAdapter(getApplicationContext(), R.layout.community_list_item, modelList);
        community_member_list.setAdapter(memberAdapter);

        get_community_members();
    }

}

public void get_community_members()
{
    StringRequest stringRequest = new StringRequest(Request.Method.POST, new Login().site_url+"community",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model);
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(context, "Error "+error, Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();

            params.put("member_id", member_id);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private class MemberAdapter extends ArrayAdapter {

    private List<Model> memberList;
    private int resource;
    private LayoutInflater inflater;

    MemberAdapter(Context context, int resource, List<Model> objects) {
        super(context, resource, objects);
        memberList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {

        if(convertView == null)
        {
            convertView = inflater.inflate(resource, null);
        }

        final ImageView imageView;
        TextView textView, textView2;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textView = (TextView)convertView.findViewById(R.id.textView);
        textView2 = (TextView) convertView.findViewById(R.id.textView2);

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("http://www.plexusd.com/uploads/specialist/" + memberList.get(position).getProfile_photo(), imageView, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setImageResource(R.mipmap.avatar);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                imageView.setImageResource(R.mipmap.avatar);
            }
        });

        textView.setText("Dr. "+memberList.get(position).getFirst_name()+" "+memberList.get(position).getLast_name());
        textView2.setText(""+memberList.get(position).getDesignation()+",\n"+memberList.get(position).getOrganization());

        return convertView;
    }
}

Here is the picture of list from mobile.


问:
splice() inside a for loop, what is the solution?
I'm trying to remove repetitions from this array called "bigArray" while keeping the three first positions of the array intact (even if they repeat).

My issue is that the splice() inside the for loop is not working properly, since every time it splices, the for loop skips the next position of the array (since that position is then one position lower in the array).

How do I get my function to return [0,0,0,3,2] ?

Thank you

var bigArray = [0,0,0,3,2,2,3,3,2];

function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) !== i) {
          bigArray.splice(i,1);

    }

    }

    console.log(bigArray);
    return bigArray;
}

call();```

答:
You are modifying the array using splice() on which you are running the loop. you must use a second array to store non repeating values. you can do something like this:

var bigArray = [0,0,0,3,2,2,3,3,2];
var noDuplicates = bigArray.slice(0,3);
function call() {

  for (let i=3; i < (bigArray.length); i++) {
    if (bigArray.indexOf(bigArray[i]) === i) {
          noDuplicates.push(bigArray[i]);

    }

    }

    console.log(noDuplicates);
    return noDuplicates;
}

call();```


问:
How can I access Amazon AWS S3 using GSOAP for C and C++?
I have searched everywhere for this and I could not find a single decent code. How can I access Amazon AWS S3 service using GSOAP?</p>

答:
How can I access Amazon AWS S3 using GSOAP for C and C++?

Step 1

Use gSOAP's wsd2lh tool to convert Amazon's S3 WSDL to an interface header file aws-s3.h:

wsdl2h -t typemap.dat -o aws-s3.h http://doc.s3.amazonaws.com/2006-03-01/AmazonS3.wsdl

Use option -c to generate C source code instead of the default C++ source code. The typemap.dat file is located in the gsoap directory of the gSOAP distribution.

Step 2

Use the soapcpp2 tool on the header file created from the wsdl2h tool.

soapcpp2 -C -j aws-s3.h

This generates client-side code (-C option) with C++ service proxies and objects (-j option) from the aws-s3.h header.  Omit -j for C code.

Step 3

Use the auto-generated AmazonS3SoapBindingProxy proxy methods to access AWS S3 and create a base64-encoded, HMAC-SHA1 hashed signature for AWS S3. The signature is a string with the base64-encoded version of the HMAC-SHA1 hashed string "AmazonS3" + OPERATION_NAME + Timestamp:

```<code>/*
    createbucket.cpp
    Example AWS S3 CreateBucket service invocation
*/

#include "soapAmazonS3SoapBindingProxy.h"
#include "AmazonS3SoapBinding.nsmap"
#include <fstream>

// Make allocation of primitive values quick and easy:
template<class T>
T * soap_make(struct soap *soap, T val) {
    T *p = (T*)soap_malloc(soap, sizeof(T));
    *p = val;
    return p;
}

// Make base64-encoded, HMAC-SHA1 hashed signature for AWS S3
std::string soap_make_s3__signature(struct soap *soap, char const *operation, char const *key) {
    std::string signature = "AmazonS3";
    signature += operation;
    char UTCstamp[40]; //to hold ISO 8601 time format
    time_t now;
    time(&now);
    strftime(UTCstamp, sizeof UTCstamp, "%Y-%m-%dT%H:%M:%S.000Z", gmtime(&now));
    signature += UTCstamp;
    // Get the HMAC-SHA1 digest of the signature string
    unsigned char * digest;
    digest = HMAC(EVP_sha1(), key, strlen(key),
    (unsigned char*)(signature.c_str()),
    signature.length(), NULL, NULL);
    char signatureBase64[20];
    // Convert the digest to base64
    soap_s2base64(soap, digest, signatureBase64, sizeof signatureBase64);
    return std::string(signatureBase64);
}

// Read access keys from file generated by AWS CLI
bool getAWSKeys(std::string path, std::string user, std::string &accessKey, std::string &secretKey) {
    std::ifstream credentialsFile(path.c_str());
    if (!credentialsFile.is_open())
        return false;

    std::string line;
    while (std::getline(credentialsFile, line)) {
        // Keep going until we get to the desired user
        if (line.find(user) == std::string::npos)
            continue;

        while (std::getline(credentialsFile, line)) {
            // Keep going until we get to the access key lines
            if (line.find("aws_access_key_id") == std::string::npos)
                continue;

            // Grab keys and trim whitespace
            size_t first, last;
            accessKey = line.substr(line.find_first_of('=')+1);
            first = accessKey.find_first_not_of(' ');
            if (first == std::string::npos)
                return false;
            last = accessKey.find_last_not_of(' ');
            accessKey.substr(first, last-first+1).swap(accessKey);

            std::getline(credentialsFile, line);
            secretKey = line.substr(line.find_first_of('=')+1);
            first = secretKey.find_first_not_of(' ');
            if (first == std::string::npos)
                return false;
            last = secretKey.find_last_not_of(' ');
            secretKey.substr(first, last-first+1).swap(secretKey);

            return true;
        }

    }
    return false;
}

int main(int argc, char **argv) {
    // Load AWS keys from file
    std::string accessKey, secretKey;
    // Use the path to your AWS credentials file
    std::string credentialsFile = (argc > 2 ? argv[2] : "path_to_aws_credentials_file");
    std::string user = "default";
    if (!getAWSKeys(credentialsFile, user, accessKey, secretKey)) {
        std::cout << "Couldn't read AWS keys for user " << user
                  << " from file " << credentialsFile << '\n';
        return 0;
    }

    // Create a proxy to invoke AWS S3 services
    AmazonS3SoapBindingProxy aws(SOAP_XML_INDENT);

    // Create bucket

    // Set the arguments of the CreateBucket service operation
    _s3__CreateBucket createBucketReq;
    std::string bucketName = (argc > 1 ? argv[1] : "BucketName");
    createBucketReq.Bucket = bucketName;
    createBucketReq.AWSAccessKeyId  = soap_new_std__string(aws.soap);
    *createBucketReq.AWSAccessKeyId = accessKey;
    createBucketReq.Timestamp       = soap_make(aws.soap, time(0));
    createBucketReq.Signature       = soap_new_std__string(aws.soap);
    *createBucketReq.Signature      = soap_make_s3__signature(aws.soap,
                                                              "CreateBucket",
                                                              secretKey.c_str());

    // Store the result of the service
    _s3__CreateBucketResponse createBucketRes;

    // Create a bucket
    if (aws.CreateBucket(&createBucketReq, createBucketRes)) {
        aws.soap_stream_fault(std::cerr);
    }
    /*
        NOTE: you must add the line:
           _s3__CreateBucketResponse = $ s3__CreateBucketResult* CreateBucketResponse;
        to the typemap.dat file because Amazon's response doesn't match
        their promised schema. This adds the variable CreateBucketResponse
        to the _s3__CreateBucketResponse class so we can access the response.
    */
    else if (createBucketRes.CreateBucketResponse) {
        s3__CreateBucketResult &result = *createBucketRes.CreateBucketResponse;
        std::cout << "You are the owner of bucket '" << result.BucketName << "'." << std::endl;
    }

    // Delete all managed data
    aws.destroy();

    return 0;
}
</code>```

The C code look similar, with the main difference being the use of function calls instead of method invocations, i.e. soap_call___s3__CreateBucket(&createBucketReq, &createBucketRes). All this is explained in the generated aws-s4.h file.

Compile the generated files with your source code:

```<code>c++ -DSOAP_MAXDIMESIZE=104857600 -DWITH_OPENSSL -o createbucket createbucket.cpp soapAmazonS3SoapBindingProxy.cpp soapC.cpp stdsoap2.cpp -lssl -lcrypto
</code>```

The SOAP_MAXDIMESIZE=104857600 ensures that DIME attachment sizes can be large enough while preventing denial of service attacks using DIME. The DIME header has the attachment size, so an attacker could set that arbitrary large to deplete memory resources. Other posts failed to mention this.

Run createbucket, and a new bucket will be created.

In the final .cpp file, note that we check the command line arguments (argv) when setting credentialsFile and bucketName. This allows the program to be called with arguments:

```<code>./createbucket BucketName path_to_credentials_file
</code>```

For more details on all of this, I suggest to read the excellent CodeProject article on How to use AWS S3 in C++ with gSOAP by Chris Moutsos from which parts of this explanation originates.

Body:
How can I access Amazon AWS S3 using GSOAP for C and C++?

Step 1

Use gSOAP's wsd2lh tool to convert Amazon's S3 WSDL to an interface header file aws-s3.h:

wsdl2h -t typemap.dat -o aws-s3.h http://doc.s3.amazonaws.com/2006-03-01/AmazonS3.wsdl

Use option -c to generate C source code instead of the default C++ source code. The typemap.dat file is located in the gsoap directory of the gSOAP distribution.

Step 2

Use the soapcpp2 tool on the header file created from the wsdl2h tool.

soapcpp2 -C -j aws-s3.h

This generates client-side code (-C option) with C++ service proxies and objects (-j option) from the aws-s3.h header.  Omit -j for C code.

Step 3

Use the auto-generated AmazonS3SoapBindingProxy proxy methods to access AWS S3 and create a base64-encoded, HMAC-SHA1 hashed signature for AWS S3. The signature is a string with the base64-encoded version of the HMAC-SHA1 hashed string "AmazonS3" + OPERATION_NAME + Timestamp:

/*
    createbucket.cpp
    Example AWS S3 CreateBucket service invocation
*/

#include "soapAmazonS3SoapBindingProxy.h"
#include "AmazonS3SoapBinding.nsmap"
#include &lt;fstream>

// Make allocation of primitive values quick and easy:
template&lt;class T>
T * soap_make(struct soap *soap, T val) {
    T *p = (T*)soap_malloc(soap, sizeof(T));
    *p = val;
    return p;
}

// Make base64-encoded, HMAC-SHA1 hashed signature for AWS S3
std::string soap_make_s3__signature(struct soap *soap, char const *operation, char const *key) {
    std::string signature = "AmazonS3";
    signature += operation;
    char UTCstamp[40]; //to hold ISO 8601 time format
    time_t now;
    time(&now);
    strftime(UTCstamp, sizeof UTCstamp, "%Y-%m-%dT%H:%M:%S.000Z", gmtime(&now));
    signature += UTCstamp;
    // Get the HMAC-SHA1 digest of the signature string
    unsigned char * digest;
    digest = HMAC(EVP_sha1(), key, strlen(key),
    (unsigned char*)(signature.c_str()),
    signature.length(), NULL, NULL);
    char signatureBase64[20];
    // Convert the digest to base64
    soap_s2base64(soap, digest, signatureBase64, sizeof signatureBase64);
    return std::string(signatureBase64);
}

// Read access keys from file generated by AWS CLI
bool getAWSKeys(std::string path, std::string user, std::string &accessKey, std::string &secretKey) {
    std::ifstream credentialsFile(path.c_str());
    if (!credentialsFile.is_open())
        return false;

    std::string line;
    while (std::getline(credentialsFile, line)) {
        // Keep going until we get to the desired user
        if (line.find(user) == std::string::npos)
            continue;

        while (std::getline(credentialsFile, line)) {
            // Keep going until we get to the access key lines
            if (line.find("aws_access_key_id") == std::string::npos)
                continue;

            // Grab keys and trim whitespace
            size_t first, last;
            accessKey = line.substr(line.find_first_of('=')+1);
            first = accessKey.find_first_not_of(' ');
            if (first == std::string::npos)
                return false;
            last = accessKey.find_last_not_of(' ');
            accessKey.substr(first, last-first+1).swap(accessKey);

            std::getline(credentialsFile, line);
            secretKey = line.substr(line.find_first_of('=')+1);
            first = secretKey.find_first_not_of(' ');
            if (first == std::string::npos)
                return false;
            last = secretKey.find_last_not_of(' ');
            secretKey.substr(first, last-first+1).swap(secretKey);

            return true;
        }

    }
    return false;
}

int main(int argc, char **argv) {
    // Load AWS keys from file
    std::string accessKey, secretKey;
    // Use the path to your AWS credentials file
    std::string credentialsFile = (argc > 2 ? argv[2] : "path_to_aws_credentials_file");
    std::string user = "default";
    if (!getAWSKeys(credentialsFile, user, accessKey, secretKey)) {
        std::cout &lt;&lt; "Couldn't read AWS keys for user " &lt;&lt; user
                  &lt;&lt; " from file " &lt;&lt; credentialsFile &lt;&lt; '\n';
        return 0;
    }

    // Create a proxy to invoke AWS S3 services
    AmazonS3SoapBindingProxy aws(SOAP_XML_INDENT);

    // Create bucket

    // Set the arguments of the CreateBucket service operation
    _s3__CreateBucket createBucketReq;
    std::string bucketName = (argc > 1 ? argv[1] : "BucketName");
    createBucketReq.Bucket = bucketName;
    createBucketReq.AWSAccessKeyId  = soap_new_std__string(aws.soap);
    *createBucketReq.AWSAccessKeyId = accessKey;
    createBucketReq.Timestamp       = soap_make(aws.soap, time(0));
    createBucketReq.Signature       = soap_new_std__string(aws.soap);
    *createBucketReq.Signature      = soap_make_s3__signature(aws.soap,
                                                              "CreateBucket",
                                                              secretKey.c_str());

    // Store the result of the service
    _s3__CreateBucketResponse createBucketRes;

    // Create a bucket
    if (aws.CreateBucket(&createBucketReq, createBucketRes)) {
        aws.soap_stream_fault(std::cerr);
    }
    /*
        NOTE: you must add the line:
           _s3__CreateBucketResponse = $ s3__CreateBucketResult* CreateBucketResponse;
        to the typemap.dat file because Amazon's response doesn't match
        their promised schema. This adds the variable CreateBucketResponse
        to the _s3__CreateBucketResponse class so we can access the response.
    */
    else if (createBucketRes.CreateBucketResponse) {
        s3__CreateBucketResult &result = *createBucketRes.CreateBucketResponse;
        std::cout &lt;&lt; "You are the owner of bucket '" &lt;&lt; result.BucketName &lt;&lt; "'." &lt;&lt; std::endl;
    }

    // Delete all managed data
    aws.destroy();

    return 0;
}

The C code look similar, with the main difference being the use of function calls instead of method invocations, i.e. soap_call___s3__CreateBucket(&createBucketReq, &createBucketRes). All this is explained in the generated aws-s4.h file.

Compile the generated files with your source code:

c++ -DSOAP_MAXDIMESIZE=104857600 -DWITH_OPENSSL -o createbucket createbucket.cpp soapAmazonS3SoapBindingProxy.cpp soapC.cpp stdsoap2.cpp -lssl -lcrypto

The SOAP_MAXDIMESIZE=104857600 ensures that DIME attachment sizes can be large enough while preventing denial of service attacks using DIME. The DIME header has the attachment size, so an attacker could set that arbitrary large to deplete memory resources. Other posts failed to mention this.

Run createbucket, and a new bucket will be created.

In the final .cpp file, note that we check the command line arguments (argv) when setting credentialsFile and bucketName. This allows the program to be called with arguments:

./createbucket BucketName path_to_credentials_file

For more details on all of this, I suggest to read the excellent CodeProject article on How to use AWS S3 in C++ with gSOAP by Chris Moutsos from which parts of this explanation originates.


问:
soft shadow, shadow blur in SceneKit
I add one node and try to setting shadow blur with SceneKit

here's my light config, I did try to set shadowRadius

```<code>light = [SCNLight light];
light.type = SCNLightTypeDirectional;
light.castsShadow = true;
light.shadowMode = SCNShadowModeForward;
light.shadowRadius = 5;
light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=25;
light.zNear=1;
light.zFar=1000;
</code>```

but the result is not softer than when I not set shadowRadius
it' here:

I did try to add samplecount

```<code>light = [SCNLight light];
light.type = SCNLightTypeDirectional;
light.castsShadow = true;
light.shadowMode = SCNShadowModeForward;
light.shadowRadius = 5;
// add samplecount
light.shadowSampleCount = 5;
light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=25;
light.zNear=1;
light.zFar=1000;
</code>```

result look like following

shadow seem soft but this shadow start from bottom of the node (z coordinate is 0). I spend a lot of time to set soft shadow only in the edge of node, not from bottom. But no result.

This problem also occurred when add two node cross over(not only node and geometry as SCNFloor)

My problem is how to get shadow blur(soft shadow) with direction light.

any help would be appreciated!

答:
I really can make shadow blur with orthographicScale. I don't know why, but this trick work for me. Hope can help someone

```<code>light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=100; // bigger is softer
</code>```

I also change shadowMapSize to bigger value and setting isJitteringEnabled antialiasingMode to reduce aliasing.

Title: soft shadow, shadow blur in SceneKit

Body:
I add one node and try to setting shadow blur with SceneKit

here's my light config, I did try to set shadowRadius

light = [SCNLight light];
light.type = SCNLightTypeDirectional;
light.castsShadow = true;
light.shadowMode = SCNShadowModeForward;
light.shadowRadius = 5;
light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=25;
light.zNear=1;
light.zFar=1000;

but the result is not softer than when I not set shadowRadius
it' here:

I did try to add samplecount

light = [SCNLight light];
light.type = SCNLightTypeDirectional;
light.castsShadow = true;
light.shadowMode = SCNShadowModeForward;
light.shadowRadius = 5;
// add samplecount
light.shadowSampleCount = 5;
light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=25;
light.zNear=1;
light.zFar=1000;

result look like following

shadow seem soft but this shadow start from bottom of the node (z coordinate is 0). I spend a lot of time to set soft shadow only in the edge of node, not from bottom. But no result.

This problem also occurred when add two node cross over(not only node and geometry as SCNFloor)

My problem is how to get shadow blur(soft shadow) with direction light.

any help would be appreciated!

Body:
I really can make shadow blur with orthographicScale. I don't know why, but this trick work for me. Hope can help someone

light.shadowMapSize=CGSizeMake(4000, 4000);
light.orthographicScale=100; // bigger is softer

I also change shadowMapSize to bigger value and setting isJitteringEnabled antialiasingMode to reduce aliasing.


问:
Convert Thread.Join(timeLapse) to equivalent non-thread pattern
I have the following code:

```<code>Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}
</code>```

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

答:
Here is a piece of code that I used in one of my projects.

Morever, have a look at Task.WhenAny(param Task[] task) method on MSDN. It returns the task which is completed.

```<code>var timeout = 5000;
var task = Task.Run(() => {
    Thread.Sleep(new Random().Next(3000, 7000));//Running time simulation!
    return "Say my name!";//Breaking Bad!
});
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // Task completed within timeout.
    // What if the task is faulted or canceled.
    // I did not supply a cancellation token but it can easily be added
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;
}
else {
    // timeout/cancellation logic
}
</code>```

Body:
I have the following code:

Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

Body:
Here is a piece of code that I used in one of my projects.

Morever, have a look at Task.WhenAny(param Task[] task) method on MSDN. It returns the task which is completed.

var timeout = 5000;
var task = Task.Run(() => {
    Thread.Sleep(new Random().Next(3000, 7000));//Running time simulation!
    return "Say my name!";//Breaking Bad!
});
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // Task completed within timeout.
    // What if the task is faulted or canceled.
    // I did not supply a cancellation token but it can easily be added
    // We re-await the task so that any exceptions/cancellation is rethrown.
    await task;
}
else {
    // timeout/cancellation logic
}


问:
Rspec testing No Route Matches ActionController::UrlGenerationError
I'm trying to wrap my head about Rspec and Controller tests, more specifically a JSON request.  In this case, I'm trying to hit the v1_devices_path route:

routes.rb

```<code>v1_device_scans POST   /v1/devices/:device_serial_number/scans(.:format) v1/scans#create
v1_device       GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                PUT    /v1/devices/:serial_number(.:format)              v1/devices#update
</code>```

And my controller:

controllers/v1/devices_controller.rb

```<code>class V1::DevicesController < ApplicationController
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def show
    @device = Device.find_by(serial_number: params[:serial_number])
    render :json => @device.as_json
  end

  def update
    if @device.update(device_params)
      render json: @device, status: :ok, location: @device
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
      :assigned_internal_ip,
      :assigned_external_ip,
      :assigned_gateway_ip,
      :version,
      :timezone,
      :task_id,
      :scan_status,
      :scan_progress
    )
  end

end
</code>```

As of right now my test is super simple... just want to make sure I get some results back:

spec/controllers/v1/devices_controller_spec.rb

require 'rails_helper'

```<code>RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :format => :json
    expect(response.status).to be(200)
  end
end
</code>```

After some tweaking, I've gotten to the point where it looks like my url is being created correctly, but I'm still getting the no route matches error:

```<code>  1) V1::DevicesController shows device info
     Failure/Error: get v1_device_path(device.serial_number), :format => :json

     ActionController::UrlGenerationError:
       No route matches {:action=>"/v1/devices/41442305171c430ab253ba1ad95c5c61", :controller=>"v1/devices", :format=>:json}
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/template_assertions.rb:61:in `process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `catch'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `process'
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
     # ./spec/controllers/v1/devices_controller_spec.rb:11:in `block (2 levels) in <top (required)>'
</code>```

What am I doing wrong?

答:
This is another solution to not change type into request. This error shows because of adding serial_number parameter in show devise route, you can add serial_number in your get url.

```<code>RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get :show, params: { serial_number: device.serial_number }, :format => :json
    expect(response.status).to be(200)
  end
end
</code>```

I hope this help you.

Body:
I'm trying to wrap my head about Rspec and Controller tests, more specifically a JSON request.  In this case, I'm trying to hit the v1_devices_path route:

routes.rb

v1_device_scans POST   /v1/devices/:device_serial_number/scans(.:format) v1/scans#create
v1_device       GET    /v1/devices/:serial_number(.:format)              v1/devices#show
                PATCH  /v1/devices/:serial_number(.:format)              v1/devices#update
                PUT    /v1/devices/:serial_number(.:format)              v1/devices#update

And my controller:

controllers/v1/devices_controller.rb

class V1::DevicesController < ApplicationController
  before_action :set_device, only: [:show, :update]
  respond_to :json

  def show
    @device = Device.find_by(serial_number: params[:serial_number])
    render :json => @device.as_json
  end

  def update
    if @device.update(device_params)
      render json: @device, status: :ok, location: @device
    else
      render json: @device.errors, status: :unprocessable_entity
    end
  end

  private

  def set_device
    @device = Device.find_by!(serial_number: params[:serial_number])
  end

  def device_params
    params.require(:device).permit(
      :serial_number,
      :name,
      :diagnostic_checkin_status,
      :diagnostic_dns,
      :diagnostic_ping,
      :assigned_internal_ip,
      :assigned_external_ip,
      :assigned_gateway_ip,
      :version,
      :timezone,
      :task_id,
      :scan_status,
      :scan_progress
    )
  end

end

As of right now my test is super simple... just want to make sure I get some results back:

spec/controllers/v1/devices_controller_spec.rb

require 'rails_helper'

RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get v1_device_path(device.serial_number), :format => :json
    expect(response.status).to be(200)
  end
end

After some tweaking, I've gotten to the point where it looks like my url is being created correctly, but I'm still getting the no route matches error:

  1) V1::DevicesController shows device info
     Failure/Error: get v1_device_path(device.serial_number), :format => :json

     ActionController::UrlGenerationError:
       No route matches {:action=>"/v1/devices/41442305171c430ab253ba1ad95c5c61", :controller=>"v1/devices", :format=>:json}
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/template_assertions.rb:61:in `process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `catch'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
     # /usr/local/bundle/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:33:in `process'
     # /usr/local/bundle/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
     # ./spec/controllers/v1/devices_controller_spec.rb:11:in `block (2 levels) in <top (required)>'

What am I doing wrong?

Body:
This is another solution to not change type into request. This error shows because of adding serial_number parameter in show devise route, you can add serial_number in your get url.

RSpec.describe V1::DevicesController, type: :controller do

  it "shows device info" do
    device = FactoryGirl.create(:device)
    get :show, params: { serial_number: device.serial_number }, :format => :json
    expect(response.status).to be(200)
  end
end

I hope this help you.


问:
Testing Frameworks for C
After doing some work with Ruby, Rails, and RSpec last summer and I learned to TATFT. Now I can't write code without writing tests first.

I'm taking a programming course in C next year, and I would like to learn to write C test-driven. Is it a good idea (or even possible) to do TDD with C? If so, are there any good testing frameworks compatible with C?

答:
This similar question also has a lot of answers "Unit Testing C Code"

I used RCUNIT, it is mature and has everything I need. I have also used ipl canata which is great but is very expensive so that is probability not what you want.

OwnerDisplayName: maxhawkins

Title: Testing Frameworks for C

LastEditorDisplayName: philippe

OwnerDisplayName: Gerhard