问:
Is there a way to iterate through a pandas datetime series performing a function?
I have created a custom function that describes seasonality and want to add a new column to a dataframe by applying that function to a series of datetime objects in a pandas dataframe. I'm attempting to create a list that contains the values of the date_season function applied to the dates in the dataframe.

All the variables in the date_season function below are of the type datetime.date, except for 'dif' which is a datetime.timedelta.

Here is the function:

```<code>import datetime as dt
import pandas as pd

def date_season(date):
    year = date.year
    min_season = dt.date(year,1,1)
    max_season = dt.date(year,6,30)
    dif = abs(max_season - date)
    dif_days = dif.days
    x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
    seasonality = np.sin(x * (np.pi) / 2)
    return(seasonality)
</code>```

And here is how the pandas dataframe is created:

```<code>start = dt.date(2017,1,1)
end = dt.date(2019,12,31)
df = pd.DataFrame({'Date': pd.date_range(start, end, freq="D")})
</code>```

Attempting to create a new list with the seasonality parameter:

```<code>z = []
for index, row in df.iterrows():
    z.append(date_season(row.Date))
</code>```

This returns the error message:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-105-63e9cb35ed55> in <module>()
      1 z = []
      2 for index, row in df.iterrows():
----> 3     z.append(date_season(row.Date))

<ipython-input-71-5e2b35e24e38> in date_season(date)
      3     min_season = dt.date(year,1,1)
      4     max_season = dt.date(year,6,30)
----> 5     dif = abs(max_season - date)
      6     dif_days = dif.days
      7     x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days

pandas\_libs\tslibs\timestamps.pyx in
pandas._libs.tslibs.timestamps._Timestamp.__sub__()

TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'datetime.date'
</code>```

Attempting:

```<code>new_df = df.apply(lambda x: date_season(x))
</code>```

returns

```<code>AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index Date')
</code>```

Not sure why it requires a datetime.datetime object, because the function works with single inputs in the datetime.date format. Is there a simpler way to iterate through the dates and create a new column with the results of this function?

答:
You need to define the min_season and max_season as pandas datetime objects instead of the built-in python datetime class. It's confusing but they are not completely interchangeable.

```<code>def date_season(date):
    year = date.year
    #use pandas.datetime
    min_season = pd.datetime(year,1,1)
    max_season = pd.datetime(year,6,30)
    dif = abs(max_season - date)
    dif_days = dif.days
    x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
    seasonality = np.sin(x * (np.pi) / 2)
    return(seasonality)
</code>```

Now you can use either applymap for your whole dataframe or you can use apply on a single column.

```<code>new_df = df.applymap(date_season)
</code>```

or

```<code>df['Date'].apply(date_season)
</code>```

Body:
I have created a custom function that describes seasonality and want to add a new column to a dataframe by applying that function to a series of datetime objects in a pandas dataframe. I'm attempting to create a list that contains the values of the date_season function applied to the dates in the dataframe.

All the variables in the date_season function below are of the type datetime.date, except for 'dif' which is a datetime.timedelta.

Here is the function:

import datetime as dt
import pandas as pd

def date_season(date):
    year = date.year
    min_season = dt.date(year,1,1)
    max_season = dt.date(year,6,30)
    dif = abs(max_season - date)
    dif_days = dif.days
    x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
    seasonality = np.sin(x * (np.pi) / 2)
    return(seasonality)

And here is how the pandas dataframe is created:

start = dt.date(2017,1,1)
end = dt.date(2019,12,31)
df = pd.DataFrame({'Date': pd.date_range(start, end, freq="D")})

Attempting to create a new list with the seasonality parameter:

z = []
for index, row in df.iterrows():
    z.append(date_season(row.Date))

This returns the error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-105-63e9cb35ed55> in <module>()
      1 z = []
      2 for index, row in df.iterrows():
----> 3     z.append(date_season(row.Date))

<ipython-input-71-5e2b35e24e38> in date_season(date)
      3     min_season = dt.date(year,1,1)
      4     max_season = dt.date(year,6,30)
----> 5     dif = abs(max_season - date)
      6     dif_days = dif.days
      7     x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days

pandas\_libs\tslibs\timestamps.pyx in
pandas._libs.tslibs.timestamps._Timestamp.__sub__()

TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'datetime.date'

Attempting:

new_df = df.apply(lambda x: date_season(x))

returns

AttributeError: ("'Series' object has no attribute 'year'", 'occurred at index Date')

Not sure why it requires a datetime.datetime object, because the function works with single inputs in the datetime.date format. Is there a simpler way to iterate through the dates and create a new column with the results of this function?

Body:
You need to define the min_season and max_season as pandas datetime objects instead of the built-in python datetime class. It's confusing but they are not completely interchangeable.

def date_season(date):
    year = date.year
    #use pandas.datetime
    min_season = pd.datetime(year,1,1)
    max_season = pd.datetime(year,6,30)
    dif = abs(max_season - date)
    dif_days = dif.days
    x = (((max_season - min_season).days) - dif.days * 2) / (max_season - min_season).days
    seasonality = np.sin(x * (np.pi) / 2)
    return(seasonality)

Now you can use either applymap for your whole dataframe or you can use apply on a single column.

new_df = df.applymap(date_season)

or

df['Date'].apply(date_season)


来源: stackexchange

问:
git checkout after a git add?
I wanted to know if there is a way to go back to the previous change in a file on git. If I create a .txt file, I edit it but I don't "git add" can I run "git checkout - file.txt" and go back, but is there a way to do it after doing "git add"?</p>

答:
This one is hard to find out there so here it is. If you have an uncommitted change (its only in your working copy) that you wish to revert (in SVN terms) to the copy in your latest commit, do the following:

```<code>git checkout filename
</code>```

This will checkout the file from HEAD, overwriting your change. This command is also used to checkout branches, and you could happen to have a file with the same name as a branch. All is not lost, you will simply need to type:

```<code>git checkout -- filename
</code>```

You can also do this with files from other branches, and such. man git-checkout has the details.

The rest of the Internet will tell you to use git reset --hard, but this resets all uncommitted changes you’ve made in your working copy. Type this with care.

from https://www.norbauer.com/rails-consulting/notes/git-revert-reset-a-single-file

ContentLicense: CC BY-SA 4.0

Title: git checkout after a git add?

Body:
This one is hard to find out there so here it is. If you have an uncommitted change (its only in your working copy) that you wish to revert (in SVN terms) to the copy in your latest commit, do the following:

git checkout filename

This will checkout the file from HEAD, overwriting your change. This command is also used to checkout branches, and you could happen to have a file with the same name as a branch. All is not lost, you will simply need to type:

git checkout -- filename

You can also do this with files from other branches, and such. man git-checkout has the details.

The rest of the Internet will tell you to use git reset --hard, but this resets all uncommitted changes you’ve made in your working copy. Type this with care.

from https://www.norbauer.com/rails-consulting/notes/git-revert-reset-a-single-file


问:
mysql query show only 1 result
i want to output the result based on todays date.
the problem is, the output only show 1 result?</p>

```<code>database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'<br>';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'<br>';
endwhile;
</code>```

答:
Try adding a GROUP BY statement to the second SQL statement.

you should group by the key of the elemnts you want to be shown in the end result

ContentLicense: CC BY-SA 3.0

Title: mysql query show only 1 result

Body:
i want to output the result based on todays date.
the problem is, the output only show 1 result?

database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'
';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'
';
endwhile;


问:
How to exclude columns under different conditions in R?
here my example:

```<code>TR1    COR2   DR3   VAR1 VAR2 P

0,1    0,3    0,23  10    12  3
0,2    0,4    0,45  12    13  0
</code>```

Here my doubt, The best way to make a confition that if it finds some value of p = 3, it has to eliminate the 3 first columns, if there is no P = 3 but if it is found P = 2 to eliminate the 2 first columns, but there is no P = 3 neither P = 2, but if you find P = 1 remove the first column

If my table is:

```<code>TR1    COR2   DR3   VAR1 VAR2 P

0,1    0,3    0,23  10    12  3
0,2    0,4    0,45  12    13  2
</code>```

The results have to look like this:

```<code>                   VAR1  VAR2 P

                    10    12  3
                    12    13  2
</code>```

If my table is:

```<code>    COR2   DR3   VAR1 VAR2 P

    0,3    0,23  10    12  2
    0,4    0,45  12    13  1
</code>```

The results have to look like this:

```<code>                   VAR1  VAR2 P

                    10    12  2
                    12    13  1
</code>```

If my table is:

```<code>       DR3   VAR1 VAR2 P

       0,23  10    12  1
       0,45  12    13  0
</code>```

The results have to look like this:

```<code>                   VAR1  VAR2 P

                    10    12  1
                    12    13  0
</code>```

答:
An option would be to get the first non-zero number in 'P' and use that to remove the columns

```<code>df1[-seq_len(df1$P[df1$P > 0][1])]
#  VAR1 VAR2 P
#1   10   12 2
#2   12   13 1
</code>```

It can be wrapped into a function

```<code>f1 <- function(dat, colNm) {
       dat[-seq_len(dat[[colNm]][dat[[colNm]] >0][1])]
 }

