问:
How to add two category lists to dictionary in python
I have a dataframe

```<code>df =
          name     age     character
0          A        10       fire
1          A        15       water
2          A        20       earth
3          A        25       air
4          B        10       fire
5          B        7        air
</code>```

I want to convert this dataframe to dictionary, so that output will be,

```<code>dic = {'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
       'B': [[10, 7], ['fire', 'air']] }
</code>```

What I tried is,

from collections import defaultdict
dic = defaultdict(list)
for i in range(len(df)):
    dic[df.loc['name', i]].append(df.loc['age', i])
    dic[df.loc['name', i]].append(df.loc['character', i]) # this is wrong. It appends to existing list.
```

If I declare dic = defaultdict([[], []]), it throws error that first argument of defaultdict must be callable or None.

How can I improve this dictionary?

答:
You may use combination of pivot_table and to_dict

```<code>dic = (df.pivot_table(columns='name', values=['age','character'], aggfunc=list)
         .to_dict('l'))

Out[107]:
{'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
 'B': [[10, 7], ['fire', 'air']]}
</code>```

If you dataframe have exact 3 columns name, age, character, you may simply ignore values= parameter

```<code>dic = df.pivot_table(columns='name', aggfunc=list).to_dict('l')
</code>```

As you said in comment, to strip whitespaces, you need to pre-process df with str.strip before calling pivot_table as follows

```<code>df.update(df.select_dtypes('object').apply(lambda x: x.str.strip()))
dic = df.pivot_table(columns='name', aggfunc=list).to_dict('l')
</code>```

Body:
I have a dataframe

df =
          name     age     character
0          A        10       fire
1          A        15       water
2          A        20       earth
3          A        25       air
4          B        10       fire
5          B        7        air

I want to convert this dataframe to dictionary, so that output will be,

dic = {'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
       'B': [[10, 7], ['fire', 'air']] }

What I tried is,

from collections import defaultdict
dic = defaultdict(list)
for i in range(len(df)):
    dic[df.loc['name', i]].append(df.loc['age', i])
    dic[df.loc['name', i]].append(df.loc['character', i]) # this is wrong. It appends to existing list.

If I declare dic = defaultdict([[], []]), it throws error that first argument of defaultdict must be callable or None.

How can I improve this dictionary?

Body:
You may use combination of pivot_table and to_dict

dic = (df.pivot_table(columns='name', values=['age','character'], aggfunc=list)
         .to_dict('l'))

Out[107]:
{'A': [[10, 15, 20, 25], ['fire', 'water', 'earth', 'air']],
 'B': [[10, 7], ['fire', 'air']]}

If you dataframe have exact 3 columns name, age, character, you may simply ignore values= parameter

dic = df.pivot_table(columns='name', aggfunc=list).to_dict('l')

As you said in comment, to strip whitespaces, you need to pre-process df with str.strip before calling pivot_table as follows

df.update(df.select_dtypes('object').apply(lambda x: x.str.strip()))
dic = df.pivot_table(columns='name', aggfunc=list).to_dict('l')


来源: stackexchange

问:
Python - simple NumPy array not showing expected values
Python newbie here.

I think I have written some pretty straightforward code to extract ONLY the numbers from a received string.

It appears to be working EXCEPT I am trying to store the retrieved numbers in a NumPy array for further processing but I am seeing only 'wacky' numbers instead.

```<code>import numpy as np
#import array
apiString = " 'open': 1.082865 'close': 1.08287 'min': 1.08266 'max': 1.08295 'volume': 888"
np_Myarr01 = np.empty([1,5], dtype=float)

def Find_numbers():
    for word in apiString.split():
        try:
            thisNumber=float(word)
            print ("Found", thisNumber)
            Store_number(thisNumber)
        except ValueError:
            pass
    return

def Store_number(thisNumber):
    np.append(np_Myarr01, thisNumber)
    print("store " + str(thisNumber))
    return

# START OF MAIN PROGRAM

Find_numbers()
print (np_Myarr01)
</code>```

*** OUTPUT *******************

```<code>Found 1.082865
store 1.082865
Found 1.08287
store 1.08287
Found 1.08266
store 1.08266
Found 1.08295
store 1.08295
Found 888.0
store 888.0
[[  2.17306514e-316   0.00000000e+000   6.92674292e-310   6.92674292e-310
    2.37151510e-322]]
</code>```

I was HOPING for the array to read

```<code>[[ 1.082865  1.08287  1.08266  1.08295  888.0]]
</code>```

Any help would be gratefully appreciated. Thank you!

答:
You can use a mixture of str.split() and re.search to extract the numbers from your apiString:

This:

```<code>apiString = " 'open': 1.082865 'close': 1.08287 'min': 1.08266 'max': 1.08295 'volume': 888"

my_array = np.array([float(x) for x in apiString.split() if not re.search('[a-zA-Z]', x)])
</code>```

Will yield:

```<code>array([  1.082865,   1.08287 ,   1.08266 ,   1.08295 , 888.      ])
</code>```

Details:

1)  apiString.split() will split your string in a list of strings where there are spaces in the original string

2) re.search('[a-zA-Z]', x) will return True if the string stored in x contains an uppercase or lowercase letter (i.e. not a number) (also why we use not here)

3) float(x) converts the string '1.808' to type float

ContentLicense: CC BY-SA 4.0

Body:
Python newbie here.

I think I have written some pretty straightforward code to extract ONLY the numbers from a received string.

It appears to be working EXCEPT I am trying to store the retrieved numbers in a NumPy array for further processing but I am seeing only 'wacky' numbers instead.

import numpy as np
#import array
apiString = " 'open': 1.082865 'close': 1.08287 'min': 1.08266 'max': 1.08295 'volume': 888"
np_Myarr01 = np.empty([1,5], dtype=float)

def Find_numbers():
    for word in apiString.split():
        try:
            thisNumber=float(word)
            print ("Found", thisNumber)
            Store_number(thisNumber)
        except ValueError:
            pass
    return

def Store_number(thisNumber):
    np.append(np_Myarr01, thisNumber)
    print("store " + str(thisNumber))
    return

# START OF MAIN PROGRAM

Find_numbers()
print (np_Myarr01)

*** OUTPUT *******************

Found 1.082865
store 1.082865
Found 1.08287
store 1.08287
Found 1.08266
store 1.08266
Found 1.08295
store 1.08295
Found 888.0
store 888.0
[[  2.17306514e-316   0.00000000e+000   6.92674292e-310   6.92674292e-310
    2.37151510e-322]]

I was HOPING for the array to read

[[ 1.082865  1.08287  1.08266  1.08295  888.0]]

Any help would be gratefully appreciated. Thank you!

Body:
You can use a mixture of str.split() and re.search to extract the numbers from your apiString:

This:

apiString = " 'open': 1.082865 'close': 1.08287 'min': 1.08266 'max': 1.08295 'volume': 888"

my_array = np.array([float(x) for x in apiString.split() if not re.search('[a-zA-Z]', x)])

Will yield:

array([  1.082865,   1.08287 ,   1.08266 ,   1.08295 , 888.      ])

Details:

1)  apiString.split() will split your string in a list of strings where there are spaces in the original string

2) re.search('[a-zA-Z]', x) will return True if the string stored in x contains an uppercase or lowercase letter (i.e. not a number) (also why we use not here)

3) float(x) converts the string '1.808' to type float


问:
problem with oracle connection in c#
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

```<code>//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}
</code>```

答:
You might want to try something like:

connection string:

```<code>Data Source=DBNAME;User ID=zahid;Password= abc123;Persist Security Info=True;Unicode=True;
</code>```

Now look in the tnsname.ora file on your PC. It will be somewhere under your local Oracle Client installation. You're looking for something like:

```<code>DBNAME =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1510))
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1514))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DBNAME)
    )
  )
</code>```

You're looking to replace DBNAME and OracleServerName with your own. Don't forget, DBNAME is the name of the main database, not one of the schemas (the entity with all the tables and procedures, etc) under it.

ContentLicense: CC BY-SA 3.0

Title: problem with oracle connection in c#

Body:
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}

Body:
You might want to try something like:

connection string:

Data Source=DBNAME;User ID=zahid;Password= abc123;Persist Security Info=True;Unicode=True;

Now look in the tnsname.ora file on your PC. It will be somewhere under your local Oracle Client installation. You're looking for something like:

DBNAME =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1510))
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1514))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DBNAME)
    )
  )

You're looking to replace DBNAME and OracleServerName with your own. Don't forget, DBNAME is the name of the main database, not one of the schemas (the entity with all the tables and procedures, etc) under it.


问:
z3py: Retrieve branching conditions from z3 formula
Let's say I have a z3py program like this one:

```<code>import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)
</code>```

Is there an elegant way for me to retrieve the branching conditions from some_formula?
So get a list like [a < input_0, a > 1]. It should work for arbitrarily deep nesting of if expressions.

I know there is some way to use cubes, but I am not able to retrieve more than two cube expressions. I am not sure how to configure the solver.

My ultimate goal is to force the solver to give me different outputs based on the constraints I push and pop. The constraints are the set of conditions I have inferred from this formula.

答:
Alright,thanks @alias! I came up with a custom version, which gets the job done. If someone knows a more elegant way to do this, please let me know.</p>

```<code>import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))
nested_formula = z3.If(some_formula == 1, 20, 10)

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)