f1(df1, "P")
#  VAR1 VAR2 P
#1   10   12 2
#2   12   13 1
</code>```

Body:
here my example:

TR1    COR2   DR3   VAR1 VAR2 P

0,1    0,3    0,23  10    12  3
0,2    0,4    0,45  12    13  0

Here my doubt, The best way to make a confition that if it finds some value of p = 3, it has to eliminate the 3 first columns, if there is no P = 3 but if it is found P = 2 to eliminate the 2 first columns, but there is no P = 3 neither P = 2, but if you find P = 1 remove the first column

If my table is:

TR1    COR2   DR3   VAR1 VAR2 P

0,1    0,3    0,23  10    12  3
0,2    0,4    0,45  12    13  2

The results have to look like this:

                   VAR1  VAR2 P

                    10    12  3
                    12    13  2

If my table is:

    COR2   DR3   VAR1 VAR2 P

    0,3    0,23  10    12  2
    0,4    0,45  12    13  1

The results have to look like this:

                   VAR1  VAR2 P

                    10    12  2
                    12    13  1

If my table is:

       DR3   VAR1 VAR2 P

       0,23  10    12  1
       0,45  12    13  0

The results have to look like this:

                   VAR1  VAR2 P

                    10    12  1
                    12    13  0

Body:
An option would be to get the first non-zero number in 'P' and use that to remove the columns

df1[-seq_len(df1$P[df1$P > 0][1])]
#  VAR1 VAR2 P
#1   10   12 2
#2   12   13 1

It can be wrapped into a function

f1 <- function(dat, colNm) {
       dat[-seq_len(dat[[colNm]][dat[[colNm]] >0][1])]
 }

f1(df1, "P")
#  VAR1 VAR2 P
#1   10   12 2
#2   12   13 1


问:
Hide a HTML Label in the CSS
We have a a interactive filter on our company website, used to show people based on department, without wanting to spend more money on a developer who has access to the templates, we can make CSS changes via wordpress.

Can hide the filters themselves at the moment as they seem to be contained within a style called : #Filters_Department

Label appears like this but other labels on the page we don't want to hide.

```<code><label>Department:</label>
</code>```

This Works for part of it.

```<code>#filters_department
{
display:none
}
</code>```

Have tried:

```<code>label[for="department"]
{
display:none;
}
</code>```

答:
This selector works with attributes

[attribute="value"] - looks for attribute that is matching exactly with the "value"

[attribute^="value"] - looks for attribute that starts with the "value"

[attribute*="value"] - looks for attribute that includes "value" somewhere in it

In your case you don't have any attributes. Add
class="..." or id="..." or custom data-attr="..."

If you use class or id attributes, better use the .value {} or #value {} selector.

But note that these selectors have different importance than the attribute selectors, it is good to know when overwriting.

See the example below

label {
  display: block;
}

label[data-attr="dept-1"] {
  display: none;
}

label[class="someClass"] {
  color: blue;
  font-size: 21px;
}

.someClass {
  color: red;
  font-size: 16px;
}

/* class selector can't overwrite the attribute selector */

#someId {
  color: red;
}

/* id selector can overwrite the attribute and the class selector*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>CSS</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <label class="someClass" data-attr="dept-1">Department: 1</label>
  <label class="someClass" data-attr="dept-2">Department: 2</label>
  <label class="someClass" data-attr="dept-3" id="someId" >Department: 3</label>
</body>

</html></code>```

Title: Hide a HTML Label in the CSS

Body:
We have a a interactive filter on our company website, used to show people based on department, without wanting to spend more money on a developer who has access to the templates, we can make CSS changes via wordpress.

Can hide the filters themselves at the moment as they seem to be contained within a style called : #Filters_Department

Label appears like this but other labels on the page we don't want to hide.

Department:

This Works for part of it.

#filters_department
{
display:none
}

Have tried:

label[for="department"]
{
display:none;
}

Body:
This selector works with attributes

[attribute="value"] - looks for attribute that is matching exactly with the "value"

[attribute^="value"] - looks for attribute that starts with the "value"

[attribute*="value"] - looks for attribute that includes "value" somewhere in it

In your case you don't have any attributes. Add
class="..." or id="..." or custom data-attr="..."

If you use class or id attributes, better use the .value {} or #value {} selector.

But note that these selectors have different importance than the attribute selectors, it is good to know when overwriting.

See the example below

label {
  display: block;
}

label[data-attr="dept-1"] {
  display: none;
}

label[class="someClass"] {
  color: blue;
  font-size: 21px;
}

.someClass {
  color: red;
  font-size: 16px;
}

/* class selector can't overwrite the attribute selector */

#someId {
  color: red;
}

/* id selector can overwrite the attribute and the class selector*/

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>CSS</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <label class="someClass" data-attr="dept-1">Department: 1</label>
  <label class="someClass" data-attr="dept-2">Department: 2</label>
  <label class="someClass" data-attr="dept-3" id="someId" >Department: 3</label>
</body>

</html>


问:
C# Templates with DLL Upon calling the method Assembly error
I am trying to use a template .tt file to create the table names for an api driven application. I can do this now with a static method as such. But obviously this is not very reusable.

```<code>public string[] GetEntities()
{
    return new string[] { "Entity01", "Entity02", "Entity03" };
}
</code>```

So what I am trying to accomplish is to allow my SqlFactory to go out and get my entities. This is what I was trying:

```<code><#@ assembly name="$(SolutionDir)\MultiApiConnector\bin\SqlFactory.dll"#>
<#+
public string[] GetEntities()
{
string hostName = "";
string dbName = "";
IDatabase database = DatabaseFactory.CreateDatabaseConnection("SqlServer", "Server=" + hostName + ";Integrated security=SSPI;database=" + dbName + ";");
return  database.GetRows;
}#>
</code>```

Severity  Code    Description Project File    Line    Suppression State
  Error     Compiling transformation: The type 'Object' is defined in an
  assembly that is not referenced. You must add a reference to assembly
  'netstandard, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=cc7b13ffcd2ddd51'. MultiApiConnector   C:\Users\Dell\source\repos\MultiApiConnector\MultiApiConnector\Controllers\Common.tt    16

For my own edification I went out and did quite a number of searches about this error I looked in the current project to make sure that there was a reference to netstandard and there is. I went to the SqlFactory project and it is there as well under the sdk.
I have looked into adding the netstandard to either solution and it is already there. Tried to add a reference to my config with no luck. I have searched stackoverflow for something similar to no avail.
I am sure I am doing something wrong as I am new to templates. If you need any more information please let me know.

答:
Add a netstandard reference to your template: </p>

```<code><#@ assembly name="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" #>
<#@ assembly name="$(SolutionDir)\MultiApiConnector\bin\SqlFactory.dll"#>
<#+
    public string[] GetEntities()
    ...
</code>```

Body:
I am trying to use a template .tt file to create the table names for an api driven application. I can do this now with a static method as such. But obviously this is not very reusable.

public string[] GetEntities()
{
    return new string[] { "Entity01", "Entity02", "Entity03" };
}

So what I am trying to accomplish is to allow my SqlFactory to go out and get my entities. This is what I was trying:

<#@ assembly name="$(SolutionDir)\MultiApiConnector\bin\SqlFactory.dll"#>
<#+
public string[] GetEntities()
{
string hostName = "";
string dbName = "";
IDatabase database = DatabaseFactory.CreateDatabaseConnection("SqlServer", "Server=" + hostName + ";Integrated security=SSPI;database=" + dbName + ";");
return  database.GetRows;
}#>

Severity  Code    Description Project File    Line    Suppression State
  Error     Compiling transformation: The type 'Object' is defined in an
  assembly that is not referenced. You must add a reference to assembly
  'netstandard, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=cc7b13ffcd2ddd51'. MultiApiConnector   C:\Users\Dell\source\repos\MultiApiConnector\MultiApiConnector\Controllers\Common.tt    16

For my own edification I went out and did quite a number of searches about this error I looked in the current project to make sure that there was a reference to netstandard and there is. I went to the SqlFactory project and it is there as well under the sdk.
I have looked into adding the netstandard to either solution and it is already there. Tried to add a reference to my config with no luck. I have searched stackoverflow for something similar to no avail.
I am sure I am doing something wrong as I am new to templates. If you need any more information please let me know.

Body:
Add a netstandard reference to your template:

<#@ assembly name="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" #>
<#@ assembly name="$(SolutionDir)\MultiApiConnector\bin\SqlFactory.dll"#>
<#+
    public string[] GetEntities()
    ...


问:
SQL query select sum point
i got 2 table

i want to write sql which select score May Month, 2019 year , trimester 2
this is my code to select score from May

```<code> SELECT
    XD.user_Id, XD.[Name],XD.viTri,XD.sex ,SUM(BD.Point) as pointM
 FROM
    XemDiem XD
 INNER JOIN
    BieuDo BD On BD.user_Id = XD.user_Id
WHERE Month(BD.[DateTime]) = 5
GROUP BY
    XD.user_Id, XD.[Name],XD.viTri ,XD.sex
</code>```

the result should be look like this

答:
Try the following:</p>

```<code>select XD.user_Id, XD.[Name],XD.viTri,XD.sex
sum(case when MONTH(convert(datetime,BD.Date,5)) = 5 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as monthP,
sum(case when MONTH(convert(datetime,BD.Date,5)) >= 4 and MONTH(convert(datetime,BD.Date,5)) <= 6 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as trimesterP
sum(case when MONTH(convert(datetime,BD.Date,5)) = 5 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as yearP
from info
    XemDiem XD
 INNER JOIN
    BieuDo BD On BD.user_Id = XD.user_Id
WHERE Month(BD.[DateTime]) = 5
GROUP BY
    XD.user_Id, XD.[Name],XD.viTri ,XD.sex
</code>```

Title: SQL query select sum point

Body:
i got 2 table

i want to write sql which select score May Month, 2019 year , trimester 2
this is my code to select score from May

 SELECT
    XD.user_Id, XD.[Name],XD.viTri,XD.sex ,SUM(BD.Point) as pointM
 FROM
    XemDiem XD
 INNER JOIN
    BieuDo BD On BD.user_Id = XD.user_Id