def get_branch_conditions(z3_formula):
    conditions = []
    if z3.is_app_of(z3_formula, z3.Z3_OP_ITE):
        # the first child is usually the condition
        cond = z3_formula.children()[0]
        conditions.append(cond)
    for child in z3_formula.children():
        conditions.extend(get_branch_conditions(child))
    return conditions

conds = get_branch_conditions(some_formula)
print(conds)
conds = get_branch_conditions(nested_formula)
print(conds)
</code>```

Body:
Let's say I have a z3py program like this one:

import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)

Is there an elegant way for me to retrieve the branching conditions from some_formula?
So get a list like [a < input_0, a > 1]. It should work for arbitrarily deep nesting of if expressions.

I know there is some way to use cubes, but I am not able to retrieve more than two cube expressions. I am not sure how to configure the solver.

My ultimate goal is to force the solver to give me different outputs based on the constraints I push and pop. The constraints are the set of conditions I have inferred from this formula.

Body:
Alright,thanks @alias! I came up with a custom version, which gets the job done. If someone knows a more elegant way to do this, please let me know.

import z3

a = z3.Int("a")
input_0 = z3.Int("input_0")
output = z3.Int("output")

some_formula = z3.If(a < input_0, 1, z3.If(a > 1, 4, 2))
nested_formula = z3.If(some_formula == 1, 20, 10)

s = z3.Solver()

s.add(output == some_formula)

s.check()
m = s.model()
print(m)

def get_branch_conditions(z3_formula):
    conditions = []
    if z3.is_app_of(z3_formula, z3.Z3_OP_ITE):
        # the first child is usually the condition
        cond = z3_formula.children()[0]
        conditions.append(cond)
    for child in z3_formula.children():
        conditions.extend(get_branch_conditions(child))
    return conditions

conds = get_branch_conditions(some_formula)
print(conds)
conds = get_branch_conditions(nested_formula)
print(conds)


问:
Control alignment in Bootstrap 4
I'm trying to learn MVC. Parting from the scaffolding that Visual Studio does, everything was working perfectly. But when updated to Bootstrap 4, all my controls scrambled in the view. I managed to solve most of them following getbootstrap.com migration steps, but still have some problems

As is visible, Country DropDown and DatePicker are not in place. Here's my view code:

```<code>  <div class="input-group" id="Country">
     @Html.LabelFor(model => model.IDCountry, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
     <div class="col-md-6 col-lg-6">
        @Html.DropDownListFor(model => model.IDCountry, new SelectList(Country.List(), "Key", "Value"), new { style = "height: 30px" })
        @Html.ValidationMessageFor(model => model.IDCountry, "", new { @class = "text-danger" })
     </div>
  </div>
  <br />

  <div class="form-group">
     @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "col-md-4 col-lg-4" })
     <div class="col-md-8 col-lg-8">
        @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
        @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })
     </div>
  </div>
</code>```

All is wrapped in a form class="form-inline"

Everything is in columns, running in Xl size, so, I have no clue
Thanks in advance for any help

EDIT: The full code of the view

```<code> @model Trevo.Models.Holidays

@{
   ViewBag.Title = "Edit";
}

@*<link rel="stylesheet" href="~/Content/themes/base/jquery-ui.css" />*@

<h2>Edit</h2>

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()

   <form class="form-inline">
      <h4>Holidays</h4>
      <hr />
      @Html.ValidationSummary(true, "", new { @class = "text-danger" })

      @* To enable or disable the country list *@
      <script type="text/javascript">
         function ShowHideCountry(SelectGlobal) {
            var dvCountry = document.getElementById("Country");
            dvCountry.style.display = SelectGlobal.checked ? "none" : "block";
         }
      </script>

      <div class="input-group" id="IsGlobal">
         @Html.LabelFor(model => model.IsGlobal, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right", style = "display: inline-block" })
         <div class="col-md-6 col-lg-6">
            @Html.CheckBoxFor(model => model.IsGlobal, new { id = "SelectGlobal", onclick = "ShowHideCountry(this)", style = "width:18px;height:18px;display: inline-block" })
            @Html.ValidationMessageFor(model => model.IsGlobal, "", new { @class = "text-danger" })
         </div>
      </div>
      <br />

      <div class="input-group col-md-3 col-lg-3" id="Country">
         @Html.LabelFor(model => model.IDCountry, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
         <div class="col-md-6 col-lg-6">
            @Html.DropDownListFor(model => model.IDCountry, new SelectList(Country.List(), "Key", "Value"), new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.IDCountry, "", new { @class = "text-danger" })
         </div>
      </div>
      <br />

      @Html.HiddenFor(model => model.IDHoliday)

      @*<div class="input-group" id="HolidayDate">
            @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-6 col-lg-6">
               @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
               @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })
            </div>
         </div>
         <br />*@

      <div class="form-group">
         @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
         <div class="col-md-8 col-lg-8">
            @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
            @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })
         </div>
      </div>

      <div class="input-group" id="Annual">
         @Html.LabelFor(model => model.Annual, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
         <div class="col-md-6 col-lg-6">
            @Html.DropDownListFor(model => model.Annual, new[] { new SelectListItem { Text = "No", Value = "0" }, new SelectListItem { Text = "Yes", Value = "1" } }, new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.Annual, "", new { @class = "text-danger" })
         </div>
      </div>
      <br />

      <div class="input-group" id="Name">
         @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
         <div class="col-md-6 col-lg-6">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
         </div>
      </div>
      <br />

      <div class="input-group" id="Workable">
         @Html.LabelFor(model => model.Workable, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })
         <div class="col-md-6 col-lg-6">
            @Html.DropDownListFor(model => model.Workable, new[] { new SelectListItem { Text = "No", Value = "0" }, new SelectListItem { Text = "Yes", Value = "1" } }, new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.Workable, "", new { @class = "text-danger" })
         </div>
      </div>

      <div class="col text-center">
         <input type="submit" value="Save" class="btn btn-primary" />
      </div>
      <hr />

   </form>
}

<div>
   <div class="row">
      <div class="col text-right">
         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" })
      </div>
   </div>
</div>

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")

   @* To enable or disable the country list on Page load *@
   <script type="text/javascript">
      $(document).ready(function () {
         var dvCountry = document.getElementById("Country");
         dvCountry.style.display = SelectGlobal.checked ? "none" : "block";
      });
   </script>

   @* DateTime picker *@
   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
   <script src="~/Scripts/jquery.maskedinput.min.js"></script>
   <script>
      $("#HolidayDate").datepicker({ dateFormat: "dd/mm/yy" }).mask("99/99/9999");
      $.validator.addMethod('date',
         function (value, element, params) {
            if (this.optional(element)) {
               return true;
            }
            var ok = true;
            try {
               $.datepicker.parseDate('dd/mm/yy', value);
            }
            catch (err) {
               ok = false;
            }
            return ok;
         });
   </script>
}
</code>```

答:
You need to make these 2 changes to make it work:

Remove col-md-3 col-lg-3 from the IDCountry group:

```<code><div class="input-group col-md-3 col-lg-3" id="Country">
</code>```

Should be:

```<code><div class="input-group" id="Country">
</code>```

Change HolidayDate group from form-group to input-group

```<code><div class="form-group">
@Html.LabelFor(model => model.HolidayDate, htm...
</code>```

Should be:

```<code><div class="input-group">
@Html.LabelFor(model => model.HolidayDate, htm...
</code>```

Title: Control alignment in Bootstrap 4

Body:
I'm trying to learn MVC. Parting from the scaffolding that Visual Studio does, everything was working perfectly. But when updated to Bootstrap 4, all my controls scrambled in the view. I managed to solve most of them following getbootstrap.com migration steps, but still have some problems

As is visible, Country DropDown and DatePicker are not in place. Here's my view code:

     @Html.LabelFor(model => model.IDCountry, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

        @Html.DropDownListFor(model => model.IDCountry, new SelectList(Country.List(), "Key", "Value"), new { style = "height: 30px" })
        @Html.ValidationMessageFor(model => model.IDCountry, "", new { @class = "text-danger" })

     @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "col-md-4 col-lg-4" })

        @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
        @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })

All is wrapped in a form class="form-inline"

Everything is in columns, running in Xl size, so, I have no clue
Thanks in advance for any help

EDIT: The full code of the view

 @model Trevo.Models.Holidays

@{
   ViewBag.Title = "Edit";
}

@*<link rel="stylesheet" href="~/Content/themes/base/jquery-ui.css" />*@

Edit

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()

   <form class="form-inline">

Holidays

      @Html.ValidationSummary(true, "", new { @class = "text-danger" })

      @* To enable or disable the country list *@

         @Html.LabelFor(model => model.IsGlobal, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right", style = "display: inline-block" })

            @Html.CheckBoxFor(model => model.IsGlobal, new { id = "SelectGlobal", onclick = "ShowHideCountry(this)", style = "width:18px;height:18px;display: inline-block" })
            @Html.ValidationMessageFor(model => model.IsGlobal, "", new { @class = "text-danger" })

         @Html.LabelFor(model => model.IDCountry, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

            @Html.DropDownListFor(model => model.IDCountry, new SelectList(Country.List(), "Key", "Value"), new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.IDCountry, "", new { @class = "text-danger" })

      @Html.HiddenFor(model => model.IDHoliday)

      @*

            @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "control-label col-md-2" })

               @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
               @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })

*@

         @Html.LabelFor(model => model.HolidayDate, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

            @Html.EditorFor(model => model.HolidayDate, new { autocomplete = "off" })
            @Html.ValidationMessageFor(model => model.HolidayDate, "", new { @class = "text-danger" })

         @Html.LabelFor(model => model.Annual, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

            @Html.DropDownListFor(model => model.Annual, new[] { new SelectListItem { Text = "No", Value = "0" }, new SelectListItem { Text = "Yes", Value = "1" } }, new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.Annual, "", new { @class = "text-danger" })

         @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

         @Html.LabelFor(model => model.Workable, htmlAttributes: new { @class = "col-md-4 col-lg-4 text-right" })

            @Html.DropDownListFor(model => model.Workable, new[] { new SelectListItem { Text = "No", Value = "0" }, new SelectListItem { Text = "Yes", Value = "1" } }, new { style = "height: 30px" })
            @Html.ValidationMessageFor(model => model.Workable, "", new { @class = "text-danger" })

         <input type="submit" value="Save" class="btn btn-primary" />

   </form>
}

         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" })

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")

   @* To enable or disable the country list on Page load *@

   @* DateTime picker *@

}

Body:
You need to make these 2 changes to make it work:

Remove col-md-3 col-lg-3 from the IDCountry group:

<div class="input-group col-md-3 col-lg-3" id="Country">

Should be:

<div class="input-group" id="Country">

Change HolidayDate group from form-group to input-group

<div class="form-group">
@Html.LabelFor(model => model.HolidayDate, htm...

Should be:

<div class="input-group">
@Html.LabelFor(model => model.HolidayDate, htm...


问:
Value increment of textbox in C#.net
I have 2 textbox and 1 button textbox1,textbox2 and 1 increment button.Both textbox is initialize by 1.If i will click on textbox1 and then click on incr button the value belongs to textbox1 will be increase only.And whenever i will click on textbox2 and again i will click on incr button only textbox2 value will be increment.
How will i do this?</p>

答: This can be done on the client side using javascript. On focus of textbox1 update a hiddenfield value. similarly for the textbox2. then on button click, based on hidden f</p>

ContentLicense: CC BY-SA 2.5

Title: Value increment of textbox in C#.net


问:
Difference in index declaration between specifying columns in ON clause and in INCLUDE clause
Just wondering about indexes. It's a quite new concept for me and I can't see the difference between declaring columns in ON clause and in INCLUDE clause. Examples below should explain the matter:

```<code>CREATE INDEX ix_client_info1
ON dbo.client(name, age, city)
WHERE name = 'A%';

CREATE INDEX ix_client_info2
ON dbo.client(name)
INCLUDE(age, city)
WHERE name = 'A%';
</code>```

How these two indexes differ in behaviour? Which to use in which situations?

答:
The difference is that included columns are not ordered in the index; they don’t belong to the index tree, they are just added to the leafs.

So this basically means two things:

the index is a bit smaller, and there is less overhead to maintain it

the index will not help if included columns are used for filtering (like in the where clause, on clause of a join, or in the group by clause) or for sorting (like in the order by clause); it is only useful when the columns are used solely in the select clause so this comes handy when you want a covering index)

There are not many cases when included columns are useful, unless you are doing advanced optimization. In general, you want regular columns keys.

Body:
Just wondering about indexes. It's a quite new concept for me and I can't see the difference between declaring columns in ON clause and in INCLUDE clause. Examples below should explain the matter:

CREATE INDEX ix_client_info1
ON dbo.client(name, age, city)
WHERE name = 'A%';

CREATE INDEX ix_client_info2
ON dbo.client(name)
INCLUDE(age, city)
WHERE name = 'A%';

How these two indexes differ in behaviour? Which to use in which situations?


答:
In addition to @barmar's comments, if your API string always looks as shown in the example, you can extract every other item after splitting (with slicing), and let NumPy handle the rest of conversion:</p>

```<code>np_Myarr01 = np.fromiter(apiString.split()[1::2], float)
</code>```

Title: Python - simple NumPy array not showing expected values

Body:
In addition to @barmar's comments, if your API string always looks as shown in the example, you can extract every other item after splitting (with slicing), and let NumPy handle the rest of conversion:

np_Myarr01 = np.fromiter(apiString.split()[1::2], float)


问:
How can I use cv2.face and cv2 with creating a window by using QT, without getting errors?
I want to use openCV, but with different openCV versions I get different errors.

For e.g when I use pip install opencv-python-headless code something like:

```<code>import cv2

img = cv2.imread('lena.jpg', -1)

cv2.imshow('image', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()
</code>```

works fine. But when I want to use the face attribute, it crashes with the error

```<code>Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(cv2.face.LBPHFaceRecognizer_create())
AttributeError: module 'cv2.cv2' has no attribute 'face'
</code>```

To fix the issue, I need to install openCV by using sudo python3 -m pip install opencv-contrib-python. But if I now execute the script above, the error

```<code>qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
</code>```

appears.

So how can I avoid both errors?

EDIT:
With the normal installation pip install opencv-python both errors appear. So it can not find the face attribute and is not able to create a window by using QT

答: It turns out that the latest opencv-python version is broken, so I just need to pip install opencv-contrib-python==4.1.0.25

Body:
I want to use openCV, but with different openCV versions I get different errors.

For e.g when I use pip install opencv-python-headless code something like:

import cv2

img = cv2.imread('lena.jpg', -1)

cv2.imshow('image', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()

works fine. But when I want to use the face attribute, it crashes with the error

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(cv2.face.LBPHFaceRecognizer_create())
AttributeError: module 'cv2.cv2' has no attribute 'face'

To fix the issue, I need to install openCV by using sudo python3 -m pip install opencv-contrib-python. But if I now execute the script above, the error

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

appears.

So how can I avoid both errors?

EDIT:
With the normal installation pip install opencv-python both errors appear. So it can not find the face attribute and is not able to create a window by using QT


问:
Static Google maps 2 pins
Is there a way I can zoom my google maps and the two pins will always show or focused?</p>

答:
its not possible. if u r using two pins, middle of the two pins will be the center of the map(Google Static map API determines the center of the map).. so if you increase the zoom value u may not seen the pin positions.

Maps API automatically determines the zoom level by default..

Title: Static Google maps 2 pins


问:
Visual Studio Windows Form App where is the Form constructor being called
My problem is that I can see the form I make properly on the [Design] page, but when I run the program it shows a blank page. The reason it happens is because "InitializeComponent()" is not being called.

Yet, I do have it on my constructor so I made a console message there to check if I even get to the constructor and I do not for some reason, it used to work well before I changed my form to a MetroForm and now even if I change it back to a normal form it won't work.

But now, since I know the problem is the constructor not even called, my question is: What class and, where inside this class the Form constructor is being called?

Note: Visual Studio does not show any errors on any class whatsoever.

If you want to see parts of the code just tell me which class you would like to see and I will send it

答:
I just ran into something similar.  I was not compiling against the right version of .NET.
Select your project, Right click and select Properties, Click Application, Select the Target framework for the version of .NET you wish to compile against.</p>


问:
Node.js, socket-io based one to one chat engine working fine on LOCAL but not working when running on different laptops using ngrok
I am working on a chat server and it's working fine on local but whenever I try to run the project using ngrok then me and my friend are unable to chat.

```<code>var socket = io('http://localhost:7777', {
    query: {
        username: '<%= user %>'
      }
  });
</code>```

Can anyone guide me how to make this public? Because the IP address changes everytime when connected to internet.

and

```<code>var app = express();

const chatServer = require('http').createServer(app);

chatServer.listen(7777);
</code>```

I'm working in node.js for the first time

答:
If your server and client do work locally, as you mention, you have some additional challenges when running the server and client on different machines over the internet:

Your client needs to know the server external IP address. So you need some way to make it configurable on the client, for example using command line arguments.

If the local IP address of your server changes, you need to configure it to use a static IP address instead of using DHCP.

You probably need to setup port forwarding on your internet router at the server side. You need to tell your router to forward all traffic on port 7777 to your server.

You might need to configure your firewall to allow traffic on port 7777.

Your ISP can and will change your external IP address occasionally. Not much you can do about that. That's why servers on the internet are usually accessed using their (domain) name, which is static.

Body:
I am working on a chat server and it's working fine on local but whenever I try to run the project using ngrok then me and my friend are unable to chat.

var socket = io('http://localhost:7777', {
    query: {
        username: '<%= user %>'
      }
  });

Can anyone guide me how to make this public? Because the IP address changes everytime when connected to internet.

and

var app = express();

const chatServer = require('http').createServer(app);

chatServer.listen(7777);

I'm working in node.js for the first time


问:
Is there any way to know what trigger call a runnable?
I´m new in the Autosar World and I have a question.

I´m working on an app that has several triggers. I would like to know if there is any way to know which one trigger call the runnable wihtout using a static var.

Thanks in advance.

答: For this purpose the activationReason is available. Please have a look at the chapter 4.2.3.3 in the AUTOSAR specification „SWS RTE“.


问:
Unable to write to CosmosDB from an Azure Event Hub
I'm working on an Azure Function(2.x) which is triggered by events coming from an Event Hub and writes the received data to a CosmosDB instance. Before I deploy it, I'd like to test it locally and reading the event works flawlessly. However, when I try to write to CosmosDB this error shows up:

"System.Private.CoreLib: Exception while executing function: Functions.EventHubTrigger. Microsoft.Azure.DocumentDB.Core: Message: {"Errors":["One of the specified inputs is invalid"]}"

The database instance was created using the Azure Portal and I added a couple of dummy entries, all of which works fine. What am I doing wrong?

function.json:

```<code>{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "event",
      "direction": "in",
      "eventHubName": "event-hub-name",
      "connection": "event-hub-connection",
      "cardinality": "many",
      "consumerGroup": "$Default"
    },
    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "doc",
      "databaseName": "database-name",
      "collectionName": "test",
      "createIfNotExists": "true",
      "connectionStringSetting": "CosmosDBConnectionString"
    }
  ]
}
</code>```

local.settings.json:

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "storage-key",
    "CosmosDBConnectionString": "AccountEndpoint=document-db-endpoint;AccountKey=account-key;",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "event-hub-connection": "Endpoint=sb://endpoint-name;SharedAccessKeyName=shared-access-key-name;SharedAccessKey=shared-access-key"
  }
}
</code>```