WHERE Month(BD.[DateTime]) = 5
GROUP BY
    XD.user_Id, XD.[Name],XD.viTri ,XD.sex

the result should be look like this

Body:
Try the following:

select XD.user_Id, XD.[Name],XD.viTri,XD.sex
sum(case when MONTH(convert(datetime,BD.Date,5)) = 5 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as monthP,
sum(case when MONTH(convert(datetime,BD.Date,5)) >= 4 and MONTH(convert(datetime,BD.Date,5)) <= 6 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as trimesterP
sum(case when MONTH(convert(datetime,BD.Date,5)) = 5 and Year(convert(datetime,BD.Date,5)) = 2019 then BD.Point else 0 end) as yearP
from info
    XemDiem XD
 INNER JOIN
    BieuDo BD On BD.user_Id = XD.user_Id
WHERE Month(BD.[DateTime]) = 5
GROUP BY
    XD.user_Id, XD.[Name],XD.viTri ,XD.sex


问:
MS SQL 2012 Trigger on Insert: Insert all rows from a table
I am sorry if this question is too standard but I could not figure a way to do this   efficiently

I have 3 tables Customer, CustomerProject, and StandardProject

StandardProject table contains a list of all projects that every customer in Customer table must have.

My logic is that when a new customer is inserted into Customer table, it will trigger and insert ALL projects from StandardProject into CustomerProject

```<code>Create Table [Customer]
(
   [CID] INTEGER PRIMARY KEY IDENTITY(1,1)
 , Customer   VARCHAR(50) NOT NULL UNIQUE
)

Create Table [CustomerProject]
(
   ProjectID INTEGER PRIMARY KEY IDENTITY(1,1)
 , [CID]     INTEGER FOREIGN KEY REFERENCES [Customer](CID)
 , Project   VARCHAR(50) NOT NULL
 , CONSTRAINT UN_Customer_Project UNIQUE([CID], Project)
)

Create Table [StandardProject]
(
    ProjectID INTEGER PRIMARY KEY IDENTITY(1,1)
 ,  Project   VARCHAR(50) NOT NULL UNIQUE
)

INSERT INTO [StandardProject](Project) VALUES('PROJECT 1')
INSERT INTO [StandardProject](Project) VALUES('PROJECT 2')
INSERT INTO [StandardProject](Project) VALUES('PROJECT 3')
</code>```

Question: When I insert Customer = 'My Customer', is there be a possible trigger that can add 'Project 1',  'Project 2', 'Project 3' into CustomerProject table?

In reality, the StandardProject can have a quite a few projects and these projects can changed frequency.

```<code>CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS

INSERT INTO [CustomerProject]([CID], [Project])...
</code>```

答:
First of all, I suggest defining CustomerProject as:

```<code>CREATE TABLE [CustomerProject] (
    ProjectID INTEGER FOREIGN KEY REFERENCES [StandardProject](ProjectID),
    CID INTEGER FOREIGN KEY REFERENCES [Customer](CID),
    CONSTRAINT UN_Customer_Project UNIQUE(CID, ProjectID)
)
</code>```

This junction table only exists to store relationships between customers and their projects, not the metadata associated with a customer or project.  So, storing the Project name here is not appropriate, and is just a waste of space.

That being said, you may try using the following trigger:

```<code>CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS

INSERT INTO [CustomerProject] (ProjectID, CID)
SELECT ProjectID, INSERTED.CID
FROM StandardProject

GO
</code>```

The insert query in the above trigger makes use of INSERTED, which holds the values from the row being inserted, which includes the CID of the customer.

Body:
I am sorry if this question is too standard but I could not figure a way to do this   efficiently

I have 3 tables Customer, CustomerProject, and StandardProject

StandardProject table contains a list of all projects that every customer in Customer table must have.

My logic is that when a new customer is inserted into Customer table, it will trigger and insert ALL projects from StandardProject into CustomerProject

Create Table [Customer]
(
   [CID] INTEGER PRIMARY KEY IDENTITY(1,1)
 , Customer   VARCHAR(50) NOT NULL UNIQUE
)

Create Table [CustomerProject]
(
   ProjectID INTEGER PRIMARY KEY IDENTITY(1,1)
 , [CID]     INTEGER FOREIGN KEY REFERENCES [Customer](CID)
 , Project   VARCHAR(50) NOT NULL
 , CONSTRAINT UN_Customer_Project UNIQUE([CID], Project)
)

Create Table [StandardProject]
(
    ProjectID INTEGER PRIMARY KEY IDENTITY(1,1)
 ,  Project   VARCHAR(50) NOT NULL UNIQUE
)

INSERT INTO [StandardProject](Project) VALUES('PROJECT 1')
INSERT INTO [StandardProject](Project) VALUES('PROJECT 2')
INSERT INTO [StandardProject](Project) VALUES('PROJECT 3')

Question: When I insert Customer = 'My Customer', is there be a possible trigger that can add 'Project 1',  'Project 2', 'Project 3' into CustomerProject table?

In reality, the StandardProject can have a quite a few projects and these projects can changed frequency.

CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS

INSERT INTO [CustomerProject]([CID], [Project])...

Body:
First of all, I suggest defining CustomerProject as:

CREATE TABLE [CustomerProject] (
    ProjectID INTEGER FOREIGN KEY REFERENCES [StandardProject](ProjectID),
    CID INTEGER FOREIGN KEY REFERENCES [Customer](CID),
    CONSTRAINT UN_Customer_Project UNIQUE(CID, ProjectID)
)

This junction table only exists to store relationships between customers and their projects, not the metadata associated with a customer or project.  So, storing the Project name here is not appropriate, and is just a waste of space.

That being said, you may try using the following trigger:

CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS

INSERT INTO [CustomerProject] (ProjectID, CID)
SELECT ProjectID, INSERTED.CID
FROM StandardProject

GO

The insert query in the above trigger makes use of INSERTED, which holds the values from the row being inserted, which includes the CID of the customer.


问:
Getting RSSI value -11 is it correct?
I am working with an app that collects data( rssi value, beacon id, minor, major) from ibeacon and calculates distance. I am getting rssi value about -11  and so distance 0.0 always. is this correct rssi value? I am using altbeacon library. what is the min and max value of rssi value of ibeacon ?</p>

答:
RSSI is measured in dBm, and in this case measures the strength of the signal at the receiver.  The stronger the signal, the less negative the value will be.  A value of -11 indicates an extremely strong signal.

Bluetooth Low Energy normally has limits on the strength of the transmission imposed by international radio regulatory agencies.  A Bluetooth LE beacon transmitter that is compliant with these regulations should never put out a signal that is stronger than about -55 dBm when measured one meter away.

Moving the receiver closer to the transmitter will increase the strength of the received signal.  In theory, moving from 1 meter away to 0 meters away should increase the signal by about +41 dB.  This might make the maximum expected theoretical signal level at 0 meters away be read as -14 dBm.  (In practice, it is impossible to get an actual distance of 0 meters -- you always have some finite distance between transmitter and receiver.)

Bottom line:  A RSSI value of -11, even if measured when the receiver is touching the transmitter, is unexpectedly strong.  Two possibilities:

The beacon transmitter is stronger than allowed by international regulatory agencies. (Unlikely)

Something is wrong with the RSSI sensor on the receiving device.  There may be a problem with the Analog to Digital converter or there may be a problem with the firmware that sends the digital reading to software upstream.  (Most likely)

Title: Getting RSSI value -11 is it correct?


问:
How to convert a directory into a package?
I have a directory with some helper functions that should be put into a package. Step one is obviously naming the directory something like +mypackage\ so I can call functions with mypackage.somefunction. The problem is, some functions depend on one another, and apparently MATLAB requires package functions to call functions in the very same package still by explicitly stating the package name, so I'd have to rewrite all function calls. Even worse, should I decide to rename the package, all function calls would have to be rewritten as well. These functions don't even work correctly anymore when I cd into the directory as soon as its name starts with a +.

Is there an easier solution than rewriting a lot? <s>Or at least something self-referential like import this.* to facilitate future package renaming?</s>

edit I noticed the same goes for classes and static methods, which is why I put the self-referential part into this separate question.

答:
In truth, I don't know that you should really be renaming your packages often. It seems to me that the whole idea behind a package in MATLAB is to organize a set of related functions and classes into a single collection that you could easily use or distribute as a "toolbox" without having to worry about name collisions.

As such, placing functions and classes into packages is like a final step that you perform to make a nice polished collection of tools, so you really shouldn't have much reason to rename your packages. Furthermore, you should only have to go through once prepending the package name to package function calls.

... (pausing to think if what I'm about to suggest is a good idea ;) ) ...

However, if you really want to avoid having to go through your package and prepend your function calls with a new package name, one approach would be to use the function mfilename to get the full file path for the currently running package function, parse the path string to find the parent package directories (which start with "+"), then pass the result to the import function to import the parent packages. You could even place these steps in a separate function packagename (requiring that you also use the function evalin):

```<code>function name = packagename

  % Get full path of calling function:
  callerPath = evalin('caller', 'mfilename(''fullpath'')');

  % Parse the path string to get package directories:
  name = regexp(callerPath, '\+(\w)+', 'tokens');

  % Format the output:
  name = strcat([name{:}], [repmat({'.'}, 1, numel(name)-1) {''}]);
  name = [name{:}];

end
</code>```

And you could then place this at the very beginning of your package functions to automatically have them include their parent package namespace:

```<code>import([packagename '.*']);
</code>```

Is this a good idea? Well, I'm not sure what the computational impacts will be if you're doing this every time you call a package function. Also, if you have packages nested within packages you will get output from packagename that looks like this:

```<code>'mainpack.subpack.subsubpack'
</code>```

And the call to import will only include the immediate parent package subsubpack. If you also want to include the other parent packages, you would have to sequentially remove the last package from the above string and import the remainder of the string.

In short, this isn't a very clean solution, but it is possible to make your package a little easier to rename in this way. However, I would still suggest that it's better to view the creation of a package as a final step in the process of creating a core set of tools, in which case renaming should be an unlikely scenario and prepending package function calls with the package name would only have to be done once.

Body:
In truth, I don't know that you should really be renaming your packages often. It seems to me that the whole idea behind a package in MATLAB is to organize a set of related functions and classes into a single collection that you could easily use or distribute as a "toolbox" without having to worry about name collisions.

As such, placing functions and classes into packages is like a final step that you perform to make a nice polished collection of tools, so you really shouldn't have much reason to rename your packages. Furthermore, you should only have to go through once prepending the package name to package function calls.

... (pausing to think if what I'm about to suggest is a good idea ;) ) ...

However, if you really want to avoid having to go through your package and prepend your function calls with a new package name, one approach would be to use the function mfilename to get the full file path for the currently running package function, parse the path string to find the parent package directories (which start with "+"), then pass the result to the import function to import the parent packages. You could even place these steps in a separate function packagename (requiring that you also use the function evalin):

function name = packagename

  % Get full path of calling function:
  callerPath = evalin('caller', 'mfilename(''fullpath'')');

  % Parse the path string to get package directories:
  name = regexp(callerPath, '\+(\w)+', 'tokens');

  % Format the output:
  name = strcat([name{:}], [repmat({'.'}, 1, numel(name)-1) {''}]);
  name = [name{:}];

end

And you could then place this at the very beginning of your package functions to automatically have them include their parent package namespace:

import([packagename '.*']);

Is this a good idea? Well, I'm not sure what the computational impacts will be if you're doing this every time you call a package function. Also, if you have packages nested within packages you will get output from packagename that looks like this:

'mainpack.subpack.subsubpack'

And the call to import will only include the immediate parent package subsubpack. If you also want to include the other parent packages, you would have to sequentially remove the last package from the above string and import the remainder of the string.

In short, this isn't a very clean solution, but it is possible to make your package a little easier to rename in this way. However, I would still suggest that it's better to view the creation of a package as a final step in the process of creating a core set of tools, in which case renaming should be an unlikely scenario and prepending package function calls with the package name would only have to be done once.


问:
logging.basicConfig in Python won't work if calling logging.info() before declaring
Based on this answer, Easier way to enable verbose logging

Let's take this Python script.

```<code>import argparse
import logging

def main():
    import argparse
    import logging

    parser = argparse.ArgumentParser(
        description='A test script for http://stackoverflow.com/q/14097061/78845'
    )
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")

    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    logging.info('Shown in debug and info mode')
    logging.debug('Only shown in debug mode')

if __name__ == "__main__":
    logging.info('Starting script!')
    main()
</code>```

Running this script from terminal as python -m verbose -v won't print anything.

If you comment the line logging.info('Starting script!') from the file as in

```<code>if __name__ == "__main__":
    #logging.info('Starting script!')
    main()
</code>```

then logging works as expected.

It looks like an attempt to call a logging.info() before basicConfig is defined will fully disable any logging.

Is it a bug in logging or a common gotcha and why does this happen?

I am on Python 3.6.7.

答: Don't use basicConfig to change the level. Use logging.getLogger().setLevel(logging.DEBUG) to change the level on the root logger. One can do this on any logger or handler as well.

Body:
Based on this answer, Easier way to enable verbose logging

Let's take this Python script.

import argparse
import logging

def main():
    import argparse
    import logging

    parser = argparse.ArgumentParser(
        description='A test script for http://stackoverflow.com/q/14097061/78845'
    )
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")

    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    logging.info('Shown in debug and info mode')
    logging.debug('Only shown in debug mode')

if __name__ == "__main__":
    logging.info('Starting script!')
    main()

Running this script from terminal as python -m verbose -v won't print anything.

If you comment the line logging.info('Starting script!') from the file as in

if __name__ == "__main__":
    #logging.info('Starting script!')
    main()

then logging works as expected.

It looks like an attempt to call a logging.info() before basicConfig is defined will fully disable any logging.

Is it a bug in logging or a common gotcha and why does this happen?

I am on Python 3.6.7.


问:
Unable to speak out the adaptive card content in cortana channel
I've integrated my bot with cortana channel and can view the adaptive cards successfully.  What I need is to speak out the content of the adaptive card.  The speak property when using shows that it is deprecated.  Is there a way to speak out the content of my card? </p>

```<code>var contentCard = AdaptiveCard(qnaAnswer.title);
 Attachment attachment = new Attachment()
   {
     ContentType = AdaptiveCard.ContentType,
     Content = contentCard
   };
      reply.Attachments = new List<Attachment> { attachment };
      await turnContext.SendActivityAsync(reply);

public static AdaptiveCard AdaptiveCard(string subtitle)
 {
   AdaptiveCard card = new AdaptiveCard();
   card.Body.Add(new AdaptiveTextBlock()
  {
   Text = string.IsNullOrEmpty(subtitle) ? string.Empty : subtitle,
   Speak =text ,
  });
return card;
 }
</code>```

答:
A few things with this code.

First, if you look at the schema for AdaptiveCards, you see speak property only is valid under a card element.

https://adaptivecards.io/explorer/AdaptiveCard.html

So this implies

```<code>card.Speak = 'Whatever'
</code>```

AdaptiveCards is flexible in that you can add properties that should be ignored by the renderer... confusing because if you put in properties with the same names you won't get any errors and/or it appears something doesn't work when  expected.

The next issue is that the speak property is in the context of the entire card, not just an element like textblock.  If you want to create a mechanism that translates the card elements to speech based on hints attached to those elements, you need to write this yourself.

Finally, adding a Speak property to a card will only work in channels that support speaking AdaptiveCards.  Believe it or not, Cortana does NOT do this. You would need to copy the Speak property from the card and then attach it to the activity's speak property for Cortana to say the result.  Check out

https://learn.microsoft.com/en-us/cortana/skills/adding-speech

Body:
I've integrated my bot with cortana channel and can view the adaptive cards successfully.  What I need is to speak out the content of the adaptive card.  The speak property when using shows that it is deprecated.  Is there a way to speak out the content of my card?

var contentCard = AdaptiveCard(qnaAnswer.title);
 Attachment attachment = new Attachment()
   {
     ContentType = AdaptiveCard.ContentType,
     Content = contentCard
   };
      reply.Attachments = new List<Attachment> { attachment };
      await turnContext.SendActivityAsync(reply);

public static AdaptiveCard AdaptiveCard(string subtitle)
 {
   AdaptiveCard card = new AdaptiveCard();
   card.Body.Add(new AdaptiveTextBlock()
  {
   Text = string.IsNullOrEmpty(subtitle) ? string.Empty : subtitle,
   Speak =text ,
  });
return card;
 }

Body:
A few things with this code.

First, if you look at the schema for AdaptiveCards, you see speak property only is valid under a card element.

https://adaptivecards.io/explorer/AdaptiveCard.html

So this implies

card.Speak = 'Whatever'

AdaptiveCards is flexible in that you can add properties that should be ignored by the renderer... confusing because if you put in properties with the same names you won't get any errors and/or it appears something doesn't work when  expected.

The next issue is that the speak property is in the context of the entire card, not just an element like textblock.  If you want to create a mechanism that translates the card elements to speech based on hints attached to those elements, you need to write this yourself.

Finally, adding a Speak property to a card will only work in channels that support speaking AdaptiveCards.  Believe it or not, Cortana does NOT do this. You would need to copy the Speak property from the card and then attach it to the activity's speak property for Cortana to say the result.  Check out

https://learn.microsoft.com/en-us/cortana/skills/adding-speech


答:
Something like this.

```<code>CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS
INSERT INTO [CustomerProject]([CID], [Project])
SELECT i.CID, St.Project
    FROM inserted i,StandardProject St

</code>```

-- Check

```<code>INSERT INTO Customer (Customer) VALUES ('MyNewCustomer')

SELECT * FROM [Customer]
SELECT * FROM [CustomerProject]

Output:

CID Customer
1   MyNewCustomer

ProjectID   CID Project
1   1   PROJECT 1
2   1   PROJECT 2
3   1   PROJECT 3

</code>```

Title: MS SQL 2012 Trigger on Insert: Insert all rows from a table

Body:
Something like this.

CREATE TRIGGER InsertStandardProjects ON [Customer]
FOR INSERT
AS
INSERT INTO [CustomerProject]([CID], [Project])
SELECT i.CID, St.Project
    FROM inserted i,StandardProject St

-- Check

INSERT INTO Customer (Customer) VALUES ('MyNewCustomer')

SELECT * FROM [Customer]
SELECT * FROM [CustomerProject]

Output:

CID Customer
1   MyNewCustomer

ProjectID   CID Project
1   1   PROJECT 1
2   1   PROJECT 2
3   1   PROJECT 3


问:
.net construct / pattern to block by segment of code, not by thread
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

```<code>void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}
</code>```

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.

答:
Sort of like that.

```<code>    class Segments
    {
        public const int None = 0;
        public const int Segm1 = 1;
        public const int Segm2 = 2;
    }

    int currentSegm = 0;
    int segm1counter = 0;
    int segm2counter = 0;

    object segm1lock = new object();
    object segm2lock = new object();

    void SomeOperationA()
    {
        while (
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm1, Segments.Segm1) != Segments.Segm1
            &&
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm1, Segments.None) != Segments.None
            )
        {
            Thread.Yield();
        }

        Interlocked.Increment(ref segm1counter);
        try
        {

            //Segment1:
            //... only executes if no threads are executing in Segment2 ...
        }
        finally
        {
            lock (segm1lock)
            {
                if (Interlocked.Decrement(ref segm1counter) == 0)
                    currentSegm = Segments.None;
            }
        }
    }

    void SomeOperationB()
    {
        while (
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm2, Segments.Segm2) != Segments.Segm2
            &&
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm2, Segments.None) != Segments.None
            )
        {
            Thread.Yield();
        }

        Interlocked.Increment(ref segm2counter);
        try
        {

            //Segment2:
            //... only executes if no threads are executing in Segment2 ...
        }
        finally
        {
            lock (segm2lock)
            {
                if (Interlocked.Decrement(ref segm2counter) == 0)
                    currentSegm = Segments.None;
            }
        }
    }
</code>```

Ok, it will not work with ReaderWriter locking/

Body:
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.

Body:
Sort of like that.

    class Segments
    {
        public const int None = 0;
        public const int Segm1 = 1;
        public const int Segm2 = 2;
    }

    int currentSegm = 0;
    int segm1counter = 0;
    int segm2counter = 0;

    object segm1lock = new object();
    object segm2lock = new object();

    void SomeOperationA()
    {
        while (
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm1, Segments.Segm1) != Segments.Segm1
            &&
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm1, Segments.None) != Segments.None
            )
        {
            Thread.Yield();
        }

        Interlocked.Increment(ref segm1counter);
        try
        {

            //Segment1:
            //... only executes if no threads are executing in Segment2 ...
        }
        finally
        {
            lock (segm1lock)
            {
                if (Interlocked.Decrement(ref segm1counter) == 0)
                    currentSegm = Segments.None;
            }
        }
    }

    void SomeOperationB()
    {
        while (
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm2, Segments.Segm2) != Segments.Segm2
            &&
            Interlocked.CompareExchange(ref currentSegm, Segments.Segm2, Segments.None) != Segments.None
            )
        {
            Thread.Yield();
        }

        Interlocked.Increment(ref segm2counter);
        try
        {

            //Segment2:
            //... only executes if no threads are executing in Segment2 ...
        }
        finally
        {
            lock (segm2lock)
            {
                if (Interlocked.Decrement(ref segm2counter) == 0)
                    currentSegm = Segments.None;
            }
        }
    }

Ok, it will not work with ReaderWriter locking/


问:
shorter php cipher than md5?
For a variety of stupid reasons, the maximum length of a given form variable that we are posting to an external server is 12 characters.

I wanted to obscure that value with md5, but obviously with 12 characters that isn't going to work.  Is there a cipher with an already-made PHP function which will result in something 12 characters or less?

The security and integrity of the cipher isn't super important here.  My last resort is to just write a function which moves each letter up or down an ascii value by x.  So the goal isn't to obscure it from a cryptography expert, but just to not post it in plain text so a non-technical worker looking at it won't know what it is.

Thanks for any advice.

答:
You can make use of a larger alphabet and make hash shorter but still reversible to original value.

I implemented it here - for example, hash ee45187ab28b4814cf03b2b4224eb974 becomes 7fBKxltZiQd7TFsUkOp26w - it goes from 32 to 22 characters. And it can become even less if you use a larger alpahabet. If you use unicode, you can even encode hash with emoji...

ContentLicense: CC BY-SA 2.5

Title: shorter php cipher than md5?


问:
How 'append' works?
I want to read a file line by line, and each line may have lots of characters.

This version readline works well

```<code>func readLine(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }
    return ln, err
}
</code>```

but another doesn't work

```<code>func readLine(r *bufio.Reader) ([]byte, error) {
    line, isprefix, err := r.ReadLine()
    for isprefix && err == nil {
        var bs []byte
        bs, isprefix, err = r.ReadLine()

        line = append(line, bs...)
    }
    return line, err
}
</code>```

And I know the problem is caused by append, but I doesn't the reason, who can help me? Thanks.

The line data like this s=
e411dbebd2f7d64dafeef9b14b5c59ec60c36779d43f850e5e347abee1e1a455,1,[encoded data, 8052 characters],1000000,

This is the sample code, and the the second version of readLine didn't return the entire data what it reads.

```<code>func main() {
    reader := bufio.NewReader(strings.NewReader(s))
    fmt.Println(readLine(reader))
}
</code>```

答: First of all (in the second sample of code) you didn't collect the value of the line from the line, isprefix, err := r.ReadLine() call to the slice line before entering the loop. And this code always skips the first line of a text.

Title: How 'append' works?

Body:
I want to read a file line by line, and each line may have lots of characters.

This version readline works well

func readLine(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }
    return ln, err
}

but another doesn't work

func readLine(r *bufio.Reader) ([]byte, error) {
    line, isprefix, err := r.ReadLine()
    for isprefix && err == nil {
        var bs []byte
        bs, isprefix, err = r.ReadLine()

        line = append(line, bs...)
    }
    return line, err
}

And I know the problem is caused by append, but I doesn't the reason, who can help me? Thanks.

The line data like this s=
e411dbebd2f7d64dafeef9b14b5c59ec60c36779d43f850e5e347abee1e1a455,1,[encoded data, 8052 characters],1000000,

This is the sample code, and the the second version of readLine didn't return the entire data what it reads.

func main() {
    reader := bufio.NewReader(strings.NewReader(s))
    fmt.Println(readLine(reader))
}


问:
Adding webhook to project via CURLing Gitlab API
I'm attempting to add a webhook to a project on Gitlab. See docs

I can GET current hooks from the project with the following command so I know I'm hitting gitlab successfully:

```<code>curl -k --request GET --header "PRIVATE-TOKEN: <token>" <url>/api/v4/projects/<projectID>/hooks
</code>```

However, I'm having issue creating a hook with a specific attribute. I can create a hook with the following command:

```<code>curl -k --request POST --header "PRIVATE-TOKEN: <token>" <url>/api/v4/projects/<projectID>/hooks?url=<hookURL>
</code>```