host.json:

```<code>{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}
</code>```

__init__.py:

```<code>import logging, json

import azure.functions as func

def main(event: func.EventHubEvent, doc: func.Out[func.Document]):

    event_data = event.get_body().decode("utf-8")
    logging.info('Python EventHub trigger processed an event: %s', event_data)

    # json object for testing the DB write operation
    temp = {}
    temp["id"] = 1
    temp["category"] = "feedback"
    temp = json.dumps(temp)

    doc.set(func.Document.from_json(temp))
    logging.info("CosmosDB updated!; Value: ", temp)
</code>```

答:
That error is a HTTP 400, BadRequest. Meaning that something in the payload is not correctly formed JSON or some of your attributes is invalid.

I see your id is a number, but in the REST contract, it's a string. Reference: https://learn.microsoft.com/rest/api/cosmos-db/create-a-document#body

Can you change the id to a string?

Body:
I'm working on an Azure Function(2.x) which is triggered by events coming from an Event Hub and writes the received data to a CosmosDB instance. Before I deploy it, I'd like to test it locally and reading the event works flawlessly. However, when I try to write to CosmosDB this error shows up:

"System.Private.CoreLib: Exception while executing function: Functions.EventHubTrigger. Microsoft.Azure.DocumentDB.Core: Message: {"Errors":["One of the specified inputs is invalid"]}"

The database instance was created using the Azure Portal and I added a couple of dummy entries, all of which works fine. What am I doing wrong?

function.json:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "event",
      "direction": "in",
      "eventHubName": "event-hub-name",
      "connection": "event-hub-connection",
      "cardinality": "many",
      "consumerGroup": "$Default"
    },
    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "doc",
      "databaseName": "database-name",
      "collectionName": "test",
      "createIfNotExists": "true",
      "connectionStringSetting": "CosmosDBConnectionString"
    }
  ]
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "storage-key",
    "CosmosDBConnectionString": "AccountEndpoint=document-db-endpoint;AccountKey=account-key;",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "event-hub-connection": "Endpoint=sb://endpoint-name;SharedAccessKeyName=shared-access-key-name;SharedAccessKey=shared-access-key"
  }
}

host.json:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

__init__.py:

import logging, json

import azure.functions as func

def main(event: func.EventHubEvent, doc: func.Out[func.Document]):

    event_data = event.get_body().decode("utf-8")
    logging.info('Python EventHub trigger processed an event: %s', event_data)

    # json object for testing the DB write operation
    temp = {}
    temp["id"] = 1
    temp["category"] = "feedback"
    temp = json.dumps(temp)

    doc.set(func.Document.from_json(temp))
    logging.info("CosmosDB updated!; Value: ", temp)


问:
export azure ml studio designer project as jupyter notebook?
I hope I am not missing something obvious here. I am using the new azure ml studio designer. I am able to use to create datasets, train models and use them just fine.

azure ml studio allows creation of Jupyter notebooks (also) and use them to do machine learning. I am able to do that too.

So, now, I am wondering, can I build my ML pipeline/experiment in ML studio designer, and once it is in good shape, export it as a python and jupyter notebook? then, use it in the same designer provided notebook option or may be use it locally?

答:
This is not currently supported, but I am 80% sure it is in the roadmap.
An alternative would be to use the SDK to create the same pipeline using ModuleStep where  I believe you can reference a Designer Module by its name to use it like a PythonScriptStep


问:
why do I have to cast when assigning
EarthquakeMarker is an abstract class that extends SimplePointMarker. OceanQuakeMarker extends EarthquakeMarker.

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;
</code>```

I read that this code wont compile because of the assignment of em = pm. However, pm has an "is-a" relationship with em, so I'm wondering why I have to cast it:

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;
</code>```

Also, I'm wondering what happens to the functionality of em since it has been casted to the abstract parent class. Does it lose the functionality that the OceanQuakeMarker has?

答:
Java doesn't know the type of the Object at compile time but it knows the type of the variable.

In case of

```<code>SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;
</code>```

Java does only know that pm is a SimplePointMarker but the real type (OceanQuakeMarker) is unknown at compile time.

Theoretically, the object could be changed at any time and it wouldn't be a EarthquakeMarker any more.

As the real type is unknown at compile-time, it will be like

```<code>SimplePointMarker pm;//=something
EarthquakeMarker em = pm;
</code>```

Therefore, you'll have to cast it because a SimplePointMarker is not always a EarthquakeMarker.

As the real type is only known at runtime, the type will also be tested at runtime.

If you cast an object to a type the object is not an instance of, a ClassCastException will be thrown.

Title: why do I have to cast when assigning

Body:
EarthquakeMarker is an abstract class that extends SimplePointMarker. OceanQuakeMarker extends EarthquakeMarker.

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;

I read that this code wont compile because of the assignment of em = pm. However, pm has an "is-a" relationship with em, so I'm wondering why I have to cast it:

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = (EarthquakeMarker) pm;

Also, I'm wondering what happens to the functionality of em since it has been casted to the abstract parent class. Does it lose the functionality that the OceanQuakeMarker has?

Body:
Java doesn't know the type of the Object at compile time but it knows the type of the variable.

In case of

SimplePointMarker pm = new OceanQuakeMarker(feature);
EarthquakeMarker em = pm;

Java does only know that pm is a SimplePointMarker but the real type (OceanQuakeMarker) is unknown at compile time.

Theoretically, the object could be changed at any time and it wouldn't be a EarthquakeMarker any more.

As the real type is unknown at compile-time, it will be like

SimplePointMarker pm;//=something
EarthquakeMarker em = pm;

Therefore, you'll have to cast it because a SimplePointMarker is not always a EarthquakeMarker.

As the real type is only known at runtime, the type will also be tested at runtime.

If you cast an object to a type the object is not an instance of, a ClassCastException will be thrown.


问:
Convert
 to end line
I'm trying to extract some text using BeautifulSoup. I'm using get_text() function for this purpose.

My problem is that the text contains
 tags and I need to convert them to end lines. how can I do this?

答:
Instead of replacing the tags with \n, it may be better to just add a \n to the end of all of the tags that matter.