I want to set the "merge_requests_attribute" to "true". It is "false" by default. However, I'm unsure how to set this in the command

答:
I resolved this so may as well post the answer:

Attributes on Gitlab can be manipulated with the --data tag.

So, in my case the command would include

--data "merge_requests_events=true"

Body:
I'm attempting to add a webhook to a project on Gitlab. See docs

I can GET current hooks from the project with the following command so I know I'm hitting gitlab successfully:

curl -k --request GET --header "PRIVATE-TOKEN: <token>" <url>/api/v4/projects/<projectID>/hooks

However, I'm having issue creating a hook with a specific attribute. I can create a hook with the following command:

curl -k --request POST --header "PRIVATE-TOKEN: <token>" <url>/api/v4/projects/<projectID>/hooks?url=<hookURL>

I want to set the "merge_requests_attribute" to "true". It is "false" by default. However, I'm unsure how to set this in the command


问:
how to center and bottom an button
I'm new to CSS , can anyone help me with the layout. Below is the layout I have

I want the green button to be center and in the bottom of its container div (the white area) and I'm using flexbox. Below is my code:

```<code>//html

 <div className="box-layout">
        <div className="box-layout__box">
            <h1 className="box-layout__title">Expensify</h1>
            <p>It's time to get your expenses under control</p>
            <button className="button" onClick={startLogin}>Login with Google</button>
            <button className="button_anon" onClick={startLoginAnonymously}>Try it</button>
        </div>
    </div>
</code>```

and css

```<code>.box-layout {
    background: url('/images/bg.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
}

.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
}

.button {
    background: $blue;
    border: none;
    color: white;
    font-weight: 300;
    font-size: $font-size-large;
    padding: $s-size;
}

.button_anon {
    background: green;
    border: none;
    color: white;
    font-weight: 300;
    font-size: 1.5rem;
    padding: 0.8rem;

}
</code>```

答:
Try the code
right above the green button. It seems that it should be already centered. Otherwise wrap it around a div, and align the div to center.

Title: how to center and bottom an button

Body:
I'm new to CSS , can anyone help me with the layout. Below is the layout I have

I want the green button to be center and in the bottom of its container div (the white area) and I'm using flexbox. Below is my code:

//html

Expensify

It's time to get your expenses under control

            <button className="button" onClick={startLogin}>Login with Google</button>
            <button className="button_anon" onClick={startLoginAnonymously}>Try it</button>

and css

.box-layout {
    background: url('/images/bg.jpg');
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
}

.box-layout__box{
    background: fade-out(white, .15);
    border-radius: 3px;
    padding: $l-size $m-size;
    text-align: center;
    width: 25rem;
}

.button {
    background: $blue;
    border: none;
    color: white;
    font-weight: 300;
    font-size: $font-size-large;
    padding: $s-size;
}

.button_anon {
    background: green;
    border: none;
    color: white;
    font-weight: 300;
    font-size: 1.5rem;
    padding: 0.8rem;

}

Body: Try the code <br>right above the green button. It seems that it should be already centered. Otherwise wrap it around a div, and align the div to center.


问:
How to handle an edit and delete button on the same form in ASP.NET MVC?
Consider the following markup:

```<code><h2>Edit SAS Program</h2>
@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    <label for="Name">Name</label>
    @Html.TextBoxFor(model => model.Name)

    using (Html.BeginForm("Delete", "SasProgram", FormMethod.Post))
    {
        <input type="submit" class="button" value="Delete" />
    }
    <input type="submit" class="button" value="Save Changes" />
}
</code>```

I'd like to have the Delete button on the same view as the Edit. However, it's not letting me have nested forms. What is the appropriate way to handle this situation?

I tried leveraging this answer, How to handle nested forms in ASP.NET MVC, but it's a broken link now.

答:
The OLD way to do this but still applicable is to have one form tag and change the action with multiple submit buttons.</p>

```<code><input class="btn btn-default" type="submit" value="Save" />
<input class="btn btn-default" type="submit" value="Delete" onclick="this.form.action='/SasProgram/delete/@Model.Id';" />
</code>```

Body:
Consider the following markup:

Edit SAS Program

@using (Html.BeginForm("Edit", "SasProgram", FormMethod.Post))
{
    Name
    @Html.TextBoxFor(model => model.Name)

    using (Html.BeginForm("Delete", "SasProgram", FormMethod.Post))
    {
        <input type="submit" class="button" value="Delete" />
    }
    <input type="submit" class="button" value="Save Changes" />
}

I'd like to have the Delete button on the same view as the Edit. However, it's not letting me have nested forms. What is the appropriate way to handle this situation?

I tried leveraging this answer, How to handle nested forms in ASP.NET MVC, but it's a broken link now.

Body:
The OLD way to do this but still applicable is to have one form tag and change the action with multiple submit buttons.

<input class="btn btn-default" type="submit" value="Save" />
<input class="btn btn-default" type="submit" value="Delete" onclick="this.form.action='/SasProgram/delete/@Model.Id';" />


问:
Can't able to run a Task in Airflow
Whenever I tried to run my DAG it gets success state but it can't able to run the task.
While running the first time it works perfectly

trigger_controller_dag.py:

```<code>def conditionally_trigger(context, dag_run_obj):
    c_p = context['params']['condition_param']
    if context['params']['condition_param']:
        dag_run_obj.payload = {'message': context['params']['message']}
        pp.pprint(dag_run_obj.payload)
        return dag_run_obj

dag = DAG(
    dag_id='example_trigger_controller_dag',
    default_args={
        "owner": "airflow",
        "start_date": datetime.utcnow(),
    },
    schedule_interval='@once',
)

trigger = TriggerDagRunOperator(
    task_id='test_trigger_dagrun',
    trigger_dag_id="example_trigger_target_dag",
    python_callable=conditionally_trigger,
    params={'condition_param': True, 'message': 'Hello World'},
    dag=dag,
)
</code>```

trigger_target_dag.py:

```<code>args = {
    'start_date': datetime.utcnow(),
    'owner': 'airflow',
}

dag = DAG(
    dag_id='example_trigger_target_dag',
    default_args=args,
    schedule_interval=None,
)

def run_this_func(ds, **kwargs):
    print("Remotely received value of {} for key=message".
          format(kwargs['dag_run'].conf['message']))

run_this = PythonOperator(
    task_id='run_this',
    provide_context=True,
    python_callable=run_this_func,
    dag=dag,
)
</code>```

While running the DAG I am getting the following error,
dependency 'Task Instance State' FAILED: Task is in the 'success' state which is not a valid state for execution. The task must be cleared in order to be run

答:
Instead of schedule_interval='@once' try schedule_interval=None.

@once means it will only run one time.

Title: Can't able to run a Task in Airflow

Body:
Whenever I tried to run my DAG it gets success state but it can't able to run the task.
While running the first time it works perfectly

trigger_controller_dag.py:

def conditionally_trigger(context, dag_run_obj):
    c_p = context['params']['condition_param']
    if context['params']['condition_param']:
        dag_run_obj.payload = {'message': context['params']['message']}
        pp.pprint(dag_run_obj.payload)
        return dag_run_obj

dag = DAG(
    dag_id='example_trigger_controller_dag',
    default_args={
        "owner": "airflow",
        "start_date": datetime.utcnow(),
    },
    schedule_interval='@once',
)

trigger = TriggerDagRunOperator(
    task_id='test_trigger_dagrun',
    trigger_dag_id="example_trigger_target_dag",
    python_callable=conditionally_trigger,
    params={'condition_param': True, 'message': 'Hello World'},
    dag=dag,
)

trigger_target_dag.py:

args = {
    'start_date': datetime.utcnow(),
    'owner': 'airflow',
}

dag = DAG(
    dag_id='example_trigger_target_dag',
    default_args=args,
    schedule_interval=None,
)

def run_this_func(ds, **kwargs):
    print("Remotely received value of {} for key=message".
          format(kwargs['dag_run'].conf['message']))

run_this = PythonOperator(
    task_id='run_this',
    provide_context=True,
    python_callable=run_this_func,
    dag=dag,
)

While running the DAG I am getting the following error,
dependency 'Task Instance State' FAILED: Task is in the 'success' state which is not a valid state for execution. The task must be cleared in order to be run


问:
How to search in ngFor results?
I have a JSON object and I need to iterate it and include a search functionality that displays the key and values searched in that key.

I achieved this Using a pipe and by looping over keys and its values.

COMPONENT.HTML:

```<code><input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch"  #search >

      <ul>
      <li * ngFor="let key of objectKey()" >
        <span>{{ key }}</span>
          < table >
          <tr * ngFor="let item of (testData[key] | LockFilter:'appName': search.value) as result" >
            <td>{{ item.appName }}</td>
              < /tr>
              < /table>
              < /li>
              < /ul>
</code>```

COMPONENT.TS:

```<code>testData = {
  "MyCat1": [
    {
      "appName": "Myapp1",
      "appCatName": "MyCat1"
    },
    {
      "appName": "Myapp2",
      "appCatName": "MyCat1"
    }
  ],
  "MyCat2": [
    {
      "appName": "Myapp3",
      "appCatName": "MyCat2"
    },
    {
      "appName": "Myapp4",
      "appCatName": "MyCat2"
    }
  ]
}
objectKey() {
  return Object.keys(this.testData);
}
</code>```

PIPE.TS:

```<code>transform(items: any[], field: string, value: string): any[] {

  if (!items) return [];
  if (!value) return items;

  return items.filter(str => {
    return str[field].toLowerCase().includes(value.toLowerCase());
  });

}
</code>```

Expected Results BEFORE SEARCH:
  MyCat1:
  Myapp1
  Myapp2

MyCat2:
  Myapp3
  Myapp4

AFTER SEARCH: (search string '1')
  MyCat1:
  Myapp1

Current Output Image

答:
Try this:

```<code><input [(ngModel)]="search" />
<ul>
    <li *ngFor="let key of objectKey()" [hidden]="!(testData[key] | LockFilter:'appName': search).length">
        <span>{{ key }}</span>
        <table>
            <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result">
                <td> {{ item.appName }}</td>
            </tr>
        </table>
    </li>
</ul>
</code>```

Working Demo

Title: How to search in ngFor results?

Body:
I have a JSON object and I need to iterate it and include a search functionality that displays the key and values searched in that key.

I achieved this Using a pipe and by looping over keys and its values.

COMPONENT.HTML:

<input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch"  #search >

        {{ key }}

            {{ item.appName }}

COMPONENT.TS:

testData = {
  "MyCat1": [
    {
      "appName": "Myapp1",
      "appCatName": "MyCat1"
    },
    {
      "appName": "Myapp2",
      "appCatName": "MyCat1"
    }
  ],
  "MyCat2": [
    {
      "appName": "Myapp3",
      "appCatName": "MyCat2"
    },
    {
      "appName": "Myapp4",
      "appCatName": "MyCat2"
    }
  ]
}
objectKey() {
  return Object.keys(this.testData);
}

PIPE.TS:

transform(items: any[], field: string, value: string): any[] {

  if (!items) return [];
  if (!value) return items;

  return items.filter(str => {
    return str[field].toLowerCase().includes(value.toLowerCase());
  });

}

Expected Results BEFORE SEARCH:
  MyCat1:
  Myapp1
  Myapp2

MyCat2:
  Myapp3
  Myapp4

AFTER SEARCH: (search string '1')
  MyCat1:
  Myapp1

Current Output Image

Body:
Try this:

<input [(ngModel)]="search" />
<ul>
    <li *ngFor="let key of objectKey()" [hidden]="!(testData[key] | LockFilter:'appName': search).length">
        <span>{{ key }}</span>
        <table>
            <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result">
                <td> {{ item.appName }}</td>
            </tr>
        </table>
    </li>
</ul>

Working Demo


问:
What's the best way to store the minimum differential data of a changed object?
I have an object which contains many properties, of many datatypes which is the settings for a search of a large cache. I would like to pass the values which have been changed on this object from the base settings and only the changes. I would also like to pass this information as a very short string.

So what I need is a technique for doing this in C# .NET 4 (pseudo code follows):

```<code>var changes = Diff(changedobject, baseobject);
return changes.ToShortString()
</code>```

and later on a remote machine which only knows the object

```<code>var changedobject = CreateObject(diffstring)
</code>```

Any ideas would be much appreciated.

Thanks

答:
I do not have a code for you but this should be pretty clear

Create a metadata class which using
  reflection, gets the properties of the
  object and caches the getter method of
  each. Then for each property, it does
  the same if it is a complex property,
  etc ... so you get an object graph
  similar to your class. Then when
  passed two objects of the same type,
  this recursively loops through the
  metadata and calls getter in order to
  compare and returns the result. You
  can also make it generically typed.

Implementaion would be something like this:

```<code>public class Metadata<T>
{
    private Dictionary<string, Metadata<T>> _properties = new Dictionary<string, Metadata<T>>();
    private MethodInfo _getter;

    private void BuildMetadata()
    {
        Type t = typeof (T);
        foreach (PropertyInfo propertyInfo in t.GetProperties())
        {
            // ....
        }
    }
}
</code>```

Body:
I have an object which contains many properties, of many datatypes which is the settings for a search of a large cache. I would like to pass the values which have been changed on this object from the base settings and only the changes. I would also like to pass this information as a very short string.

So what I need is a technique for doing this in C# .NET 4 (pseudo code follows):

var changes = Diff(changedobject, baseobject);
return changes.ToShortString()