To steal the list from @petezurich:

```<code>for elem in soup.find_all(["a", "p", "div", "h3", "br"]):
    elem.append('\n')
</code>```

Title: Convert </br> to end line

Body:
Instead of replacing the tags with \n, it may be better to just add a \n to the end of all of the tags that matter.

To steal the list from @petezurich:

for elem in soup.find_all(["a", "p", "div", "h3", "br"]):
    elem.append('\n')


问:
Do you guys minify node.js while deploying?
I got a weird question while I'm about to deploy my node.js code. like we create a build version for angular, do i need to generate build version before deploying?(minifying js etc.,). First time deploying node.js, please help! Thanks in advance!</p>

答:
No, you don’t need that

Minifying is used to decrease the amount of traffic, served to users. You don’t need this for a server-side code.

As an analogy, you can ask yourself "Do you minify your php or ruby code?"


问:
Running SSH Agent when starting Git Bash on Windows
I am using git bash. I have to use

```<code>eval `ssh-agent.exe`
ssh-add /my/ssh/location/
</code>```

every time when I start a new git bash.

Is there a way to set ssh agent permanently? Or does windows has a good way
to manage the ssh keys?

I'm a new guy, please give me detailed tutorial, thanks!

答:
I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile:

```<code>env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env
</code>```

I probably have something configured weird, but was not successful when I added it to my .profile or .bashrc. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.

You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.

Body:
I am using git bash. I have to use

eval `ssh-agent.exe`
ssh-add /my/ssh/location/

every time when I start a new git bash.

Is there a way to set ssh agent permanently? Or does windows has a good way
to manage the ssh keys?

I'm a new guy, please give me detailed tutorial, thanks!

Body:
I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

I probably have something configured weird, but was not successful when I added it to my .profile or .bashrc. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.

You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.


问:
WiX: Reference files in source media folder of MSI
I would like to keep some files outside of my MSI in a directory:
e.g.

```<code>C:\users\foo\msi-folder\
  installer.msi
  stuff\
    files here i want to reference
</code>```

I can successfully not embed the files with a custom <Media> (not sure if this is necessary) element and setting compressed="no" such that the files get created in my bin directory

but, when i run the installer it tries to look for them in (TARGETDIR) C:\stuff\....

I want to be able to do something like <Directory Name="stuff" SourceName="[SourceDir]stuff"> but that does not seem to work.

答:
I ended up removing the files and using a custom action to reference them by path (using <SetProperty Value="[SourceDir]..." /> to reference the paths.

I also ended up switching to using PnPUtil as DIFx is deprecated

Body:
I would like to keep some files outside of my MSI in a directory:
e.g.

C:\users\foo\msi-folder\
  installer.msi
  stuff\
    files here i want to reference

I can successfully not embed the files with a custom <Media> (not sure if this is necessary) element and setting compressed="no" such that the files get created in my bin directory

but, when i run the installer it tries to look for them in (TARGETDIR) C:\stuff\....

I want to be able to do something like <Directory Name="stuff" SourceName="[SourceDir]stuff"> but that does not seem to work.


问:
render a map's size in react
I have two maps that I want to use their length as an integer for a component in react. the code looks something like this:

```<code>function Test() {
  const classes = useStyles();
  const [spacing, setSpacing] = React.useState(2);
  // FETCH REQUEST DATABASE ITEMS
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch("/test")
      .then(res => res.json())
      .then(items => setItems(items));
  }, []);
  // ASSIGN ITEMS TO MAPPED GRID
  return (
    <Grid
      container
      direction="row"
      justify="space-around"
      alignItems="flex-start"
      spacing={2}
    >
      {items.map(x => {
        return (
          <Grid item sm key={`key${x._id}`}>
            <SmallCard
              key={x._id}

              // MAP I WANT TO TURN INTO INTEGER BELLOW

              mappedItemCount = {x.map.size}

              // ^ ^ ^ ^ ^ ^ THIS PART HERE IN PARTICULAR

            />
          </Grid>
        );
      })}
    </Grid>
  );
}
</code>```

For some reason this does not seem to turn it into an integer and still lists as NAN. What am I doing wrong?

答:
my item was an object not a map due to the way its being rendered. so the correct syntax should really be the following:

```<code>mappedItemCount = {Object.keys(x.map.size).length}
</code>```

Sacred texts can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Title: render a map's size in react

Body:
I have two maps that I want to use their length as an integer for a component in react. the code looks something like this:

function Test() {
  const classes = useStyles();
  const [spacing, setSpacing] = React.useState(2);
  // FETCH REQUEST DATABASE ITEMS
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch("/test")
      .then(res => res.json())
      .then(items => setItems(items));
  }, []);
  // ASSIGN ITEMS TO MAPPED GRID
  return (
    <Grid
      container
      direction="row"
      justify="space-around"
      alignItems="flex-start"
      spacing={2}
    >
      {items.map(x => {
        return (
          <Grid item sm key={`key${x._id}`}>
            <SmallCard
              key={x._id}

              // MAP I WANT TO TURN INTO INTEGER BELLOW

              mappedItemCount = {x.map.size}

              // ^ ^ ^ ^ ^ ^ THIS PART HERE IN PARTICULAR

            />
          </Grid>
        );
      })}
    </Grid>
  );
}

For some reason this does not seem to turn it into an integer and still lists as NAN. What am I doing wrong?

Body:
my item was an object not a map due to the way its being rendered. so the correct syntax should really be the following:

mappedItemCount = {Object.keys(x.map.size).length}

Sacred texts can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys


问:
Script to copy Layer Names to text box in Photoshop
I'm trying to create a script out of 2 working scripts

Goal:

We need a script that will go through all the layers in the current document, find each layer marked in certain color (Red for example), copy the names of only the layers marked in red, then put all names in a text layer one after another (attached example image).

Resources:

I found 2 scripts that each do half of what we need, so how to we put them together?

1)  "Select by red" goes through the document and finds how many layers marked in "red" are in the document:

```<code>#target photoshop

if (app.documents.length > 0) {

// the file;

var myDocument = app.activeDocument;

// get number of layers;

var ref = new ActionReference();

ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );

var applicationDesc = executeActionGet(ref);

var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));

// process the layers;

var theLayers = new Array;

var theOthers = new Array;

for (var m = 0; m <= theNumber; m++) {

try {

var ref = new ActionReference();

ref.putIndex( charIDToTypeID( "Lyr " ), m);

var layerDesc = executeActionGet(ref);

var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));

var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));

// if not layer group collect values;

if (layerSet != "layerSectionEnd" /*&& layerSet != "layerSectionStart"*/ && isBackground != true) {

var theName = layerDesc.getString(stringIDToTypeID('name'));

var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));

var visible = layerDesc.getBoolean(stringIDToTypeID("visible"));

var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));

if (typeIDToStringID(theColor) == "red") {theLayers.push([theName, theID])}

else {theOthers.push([theName, theID])}

};

}

catch (e) {};

};

// if layers are red;

if (theLayers.length > 0) {alert ("there are " + theLayers.length + " Red layers")}

else {alert ("no red layers")}

};
</code>```

2)  "Text box from layer name" takes the name of the currently selected layer, and pastes it into a new text layer called "Comp".

```<code>if (app.documents.length > 0) mainScript();

function mainScript() {

    try{

        var myLayerName = activeDocument.activeLayer.name;

        var myLayerText = activeDocument.artLayers.add();

        myLayerText.name = "Comp";

        myLayerText.kind = LayerKind.TEXT;

        var textProperty = myLayerText.textItem;

        textProperty.size = 10;

        textProperty.font = "Arial";

        myLayerText.textItem.contents = myLayerName;

    }catch (errStr){

        alert(errStr);

    }

}
</code>```

Plan:

From my understanding, we need to start with a loop that's as long as our document size i.e. total number of layers for (var i = 0; i < doc.layers.length; i++).

Then layer by layer the script will check for color ID if (typeIDToStringID(theColor) == "red") . When it finds layer marked in red, it copies the layer name - then either stores it in array (to output later all at once), or creates a new text box and pastes the layer name myLayerText.textItem.contents = myLayerName.

Then for each time it finds another layer marked in red , it copies the layer name, and pastes it in the same text box just a line above/below previous layer name.

Any help is much appreciated!

答:
The only thing you needed to do was to join the names of your theLayers array using the line-break symbol \r:

```<code>if (app.documents.length > 0)
{

  // the file;
  var myDocument = app.activeDocument;

  // get number of layers;
  var ref = new ActionReference();
  ref.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));

  var applicationDesc = executeActionGet(ref);
  var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));

  // process the layers;
  var theLayers = new Array;

  for (var m = 0; m <= theNumber; m++)
  {
    try
    {
      var ref = new ActionReference();
      ref.putIndex(charIDToTypeID("Lyr "), m);
      var layerDesc = executeActionGet(ref);
      var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
      var isBackground = layerDesc.getBoolean(stringIDToTypeID("background")); // if not layer group collect values;  if (layerSet != "layerSectionEnd" /*&& layerSet != "layerSectionStart"*/ && isBackground != true)
      {
        var theName = layerDesc.getString(stringIDToTypeID('name'));
        var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));
        if (typeIDToStringID(theColor) == "red")
        {
          theLayers.push(theName); // we only need names here
        }
      };
    }
    catch (e)
    {};
  };

  // got our red layers in theLayers

  var myLayerText = activeDocument.artLayers.add();
  myLayerText.name = "Result";
  myLayerText.kind = LayerKind.TEXT;
  var textProperty = myLayerText.textItem;
  textProperty.size = 10;
  textProperty.font = "Arial";
  myLayerText.textItem.contents = theLayers.join('\r'); // joining layers with a line-break: this is going to be textItem text

};
</code>```

Here's the result:

I'd suggest you to take a course on JS on any learning website (code academy, etc): this won't take you more than an hour or two but you'll get the basic concepts: this will make your life much easier in terms of dealing with questions like this.

Body:
I'm trying to create a script out of 2 working scripts

Goal:

We need a script that will go through all the layers in the current document, find each layer marked in certain color (Red for example), copy the names of only the layers marked in red, then put all names in a text layer one after another (attached example image).

Resources:

I found 2 scripts that each do half of what we need, so how to we put them together?

1)  "Select by red" goes through the document and finds how many layers marked in "red" are in the document:

#target photoshop

if (app.documents.length > 0) {

// the file;

var myDocument = app.activeDocument;

// get number of layers;

var ref = new ActionReference();

ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );

var applicationDesc = executeActionGet(ref);

var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));

// process the layers;

var theLayers = new Array;

var theOthers = new Array;

for (var m = 0; m <= theNumber; m++) {

try {

var ref = new ActionReference();

ref.putIndex( charIDToTypeID( "Lyr " ), m);

var layerDesc = executeActionGet(ref);

var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));

var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));

// if not layer group collect values;

if (layerSet != "layerSectionEnd" /*&& layerSet != "layerSectionStart"*/ && isBackground != true) {

var theName = layerDesc.getString(stringIDToTypeID('name'));

var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));

var visible = layerDesc.getBoolean(stringIDToTypeID("visible"));

var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));

if (typeIDToStringID(theColor) == "red") {theLayers.push([theName, theID])}

else {theOthers.push([theName, theID])}

};

}

catch (e) {};

};

// if layers are red;

if (theLayers.length > 0) {alert ("there are " + theLayers.length + " Red layers")}

else {alert ("no red layers")}

};

2)  "Text box from layer name" takes the name of the currently selected layer, and pastes it into a new text layer called "Comp".

if (app.documents.length > 0) mainScript();

function mainScript() {

    try{

        var myLayerName = activeDocument.activeLayer.name;

        var myLayerText = activeDocument.artLayers.add();

        myLayerText.name = "Comp";

        myLayerText.kind = LayerKind.TEXT;

        var textProperty = myLayerText.textItem;

        textProperty.size = 10;

        textProperty.font = "Arial";

        myLayerText.textItem.contents = myLayerName;

    }catch (errStr){

        alert(errStr);

    }

}

Plan:

From my understanding, we need to start with a loop that's as long as our document size i.e. total number of layers for (var i = 0; i < doc.layers.length; i++).

Then layer by layer the script will check for color ID if (typeIDToStringID(theColor) == "red") . When it finds layer marked in red, it copies the layer name - then either stores it in array (to output later all at once), or creates a new text box and pastes the layer name myLayerText.textItem.contents = myLayerName.

Then for each time it finds another layer marked in red , it copies the layer name, and pastes it in the same text box just a line above/below previous layer name.

Any help is much appreciated!

Body:
The only thing you needed to do was to join the names of your theLayers array using the line-break symbol \r:

if (app.documents.length > 0)
{

  // the file;
  var myDocument = app.activeDocument;

  // get number of layers;
  var ref = new ActionReference();
  ref.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));

  var applicationDesc = executeActionGet(ref);
  var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));

  // process the layers;
  var theLayers = new Array;

  for (var m = 0; m <= theNumber; m++)
  {
    try
    {
      var ref = new ActionReference();
      ref.putIndex(charIDToTypeID("Lyr "), m);
      var layerDesc = executeActionGet(ref);
      var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
      var isBackground = layerDesc.getBoolean(stringIDToTypeID("background")); // if not layer group collect values;  if (layerSet != "layerSectionEnd" /*&& layerSet != "layerSectionStart"*/ && isBackground != true)
      {
        var theName = layerDesc.getString(stringIDToTypeID('name'));
        var theColor = layerDesc.getEnumerationValue(stringIDToTypeID("color"));
        if (typeIDToStringID(theColor) == "red")
        {
          theLayers.push(theName); // we only need names here
        }
      };
    }
    catch (e)
    {};
  };

  // got our red layers in theLayers

  var myLayerText = activeDocument.artLayers.add();
  myLayerText.name = "Result";
  myLayerText.kind = LayerKind.TEXT;
  var textProperty = myLayerText.textItem;
  textProperty.size = 10;
  textProperty.font = "Arial";
  myLayerText.textItem.contents = theLayers.join('\r'); // joining layers with a line-break: this is going to be textItem text

};

Here's the result:

I'd suggest you to take a course on JS on any learning website (code academy, etc): this won't take you more than an hour or two but you'll get the basic concepts: this will make your life much easier in terms of dealing with questions like this.


问:
How do I install certificates using Octopus Deploy?
When deploying applications using Octopus Deploy, how do I include the SSL/TLS certificate?</p>

答:
When deploying to Internet Information Services (IIS), the built-in Deploy to IIS step has the ability to include an SSL/TSL certificate variable and bind it to IIS when deployed.

The first step will be to add a certificate variable to your project.  Click on Variables and create a new variable.  Click on Change Type and select Certificate

Once you've added your variable, add the Deploy to IIS step to your project

Scroll down to the Bindings section and click the Add button

Choose HTTPS then select your certificate variable

And that's all!  When your application is deployed, it will also deploy the certificate to the server and bind it to port 443 in IIS!

Octopus Deploy also contains steps that will import certificates to Tomcat, Wildfly, or Java keystore.


问:
Amazon MWS Scratchpad error 50001 ill formed XML
This simple code in MWS Scratchpad gives me this 50001 error
"The XML you submitted is ill-formed at the Amazon Envelope XML level at (or near) line 2, column 14."</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<messagetype>OrderFulfillment</messagetype>
<message>
 <messageid>1</messageid>
 <orderfulfillment>
      <amazonorderid>171-0326363-1826719</amazonorderid>
      <carriername>La Poste</carriername>
      <shippertrackingnumber>1K03004689202</shippertrackingnumber>
 </orderfulfillment>
</message>
</code>```

答:
Most probably because there is no root element. All XML must be enclosed into a single element-node, that is the root. For XHTML this is . But, since I do not know the conventions of amazon-mws scratchpad, this is all I can guess. You would need something like:

<?xml version="1.0" encoding="utf-8"?>
<some-outer-element>
   <messagetype>OrderFulfillment</messagetype>
   <message>
      ...
   </message>
</some-outer-element>
```

where <some-outer-element> would need to be the valid root-element for the document type you are using. Which one that is should be in the documentation for Amazon MWS (Scratchpad) or the XML schema definition of the XML you are using.

Body:
This simple code in MWS Scratchpad gives me this 50001 error
"The XML you submitted is ill-formed at the Amazon Envelope XML level at (or near) line 2, column 14."

<?xml version="1.0" encoding="utf-8"?>
<messagetype>OrderFulfillment</messagetype>
<message>
 <messageid>1</messageid>
 <orderfulfillment>
      <amazonorderid>171-0326363-1826719</amazonorderid>
      <carriername>La Poste</carriername>
      <shippertrackingnumber>1K03004689202</shippertrackingnumber>
 </orderfulfillment>
</message>

Body:
Most probably because there is no root element. All XML must be enclosed into a single element-node, that is the root. For XHTML this is <html>. But, since I do not know the conventions of amazon-mws scratchpad, this is all I can guess. You would need something like:

<?xml version="1.0" encoding="utf-8"?>
<some-outer-element>
   <messagetype>OrderFulfillment</messagetype>
   <message>
      ...
   </message>
</some-outer-element>

where <some-outer-element> would need to be the valid root-element for the document type you are using. Which one that is should be in the documentation for Amazon MWS (Scratchpad) or the XML schema definition of the XML you are using.


问:
How is data from tf.data generated and passed to the model
In the book Hands-On ML with Scikit-Learn, Tensorflow and Keras, the author explains using the Data API to manipulate, transform and pass data to the model efficiently, he writes the following function:

```<code>def csv_reader(filepaths, batch_size=32):
    dataset = tf.data.Dataset.list_files(filepaths)
    dataset = dataset.interleave(lambda filepath:
    tf.data.TextLineDataset(filepath).skip(1), cycle_length=5)
    dataset = dataset.shuffle(10000).repeat(1)
    return dataset.batch(batch_size).prefetch(1)
</code>```

Then : train_set = csv_reader_dataset(train_filepaths)

and: model.fit(train_set, epochs=10)

What I don't understand is the part where he creates the actual train_set from the function, isn't that way he only has one batch of data? He says that we create a training set once and don't need to repeat it as it will be taken care of by Keras but I don't see how.

答: A tf.data.Dataset is like a blueprint for how to get your data. To use a dataset to read data, you create an iterator over the dataset. The same dataset can be used to create multiple iterators, which will each iterate over the whole dataset. So Keras just needs one dataset, then can use the dataset to iterate over your data multiple times.

Body:
In the book Hands-On ML with Scikit-Learn, Tensorflow and Keras, the author explains using the Data API to manipulate, transform and pass data to the model efficiently, he writes the following function:

def csv_reader(filepaths, batch_size=32):
    dataset = tf.data.Dataset.list_files(filepaths)
    dataset = dataset.interleave(lambda filepath:
    tf.data.TextLineDataset(filepath).skip(1), cycle_length=5)
    dataset = dataset.shuffle(10000).repeat(1)
    return dataset.batch(batch_size).prefetch(1)

Then : train_set = csv_reader_dataset(train_filepaths)

and: model.fit(train_set, epochs=10)

What I don't understand is the part where he creates the actual train_set from the function, isn't that way he only has one batch of data? He says that we create a training set once and don't need to repeat it as it will be taken care of by Keras but I don't see how.


问:
Thymeleaf - Getting full name of authenticated user
According to thymeleaf security page I can get the logged username and roles as below:

```<code>Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>
</code>```

I have a web application where authentication is done through active directory using ActiveDirectoryLdapAuthenticationProvider as below:

```<code>@Bean
@Override
public AuthenticationManager authenticationManager() {
    return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}

@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
    ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain,
            adUrl);
    provider.setConvertSubErrorCodesToExceptions(true);
    provider.setUseAuthenticationRequestCredentials(true);

    return provider;
}
</code>```

Then after the user logged in I have a header page that I use in all my pages with the above sec:authentication="name" thymeleaf tag to show the username, but I wanted to see if there's a way to show the full name instead.

Solution suggested here is not working for me:

I'm using: thymeleaf-extras-springsecurity5

and using:

Is giving me: Method getUser() cannot be found on type org.springframework.security.ldap.userdetails.LdapUserDetailsImpl

It seems this information comes from: org.springframework.security.ldap.userdetails.LdapUserDetailsImpl and there just a few options are, like the username, but not the rest of the information an AD can have.

答:
This is how I solved my issue:

First

I added to the provider an UserDetailsContextMapper with org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper as below:

```<code>@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
  ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain, adUrl);
  provider.setConvertSubErrorCodesToExceptions(true);
  provider.setUseAuthenticationRequestCredentials(true);
  provider.setUserDetailsContextMapper(userDetailsContextMapper());  <---

  return provider;
}

@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
  return new LdapUserDetailsMapper() {
      @Override
      public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
          InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
          return personContextMapper.mapUserFromContext(ctx, username, authorities);
      }
  };
}
</code>```

Second

Then in my header page I added:

```<code><span th:text ="${#authentication.getPrincipal().getDisplayName()}"></span>
</code>```

To display the full name.

With this approach you also have access to show all other AD related fields such as:

```<code><span th:text ="${#authentication.getPrincipal().getMail()}"></span>
<span th:text ="${#authentication.getPrincipal().getTelephoneNumber()}"></span>
<span th:text ="${#authentication.getPrincipal().getRoomNumber()}"></span>
</code>```

Body:
According to thymeleaf security page I can get the logged username and roles as below:

Logged user: Bob
Roles: [ROLE_USER, ROLE_ADMIN]

I have a web application where authentication is done through active directory using ActiveDirectoryLdapAuthenticationProvider as below:

@Bean
@Override
public AuthenticationManager authenticationManager() {
    return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}

@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
    ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain,
            adUrl);
    provider.setConvertSubErrorCodesToExceptions(true);
    provider.setUseAuthenticationRequestCredentials(true);

    return provider;
}

Then after the user logged in I have a header page that I use in all my pages with the above sec:authentication="name" thymeleaf tag to show the username, but I wanted to see if there's a way to show the full name instead.

Solution suggested here is not working for me:

I'm using: thymeleaf-extras-springsecurity5

and using:

Is giving me: Method getUser() cannot be found on type org.springframework.security.ldap.userdetails.LdapUserDetailsImpl

It seems this information comes from: org.springframework.security.ldap.userdetails.LdapUserDetailsImpl and there just a few options are, like the username, but not the rest of the information an AD can have.

Body:
This is how I solved my issue:

First

I added to the provider an UserDetailsContextMapper with org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper as below:

@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
  ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain, adUrl);
  provider.setConvertSubErrorCodesToExceptions(true);
  provider.setUseAuthenticationRequestCredentials(true);
  provider.setUserDetailsContextMapper(userDetailsContextMapper());  <---

  return provider;
}

@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
  return new LdapUserDetailsMapper() {
      @Override
      public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
          InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
          return personContextMapper.mapUserFromContext(ctx, username, authorities);
      }
  };
}

Second

Then in my header page I added:

<span th:text ="${#authentication.getPrincipal().getDisplayName()}"></span>

To display the full name.

With this approach you also have access to show all other AD related fields such as:

<span th:text ="${#authentication.getPrincipal().getMail()}"></span>
<span th:text ="${#authentication.getPrincipal().getTelephoneNumber()}"></span>
<span th:text ="${#authentication.getPrincipal().getRoomNumber()}"></span>


问:
Firebase create a new object every time I click a button
I have a problem/ question. I want to save different objects to firebase realtime database every time I click a button, but I have a problem because, since I have a Shopping list I click more items and I want to save them to the database but it saves just the last item I clicked and I want to understand what I'm doing wrong. I'm new to Android / Firebase, it's the first time I'm doing it so if anyone can tell me what I'm doing wrong it would be awesome. Thank you so much. I will attach the code and the photo of the database.

Activity :

```<code>public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
int position=0;
String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

public static int cart_count = 0;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
}

private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {

            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);

        addToCart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Users a = new Users(nome,surname,prezzo);
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference("Cart");
                myRef.setValue(a);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

    }
}

}
</code>```

enter code here

答:
You need to use the push() method:

```<code>myRef.push().setValue(a);
</code>```

Currently the last data you are adding is overriding the data before it. The push() method will create a random ID and separate each user.

Or if you are using firebase authentication then you can use the user uid instead of push() to separate each user that you are saving.

Body:
I have a problem/ question. I want to save different objects to firebase realtime database every time I click a button, but I have a problem because, since I have a Shopping list I click more items and I want to save them to the database but it saves just the last item I clicked and I want to understand what I'm doing wrong. I'm new to Android / Firebase, it's the first time I'm doing it so if anyone can tell me what I'm doing wrong it would be awesome. Thank you so much. I will attach the code and the photo of the database.

Activity :

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
int position=0;
String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

public static int cart_count = 0;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
}

private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {

            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);

        addToCart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Users a = new Users(nome,surname,prezzo);
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference("Cart");
                myRef.setValue(a);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

    }
}

}

enter code here

Body:
You need to use the push() method:

myRef.push().setValue(a);

Currently the last data you are adding is overriding the data before it. The push() method will create a random ID and separate each user.

Or if you are using firebase authentication then you can use the user uid instead of push() to separate each user that you are saving.


问:
"D/Notification: allPendingIntents" log while updating notification
I'm updating a notification while progress is updating and each time I get a log which is not in my code:

D/Notification: allPendingIntents

Notification creation code :

mProgressNotifBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setPriority(Notification.PRIORITY_HIGH)
    .setContentTitle(notifTitle)
    .setAutoCancel(false)
    .setProgress(MAX_PROGRESS, 0, true)
    .setContentIntent(getPendingIntent());
setOfflineNotificationChannelId();
Notification notification = mProgressNotifBuilder.build();
startForeground(NOTIF_ID, notification);
mNotificationManager.notify(NOTIF_ID, notification);
```

<p>Updating notification code:  </p>

<pre class="lang-java prettyprint-override"><code>private void updateNotificationProgress(int present) {
    mProgressNotifBuilder.setProgress(MAX_PROGRESS, present, false);
    mNotificationManager.notify(NOTIF_ID, mProgressNotifBuilder.build());
}
</code>```

What does this log mean and how can I resolve it?

答:
I hope I can help you, I've been having this problem recently, I think you need to add :

.setChannelId(NOTIFICATION_CHANNEL_ID)

in your code.
also check out this link:  https://developer.android.com/training/notify-user/channels
and watch the video.

so your code should look like this;

```<code>mProgressNotifBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setPriority(Notification.PRIORITY_HIGH)
    .setContentTitle(notifTitle)
    .setAutoCancel(false)
    .setChannelId(NOTIFICATION_CHANNEL_ID)   // <---- add this
    .setProgress(MAX_PROGRESS, 0, true)
    .setContentIntent(getPendingIntent());
setOfflineNotificationChannelId();
Notification notification = mProgressNotifBuilder.build();
startForeground(NOTIF_ID, notification);
mNotificationManager.notify(NOTIF_ID, notification);
</code>```

Body:
I'm updating a notification while progress is updating and each time I get a log which is not in my code:

D/Notification: allPendingIntents

Notification creation code :

mProgressNotifBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setPriority(Notification.PRIORITY_HIGH)
    .setContentTitle(notifTitle)
    .setAutoCancel(false)
    .setProgress(MAX_PROGRESS, 0, true)
    .setContentIntent(getPendingIntent());
setOfflineNotificationChannelId();
Notification notification = mProgressNotifBuilder.build();
startForeground(NOTIF_ID, notification);
mNotificationManager.notify(NOTIF_ID, notification);

Updating notification code:

private void updateNotificationProgress(int present) {
    mProgressNotifBuilder.setProgress(MAX_PROGRESS, present, false);
    mNotificationManager.notify(NOTIF_ID, mProgressNotifBuilder.build());
}

What does this log mean and how can I resolve it?

Body:
I hope I can help you, I've been having this problem recently, I think you need to add :

.setChannelId(NOTIFICATION_CHANNEL_ID)

in your code.
also check out this link:  https://developer.android.com/training/notify-user/channels
and watch the video.

so your code should look like this;

mProgressNotifBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setPriority(Notification.PRIORITY_HIGH)
    .setContentTitle(notifTitle)
    .setAutoCancel(false)
    .setChannelId(NOTIFICATION_CHANNEL_ID)   // <---- add this
    .setProgress(MAX_PROGRESS, 0, true)
    .setContentIntent(getPendingIntent());
setOfflineNotificationChannelId();
Notification notification = mProgressNotifBuilder.build();
startForeground(NOTIF_ID, notification);
mNotificationManager.notify(NOTIF_ID, notification);


问:
React - two different Switch
I have created two different Switch from react-router-dom. One main Switch have all main Routes with MainTemplate and now I want to add different Route without this MainTemplate to have blank page. Is there any way to do this with React Router Dom ?

```<code>return (
    <Provider store={store}>
      <BrowserRouter>

        // Different page for login without MainTemplate UI
        <Switch>
          <Route strict exact path="/login" component={LoginPage} />
        </Switch>

        <MainTemplate>
          <MenuSidebar />
          <NextMeet />
          <Suspense
            fallback={
              <div style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
                <h1>Ładowanie...</h1>
              </div>
            }
          >
            // Main Switch for the rest of an app
            <Switch>
              <PrivateRoute exact path={routes.home} component={Home} />
              <PrivateRoute exact strict path={routes.timetable} component={Timetable} />
              <PrivateRoute exact strict path={routes.topicDatabase} component={TopicDatabase} />
              <PrivateRoute exact strict path={routes.history} component={History} />
              <PrivateRoute exact strict path={routes.account} component={Account} />
            </Switch>
          </Suspense>
        </MainTemplate>
      </BrowserRouter>
    </Provider>
  );
</code>```

For now when I go to '/login I see LoginPage component and also MainTemplate, MenuSidebar and NextMeet components

答:
In this case, you should only have one <Switch> on this page. So, since Login doesn't require <MainTemplate>, this should be moved into a new component. Then, link to that component it's own <Route> (Aafter login) as a "catch all" for path="/".

Then, in your new page you made for the Main page, you can use the subroutes you have on that page.

Updated Page

```<code>  return (
    <Provider store={store}>
      <BrowserRouter>

        // Different page for login without MainTemplate UI
        <Switch>
          <Route strict exact path="/login" component={LoginPage} />
          <Route path="/" component={MainPage} />
        </Switch>

      </BrowserRouter>
    </Provider>
  );
</code>```

New "main-page.component.jsx

```<code>        <MainTemplate>
          <MenuSidebar />
          <NextMeet />
          <Suspense
            fallback={
              <div style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
                <h1>Ładowanie...</h1>
              </div>
            }
          >
            // Main Switch for the rest of an app
            <Switch>
              <PrivateRoute exact path={routes.home} component={Home} />
              <PrivateRoute exact strict path={routes.timetable} component={Timetable} />
              <PrivateRoute exact strict path={routes.topicDatabase} component={TopicDatabase} />
              <PrivateRoute exact strict path={routes.history} component={History} />
              <PrivateRoute exact strict path={routes.account} component={Account} />
            </Switch>
          </Suspense>
        </MainTemplate>
</code>```

Title: React - two different Switch

Body:
I have created two different Switch from react-router-dom. One main Switch have all main Routes with MainTemplate and now I want to add different Route without this MainTemplate to have blank page. Is there any way to do this with React Router Dom ?

return (
    <Provider store={store}>
      <BrowserRouter>

        // Different page for login without MainTemplate UI
        <Switch>
          <Route strict exact path="/login" component={LoginPage} />
        </Switch>

        <MainTemplate>
          <MenuSidebar />
          <NextMeet />
          <Suspense
            fallback={

Ładowanie...

            }
          >
            // Main Switch for the rest of an app
            <Switch>
              <PrivateRoute exact path={routes.home} component={Home} />
              <PrivateRoute exact strict path={routes.timetable} component={Timetable} />
              <PrivateRoute exact strict path={routes.topicDatabase} component={TopicDatabase} />
              <PrivateRoute exact strict path={routes.history} component={History} />
              <PrivateRoute exact strict path={routes.account} component={Account} />
            </Switch>
          </Suspense>
        </MainTemplate>
      </BrowserRouter>
    </Provider>
  );

For now when I go to '/login I see LoginPage component and also MainTemplate, MenuSidebar and NextMeet components

Body:
In this case, you should only have one <Switch> on this page. So, since Login doesn't require <MainTemplate>, this should be moved into a new component. Then, link to that component it's own <Route> (Aafter login) as a "catch all" for path="/".

Then, in your new page you made for the Main page, you can use the subroutes you have on that page.

Updated Page

  return (
    <Provider store={store}>
      <BrowserRouter>

        // Different page for login without MainTemplate UI
        <Switch>
          <Route strict exact path="/login" component={LoginPage} />
          <Route path="/" component={MainPage} />
        </Switch>

      </BrowserRouter>
    </Provider>
  );

New "main-page.component.jsx

        <MainTemplate>
          <MenuSidebar />
          <NextMeet />
          <Suspense
            fallback={
              <div style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
                <h1>Ładowanie...</h1>
              </div>
            }
          >
            // Main Switch for the rest of an app
            <Switch>
              <PrivateRoute exact path={routes.home} component={Home} />
              <PrivateRoute exact strict path={routes.timetable} component={Timetable} />
              <PrivateRoute exact strict path={routes.topicDatabase} component={TopicDatabase} />
              <PrivateRoute exact strict path={routes.history} component={History} />
              <PrivateRoute exact strict path={routes.account} component={Account} />
            </Switch>
          </Suspense>
        </MainTemplate>


问:
Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14
I am having an error regarding (Keras that does not support TensorFlow 2.0. We recommend using tf.keras, or alternatively, downgrading to TensorFlow 1.14.) any recommendations.

thanks

```<code>import keras
#For building the Neural Network layer by layer
from keras.models import Sequential
#To randomly initialize the weights to small numbers close to 0(But not 0)
from keras.layers import Dense

classifier=tf.keras.Sequential()

classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))

RuntimeError: It looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14.
</code>```

答:
I ran into the same issue. Downgraded my TensorFlow to version 1.14 using the following:

```<code>!pip install tensorflow==1.14.0
</code>```

Fixed the error.

Body:
I am having an error regarding (Keras that does not support TensorFlow 2.0. We recommend using tf.keras, or alternatively, downgrading to TensorFlow 1.14.) any recommendations.

thanks

import keras
#For building the Neural Network layer by layer
from keras.models import Sequential
#To randomly initialize the weights to small numbers close to 0(But not 0)
from keras.layers import Dense

classifier=tf.keras.Sequential()

classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))

RuntimeError: It looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14.

Body:
I ran into the same issue. Downgraded my TensorFlow to version 1.14 using the following:

!pip install tensorflow==1.14.0

Fixed the error.