and later on a remote machine which only knows the object

var changedobject = CreateObject(diffstring)

Any ideas would be much appreciated.

Thanks

Body:
I do not have a code for you but this should be pretty clear

Create a metadata class which using
  reflection, gets the properties of the
  object and caches the getter method of
  each. Then for each property, it does
  the same if it is a complex property,
  etc ... so you get an object graph
  similar to your class. Then when
  passed two objects of the same type,
  this recursively loops through the
  metadata and calls getter in order to
  compare and returns the result. You
  can also make it generically typed.

Implementaion would be something like this:

public class Metadata<T>
{
    private Dictionary<string, Metadata<T>> _properties = new Dictionary<string, Metadata<T>>();
    private MethodInfo _getter;

    private void BuildMetadata()
    {
        Type t = typeof (T);
        foreach (PropertyInfo propertyInfo in t.GetProperties())
        {
            // ....
        }
    }
}


问:
Loading class through Jars in scala
I am trying to load a class from target Jar, I saw some examples and tried to replicate, but unfortunately i couldn't.

What am I doing wrong here:

```<code>import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)
</code>```

The class that is inside of jar is the following:

```<code>package typeLoader.testJars

class DummySimpleClass {

  def printer(): Unit = println("Hello World!")

}
</code>```

And the error that I got is:

```<code>java.lang.ClassNotFoundException: scala.typeLoader.testJars.DummySimpleClass.scala
  at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at efeawfew.JavaTest$.<init>(JavaTest.scala:13)
</code>```

Any ideas?

Edited: Added the jar path

答:
you need to mention the package name as well</p>
```<code> import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("typeLoader.testJars.DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)
</code>```

Title: Loading class through Jars in scala

Body:
I am trying to load a class from target Jar, I saw some examples and tried to replicate, but unfortunately i couldn't.

What am I doing wrong here:

import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)

The class that is inside of jar is the following:

package typeLoader.testJars

class DummySimpleClass {

  def printer(): Unit = println("Hello World!")

}

And the error that I got is:

java.lang.ClassNotFoundException: scala.typeLoader.testJars.DummySimpleClass.scala
  at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at efeawfew.JavaTest$.<init>(JavaTest.scala:13)

Any ideas?

Edited: Added the jar path

Body:
you need to mention the package name as well

 import java.io.File
import java.net.{URL, URLClassLoader}

  val jarPathName = "C:\\Users\\Pedro Luis\\IdeaProjects\\Metamorphosis\\test\\typeLoader\\testJars\\DummySimpleClass3.jar"

  val classLoader = new URLClassLoader(Array[URL](new File(jarPathName).toURI.toURL))
  val classToLoad = classLoader.loadClass("typeLoader.testJars.DummySimpleClass.scala")
  val method = classToLoad.getDeclaredMethod("printer")
  val instance = classToLoad.newInstance()

  method.invoke(instance)


问:
Python: read a csv file generated dynamically by an API?
I want to read into pandas the csv generated by this URL:

https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=demo&datatype=csv

How should this be done?

答:
I believe you can just read it with pd.read_csv

```<code>import pandas as pd
URL = 'https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=demo&datatype=csv'

df = pd.read_csv(URL)
</code>```

Results:

Body:
I believe you can just read it with pd.read_csv

import pandas as pd
URL = 'https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=demo&datatype=csv'

df = pd.read_csv(URL)

Results:


问:
Event handling after HTML injection with Vue.js
Vue is not registering event handler for HTML injected objects.  How do I do this manually or what is a better way to work around my problem?

Specifically, I send a query to my server to find a token in text and return the context (surrounding text) of that token as it exists in unstructured natural language.  The server also goes through the context and finds a list of those words that also happen to be in my token set.

When I render to my page I want all of these found tokens in the list to be clickable so that I can send the text of that token as a new search query.  The big problem I am having is my issue does not conform to a template.  The clickable text varies in number and positioning.

An example of what I am talking about is that my return may look like:

```<code>{
   "context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
   "chunks": ['human events', 'one people', 'political bands']
}
</code>```

And the resulting output I am looking for is the sentence looks something like this in psuedocode:

```<code>When in the Course of <a @click='search("human events")'>human events</a>, it becomes necessary for <a @click='search("one people")'>one people</a> to dissolve the <a @click='search("political bands")'>political bands</a> which have connected
</code>```

This is what I have tried so far though the click handler is not registered and the function never gets called:

<v-flex xs10 v-html="addlink(context.context, context.chunks)"></v-flex>
```

<p>and in my methods section:</p>

```addlink: function(words, matchterms){
                for(var index in matchterms){
                    var regquery = matchterms[index].replace(this.regEscape, '\\$&');
                    var query = matchterms[index];
                    var regEx = new RegExp(regquery, "ig");
                    words = words.replace(regEx, '' + query + '');
                }
                return words;
            }
```

As I said, this does not work and I know why.  This is just showing that because of the nature of the problem is seems like regex is the correct solution but that gets me into a v-html injection situation.  Is there something I can do in Vue to register the event handlers or can some one tell me a better way to load this data so I keep my links inline with the sentence and make them functional as well?

答:
I've already posted one answer but I've just realised that there's a totally different approach that might work depending on your circumstances.

You could use event delegation. So rather than putting click listeners on each  you could put a single listener on the wrapper element. Within the listener you could then check whether the clicked element was an  (using event.target) and act accordingly.

Body:
Vue is not registering event handler for HTML injected objects.  How do I do this manually or what is a better way to work around my problem?

Specifically, I send a query to my server to find a token in text and return the context (surrounding text) of that token as it exists in unstructured natural language.  The server also goes through the context and finds a list of those words that also happen to be in my token set.

When I render to my page I want all of these found tokens in the list to be clickable so that I can send the text of that token as a new search query.  The big problem I am having is my issue does not conform to a template.  The clickable text varies in number and positioning.

An example of what I am talking about is that my return may look like:

{
   "context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
   "chunks": ['human events', 'one people', 'political bands']
}

And the resulting output I am looking for is the sentence looks something like this in psuedocode:

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected

This is what I have tried so far though the click handler is not registered and the function never gets called:

<v-flex xs10 v-html="addlink(context.context, context.chunks)"></v-flex>

and in my methods section:

addlink: function(words, matchterms){
                for(var index in matchterms){
                    var regquery = matchterms[index].replace(this.regEscape, '\\$&');
                    var query = matchterms[index];
                    var regEx = new RegExp(regquery, "ig");
                    words = words.replace(regEx, '' + query + '');
                }
                return words;
            }

As I said, this does not work and I know why.  This is just showing that because of the nature of the problem is seems like regex is the correct solution but that gets me into a v-html injection situation.  Is there something I can do in Vue to register the event handlers or can some one tell me a better way to load this data so I keep my links inline with the sentence and make them functional as well?

Body:
I've already posted one answer but I've just realised that there's a totally different approach that might work depending on your circumstances.

You could use event delegation. So rather than putting click listeners on each <a> you could put a single listener on the wrapper element. Within the listener you could then check whether the clicked element was an <a> (using event.target) and act accordingly.


问:
Accessibility on back to top link
I am working on a web page which is relatively long (4+ pages). For ease of use I have added the back to top link at the bottom of the page.

I would like to know, whether I can skip this link from screen readers or assistive tools by using aria-hidden="true" and tabindex="-1". Does this fail the accessibility criteria ?

Since the back to top arrow is visible at the bottom of the page, is it necessary to make this link available for screen reader users ?  So far my understanding is home key serves as back to top for keyboard/screen reader users.

Any suggestions would be really helpful.

答:
You shouldn't be focusing on any one single user's experience. For example, if you have that 'Back to Top' link in logical spots, it should not be taken out of tab order because you're only considering one type of user experience. A the same time, accessible features shouldn't impede on a normal experience.

That said, on a pure development basis, links should receive focus so it does fail since it's not completely operable.

Title: Accessibility on back to top link


问:
How to deal with duplicate elements in the list in Haskell

Possible Duplicate:

  Searching through list

I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.

```<code>Main>  once [2,3,2,4] 2
False
Main> once [1..100] 2
True
</code>```

And here is my current code:

```<code>once :: Int -> [Int] -> Bool
once x [] = False
once x (y:ys) = (x==y) || (once x ys)
</code>```

It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false.
Need help with this, thanks!

答:
There are many possibilities doing that. If you know that the list is finite, you could say:

```<code>once x xs = length (filter (==x) xs) == 1
</code>```

(If it's not finite, there is no solution.)

By the way, you had it almost in your solution, you just replace

```<code>|| (once x ys)
</code>```

with

```<code>&& (x `notElem` ys)
</code>```

Body:
Possible Duplicate:

  Searching through list

I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.

Main>  once [2,3,2,4] 2
False
Main> once [1..100] 2
True

And here is my current code:

once :: Int -> [Int] -> Bool
once x [] = False
once x (y:ys) = (x==y) || (once x ys)

It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false.
Need help with this, thanks!

Body:
There are many possibilities doing that. If you know that the list is finite, you could say:

once x xs = length (filter (==x) xs) == 1

(If it's not finite, there is no solution.)

By the way, you had it almost in your solution, you just replace

|| (once x ys)

with

&& (x `notElem` ys)


问:
How to update dataframe values based on conditions?
I am needing to see how I can update dataframe values in R based on a condition and then use a query to SQL Server to make the calculations and replace that value within the dataframe.

Right now for example, my dataframe looks like this:

```<code>empID     name     description     annl_salary
123       John     driver          0
789       Smith    temp            0
246       Joe      manager         60000
</code>```

So basically for example, any user that is "temp", the annl_salary column for them will always show 0, but for the "driver" description sometimes there will be 0 for this description and so I am needing to see if there is a way to:

Check to see if there are any 0 values in the annl_salary column where the description IS NOT equal to "temp"

If there are any, then run a SQL Query to calculate the salary and update the 0 value in the dataframe for each specific user that has a 0 salary and is not a temp

Then sort the dataframe by annl_salary and description in ascending order and export to xlsx file

I am still new to R and so far I have this but I am stuck:

```<code>library(RODBC)
library(xlsx)

data <- read.xlsx("Book1.xlsx", sheetName = "Sheet1")

if(data$annl_salary == 0 & data$description != "temp"){data$annl_salary = "SQL Query from RODBC to update the values for each user with 0 and not driver"}
</code>```

答:
I would try something like this but it's hard to know without understanding the structure of the SQL database you need to query.</p>

```<code>library(RODBC)

channel <- odbcConnect("database")
sqlQuery(channel, paste("SQL QUERY"))

data$annl_salary <- ifelse(data$description != 'Temp' & data$annl_salary == 0, query, data$annl_salary)

data <- data %>%
    arrange(annl_salary)

</code>```

Body:
I am needing to see how I can update dataframe values in R based on a condition and then use a query to SQL Server to make the calculations and replace that value within the dataframe.

Right now for example, my dataframe looks like this:

empID     name     description     annl_salary
123       John     driver          0
789       Smith    temp            0
246       Joe      manager         60000

So basically for example, any user that is "temp", the annl_salary column for them will always show 0, but for the "driver" description sometimes there will be 0 for this description and so I am needing to see if there is a way to:

Check to see if there are any 0 values in the annl_salary column where the description IS NOT equal to "temp"

If there are any, then run a SQL Query to calculate the salary and update the 0 value in the dataframe for each specific user that has a 0 salary and is not a temp

Then sort the dataframe by annl_salary and description in ascending order and export to xlsx file

I am still new to R and so far I have this but I am stuck:

library(RODBC)
library(xlsx)

data <- read.xlsx("Book1.xlsx", sheetName = "Sheet1")

if(data$annl_salary == 0 & data$description != "temp"){data$annl_salary = "SQL Query from RODBC to update the values for each user with 0 and not driver"}

Body:
I would try something like this but it's hard to know without understanding the structure of the SQL database you need to query.

library(RODBC)

channel <- odbcConnect("database")
sqlQuery(channel, paste("SQL QUERY"))

data$annl_salary <- ifelse(data$description != 'Temp' & data$annl_salary == 0, query, data$annl_salary)

data <- data %>%
    arrange(annl_salary)


问:
Why can't I use execl() to run a bash script?
I'm trying to run a bash script from a website button on a raspberry pi, where the script is located in home/pi/. The code snippet below shows my current solution. Whenever the website button is pressed, it calls this block of code in a c file.

```<code>else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/bash";
        char name[40];
        strcpy(name, "home/pi/SelfTest.sh");
        execl(command, command, name, NULL);
        return 0;
    }
</code>```

I'm running this on a Raspberry Pi 3+, the script I'm running has 777 permissions and is owned by pi:www-data, if that helps.

I tested to see if the IF block actually got called by just having it create an empty directory called 'TEST'. The bottom snippet of code shows how I approached that. This seems to work without issue (as soon as I press the button on the website, I 'ls' home/pi/ and a new folder called 'TEST' is there). Unfortunately, when I run the top snippet of code(to run SelfTest.sh), the script doesn't run (the script itself is supposed to record the output to a log file with a timestamp, and pressing the button does not update the timestamp. The timestamp only updates when I run the script from within the terminal)

```<code>else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/mkdir";
        char name[40];
        strcpy(name, "/home/pi/TEST");
        execl(command, command, name, NULL);
        return 0;
    }
</code>```

What should be happening every time I press the website button is that it should run SelfTest.sh. I should be able to verify this by reading the logfile, but it never gets updated when I press the website button.

Please let me know if you need any extra information!

答: Apparently I'm super clumsy and didn't realize that I didn't need bash. I changed 'char *command = "/bin/bash";' to 'char *command = "/bin/sh";' and the script ran as expected!</p>

Body:
I'm trying to run a bash script from a website button on a raspberry pi, where the script is located in home/pi/. The code snippet below shows my current solution. Whenever the website button is pressed, it calls this block of code in a c file.

else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/bash";
        char name[40];
        strcpy(name, "home/pi/SelfTest.sh");
        execl(command, command, name, NULL);
        return 0;
    }

I'm running this on a Raspberry Pi 3+, the script I'm running has 777 permissions and is owned by pi:www-data, if that helps.

I tested to see if the IF block actually got called by just having it create an empty directory called 'TEST'. The bottom snippet of code shows how I approached that. This seems to work without issue (as soon as I press the button on the website, I 'ls' home/pi/ and a new folder called 'TEST' is there). Unfortunately, when I run the top snippet of code(to run SelfTest.sh), the script doesn't run (the script itself is supposed to record the output to a log file with a timestamp, and pressing the button does not update the timestamp. The timestamp only updates when I run the script from within the terminal)

else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/mkdir";
        char name[40];
        strcpy(name, "/home/pi/TEST");
        execl(command, command, name, NULL);
        return 0;
    }

What should be happening every time I press the website button is that it should run SelfTest.sh. I should be able to verify this by reading the logfile, but it never gets updated when I press the website button.

Please let me know if you need any extra information!


问:
stacking fullsized background images using bootstrap horizontally?
I need to stack 3 background images fully sized in the background using bootstrap in React. The images are wonky and have weird sizing and have whitespace between them.

I've tried messing with the image dimensions but it won't be responsive.

```<code><div className="container">
    <div style={{ backgroundImage: `url(${CityLife})`, backgroundSize: '100% auto', minHeight: '100%', minHeight: '1000px', backgroundRepeat: 'no-repeat' }}>
        Test2
    </div>
    <div  style={{ backgroundImage: `url(${GoodLife})`, backgroundSize: '100% auto', minHeight: '100%', minHeight: '1000px', backgroundRepeat: 'no-repeat' }}>
        Test2
    </div>
</div>
</code>```

It would be great if the pictures stacked up in full size on top of each other while being reponsive.

答:
Flexbox is great for things like this.

You mentioned you need to use Bootstrap, which is fine, you can mix the two.

Flex properties to get it to work:

.parent {
  display: flex;
  width: 100vw;
  height: 100vh;
  flex-wrap: wrap;
  flex-direction: row // or 'column' for inline
}

.img {
  width: 100vw;
  height: 100vh;
  padding: 5%;
}

.img-1,
.img-2,
.img-3 {
  /* you can inherit some of these properties with another css class */
  background: url(https://picsum.photos/1000/1000);
  display: block;
  padding: 4%;
  background-size: cover;
  background-repeat: no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="img img-1"> one </div>
  <div class="img img-2"> two </div>
  <div class="img img-3"> three </div>
</div></code>```

Body:
I need to stack 3 background images fully sized in the background using bootstrap in React. The images are wonky and have weird sizing and have whitespace between them.

I've tried messing with the image dimensions but it won't be responsive.

    <div style={{ backgroundImage: `url(${CityLife})`, backgroundSize: '100% auto', minHeight: '100%', minHeight: '1000px', backgroundRepeat: 'no-repeat' }}>
        Test2

    <div  style={{ backgroundImage: `url(${GoodLife})`, backgroundSize: '100% auto', minHeight: '100%', minHeight: '1000px', backgroundRepeat: 'no-repeat' }}>
        Test2

It would be great if the pictures stacked up in full size on top of each other while being reponsive.

Body:
Flexbox is great for things like this.

You mentioned you need to use Bootstrap, which is fine, you can mix the two.

Flex properties to get it to work:

.parent {
  display: flex;
  width: 100vw;
  height: 100vh;
  flex-wrap: wrap;
  flex-direction: row // or 'column' for inline
}

.img {
  width: 100vw;
  height: 100vh;
  padding: 5%;
}

.img-1,
.img-2,
.img-3 {
  /* you can inherit some of these properties with another css class */
  background: url(https://picsum.photos/1000/1000);
  display: block;
  padding: 4%;
  background-size: cover;
  background-repeat: no-repeat;
}

<div class="parent">
  <div class="img img-1"> one </div>
  <div class="img img-2"> two </div>
  <div class="img img-3"> three </div>
</div>


问:
Why is the XPath not valid?
The problem is that the XPath I get from Chrome is not correct or I do not know how to edit it so I can make it usable. I wanna parse it so i can get the results through a discord bot.

I did not try anything at all, I have no experience in using XPath so that is why I am here.

```<code>//*[@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2]
</code>```

What should happen is(if the xpath path would work) that I get a result through a discord bot but the path is not correct.

Could not store a value from path //*
   [@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2], Check that the path is valid!

答:
Use this xpath.

```<code> //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td
</code>```

If you expecting value 33 from the xpath then you can use either

```<code> //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td/text()
</code>```

or

```<code>  //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td/@text
</code>```

Screenshot:

Title: Why is the XPath not valid?

Body:
The problem is that the XPath I get from Chrome is not correct or I do not know how to edit it so I can make it usable. I wanna parse it so i can get the results through a discord bot.

I did not try anything at all, I have no experience in using XPath so that is why I am here.

//*[@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2]

What should happen is(if the xpath path would work) that I get a result through a discord bot but the path is not correct.

Could not store a value from path //*
   [@id="home"]/div/div/div[1]/div/table/tbody/tr[1]/td[2], Check that the path is valid!

Body:
Use this xpath.

 //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td

If you expecting value 33 from the xpath then you can use either

 //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td/text()

or

  //table[@class='table bb']//td[strong[.='Level']]/following-sibling::td/@text

Screenshot: