问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
Since mvinstr is actually storing data into the array pointed at by the char*, you can't use a string there.  You need to allocate an array of char, pass that to mvinstr, and then transfer the characters to a string if you want.

If you were using a function that could have been declared with a const char * (i.e. it doesn't actually modify the array), then you could use const_cast<> to remove the const.

```<code>const_cast<char *>(str.c_str());
</code>```

But that's not what you're doing here.  const_cast might work if you tried it, but it would be by accident, not because it's supposed to work, and a new compiler or library version could break it at any time.

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
Since mvinstr is actually storing data into the array pointed at by the char*, you can't use a string there.  You need to allocate an array of char, pass that to mvinstr, and then transfer the characters to a string if you want.

If you were using a function that could have been declared with a const char * (i.e. it doesn't actually modify the array), then you could use const_cast<> to remove the const.

const_cast<char *>(str.c_str());

But that's not what you're doing here.  const_cast might work if you tried it, but it would be by accident, not because it's supposed to work, and a new compiler or library version could break it at any time.


来源: stackexchange

问:
ecto changeset add assoc for existing
Good morning! I've reached a moment where I'm struggling. To summarize, I'm trying to create a schema/model that has an association where the associated schema/model already exists. Every example I've found looks more like Rails nested attributes. Here is my various code thingses:

The schema (& its changeset function) with the associations:

```<code>schema "payor_procedure_mappings" do
  belongs_to :payor, Payor
  belongs_to :procedure, Procedure
  field :payor_procedure_name, :string
  field :payor_procedure_id, :string

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
  |> cast_assoc(:payor, params[:payor])  # <--- LINE 50 from stacktrace
end

defp required do
  :payor_procedure_name,
  :payor_procedure_id
]
</code>```

The pre-existing schema I want to associate with that:

```<code>schema "payors" do
  field :name, :string, null: :false
  field :polling_url, :string, null: :false

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end
</code>```

Here's the code where I'm attempting to set the association:

```<code>test "valid if all required params are present", %{procedure: procedure, payor: payor} do
  params = %{
    payor: payor,
    payor_procedure_name: "That one thing we do to patients",
    payor_procedure_id: "2342"
  }

changeset =
  %PayorProcedureMapping{}
  |> PayorProcedureMapping.changeset(params)   # THIS IS LINE 28 from stacktrace

  assert changeset.valid?
end
</code>```

(Please note that the payor in the second argument to the test function is an already loaded schema/model struct)

To be clear, my params being passed in look like this:

```<code>%{
  payor: %ReimbursementMonitor.Schemas.Payor{
    __meta__: #Ecto.Schema.Metadata<:loaded, "payors">,
    id: 12,
    inserted_at: ~N[2020-02-15 16:30:16],
    name: "test_name",
    polling_url: "www.example.com",
    updated_at: ~N[2020-02-15 16:30:16]
  },
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}
</code>```

The situation I've encountered is that if the payor exists already, my tests are really unhappy. I get this error when attempting to run that test:

```<code>** (FunctionClauseError) no function clause matching in Keyword.get_lazy/3

 The following arguments were given to Keyword.get_lazy/3:

     # 1
     nil

     # 2
     :with

     # 3
     #Function<5.89690842/0 in Ecto.Changeset.cast_relation/4>

 Attempted function clauses (showing 1 out of 1):

def get_lazy(keywords, key, fun) when is_list(keywords) and is_atom(key) and is_function(fun, 0)
  code: |> PayorProcedureMapping.changeset(params)
  stacktrace:
    (elixir) lib/keyword.ex:223: Keyword.get_lazy/3
    (ecto) lib/ecto/changeset.ex:778: Ecto.Changeset.cast_relation/4
    (reimbursement_monitor) lib/reimbursement_monitor/schemas/payor_procedure_mapping.ex:50: ReimbursementMonitor.Schemas.PayorProcedureMapping.changeset/2
    test/schemas/payor_procedure_mapping_test.exs:28: (test)
</code>```

Full disclosure, I've searched google a ton but the examples I've been able to find are creating or building the payor schema at the time the payor_procedure_mappings is inserted.

I feel like I'm off in the weeds. I'd love to get some pointers of where to go look, good examples of what I'm asking about.

Thanks for your help in advance!

答:
Can you try the following:

```<code># the params that you pass in
%{
  payor_id: 12,
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}

# the changeset function for payor_procedure_mappings
def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end
</code>```

I think the purpose of cast_assoc is to create new associated record(s), which is why you only found examples for doing that. Since you only want to associate the payor_procedure_mappings record you are creating to an existing payor record, I believe you just need to set the appropriate id.

ContentLicense: CC BY-SA 4.0

Title: ecto changeset add assoc for existing

Body:
Good morning! I've reached a moment where I'm struggling. To summarize, I'm trying to create a schema/model that has an association where the associated schema/model already exists. Every example I've found looks more like Rails nested attributes. Here is my various code thingses:

The schema (& its changeset function) with the associations:

schema "payor_procedure_mappings" do
  belongs_to :payor, Payor
  belongs_to :procedure, Procedure
  field :payor_procedure_name, :string
  field :payor_procedure_id, :string

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
  |> cast_assoc(:payor, params[:payor])  # <--- LINE 50 from stacktrace
end

defp required do
  :payor_procedure_name,
  :payor_procedure_id
]

The pre-existing schema I want to associate with that:

schema "payors" do
  field :name, :string, null: :false
  field :polling_url, :string, null: :false

  timestamps()
end

def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end

Here's the code where I'm attempting to set the association:

test "valid if all required params are present", %{procedure: procedure, payor: payor} do
  params = %{
    payor: payor,
    payor_procedure_name: "That one thing we do to patients",
    payor_procedure_id: "2342"
  }

changeset =
  %PayorProcedureMapping{}
  |> PayorProcedureMapping.changeset(params)   # THIS IS LINE 28 from stacktrace

  assert changeset.valid?
end

(Please note that the payor in the second argument to the test function is an already loaded schema/model struct)

To be clear, my params being passed in look like this:

%{
  payor: %ReimbursementMonitor.Schemas.Payor{
    __meta__: #Ecto.Schema.Metadata<:loaded, "payors">,
    id: 12,
    inserted_at: ~N[2020-02-15 16:30:16],
    name: "test_name",
    polling_url: "www.example.com",
    updated_at: ~N[2020-02-15 16:30:16]
  },
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}

The situation I've encountered is that if the payor exists already, my tests are really unhappy. I get this error when attempting to run that test:

** (FunctionClauseError) no function clause matching in Keyword.get_lazy/3

 The following arguments were given to Keyword.get_lazy/3:

     # 1
     nil

     # 2
     :with

     # 3
     #Function<5.89690842/0 in Ecto.Changeset.cast_relation/4>

 Attempted function clauses (showing 1 out of 1):

def get_lazy(keywords, key, fun) when is_list(keywords) and is_atom(key) and is_function(fun, 0)
  code: |> PayorProcedureMapping.changeset(params)
  stacktrace:
    (elixir) lib/keyword.ex:223: Keyword.get_lazy/3
    (ecto) lib/ecto/changeset.ex:778: Ecto.Changeset.cast_relation/4
    (reimbursement_monitor) lib/reimbursement_monitor/schemas/payor_procedure_mapping.ex:50: ReimbursementMonitor.Schemas.PayorProcedureMapping.changeset/2
    test/schemas/payor_procedure_mapping_test.exs:28: (test)

Full disclosure, I've searched google a ton but the examples I've been able to find are creating or building the payor schema at the time the payor_procedure_mappings is inserted.

I feel like I'm off in the weeds. I'd love to get some pointers of where to go look, good examples of what I'm asking about.

Thanks for your help in advance!

Body:
Can you try the following:

# the params that you pass in
%{
  payor_id: 12,
  payor_procedure_id: "2342",
  payor_procedure_name: "That one thing we do to patients"
}

# the changeset function for payor_procedure_mappings
def changeset(model, params \\ %{}) do
  model
  |> cast(params, all_params())
  |> validate_required(required())
end

I think the purpose of cast_assoc is to create new associated record(s), which is why you only found examples for doing that. Since you only want to associate the payor_procedure_mappings record you are creating to an existing payor record, I believe you just need to set the appropriate id.


问:
Alter Database to utf8 In Rails
I'm trying to Alter a database to accept utf8_general_ci in migration file

```<code>class AlterTableToArabic < ActiveRecord::Migration[5.2]
  def change
    ALTER DATABASE noswazefa_backend_development CHARACTER SET utf8 COLLATE utf8_general_ci;
  end
end
</code>```

but when I run rake db:migrate, this error appears in console:

-- utf8_general_ci()
      rake aborted!
      StandardError: An error has occurred, all later migrations canceled:
      undefined local variable or method `utf8_general_ci' for # < AlterTableToArabic:0x000055e5b967b020 >

答:
generate migration file and paste this code</p>

```<code>class ConvertTablesToUtf8 < ActiveRecord::Migration[5.2]
 def change_encoding(encoding,collation)
 connection = ActiveRecord::Base.connection
 tables = connection.tables
 dbname =connection.current_database
 execute <<-SQL
   ALTER DATABASE #{dbname} CHARACTER SET #{encoding} COLLATE #{collation};
 SQL
 tables.each do |tablename|
   execute <<-SQL
     ALTER TABLE #{dbname}.#{tablename} CONVERT TO CHARACTER SET #{encoding} COLLATE #{collation};
   SQL
 end
 end

def change
 reversible do |dir|
   dir.up do
     change_encoding('utf8','utf8_general_ci')
   end
   dir.down do
     change_encoding('latin1','latin1_swedish_ci')
   end
 end
end
end
</code>```

Title: Alter Database to utf8 In Rails

Body:
I'm trying to Alter a database to accept utf8_general_ci in migration file

class AlterTableToArabic < ActiveRecord::Migration[5.2]
  def change
    ALTER DATABASE noswazefa_backend_development CHARACTER SET utf8 COLLATE utf8_general_ci;
  end
end

but when I run rake db:migrate, this error appears in console:

-- utf8_general_ci()
      rake aborted!
      StandardError: An error has occurred, all later migrations canceled:
      undefined local variable or method `utf8_general_ci' for # < AlterTableToArabic:0x000055e5b967b020 >

Body:
generate migration file and paste this code

class ConvertTablesToUtf8 < ActiveRecord::Migration[5.2]
 def change_encoding(encoding,collation)
 connection = ActiveRecord::Base.connection
 tables = connection.tables
 dbname =connection.current_database
 execute <<-SQL
   ALTER DATABASE #{dbname} CHARACTER SET #{encoding} COLLATE #{collation};
 SQL
 tables.each do |tablename|
   execute <<-SQL
     ALTER TABLE #{dbname}.#{tablename} CONVERT TO CHARACTER SET #{encoding} COLLATE #{collation};
   SQL
 end
 end

def change
 reversible do |dir|
   dir.up do
     change_encoding('utf8','utf8_general_ci')
   end
   dir.down do
     change_encoding('latin1','latin1_swedish_ci')
   end
 end
end
end


问:
Why does my window scroll function fire up everytime i load page instead of onchange?
I want the scroll to only occur after I select an option. But why is the scroll being triggered every time I load page instead?

function search2() { window.scrollTo({
  top: 300,
  left: 0,
  behavior: 'smooth'
}); };
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id = "make" onchange="search2();">
<option>Audi</option>
</select></code>```

答:
i have tested your code but didnt notice what you said but for firing onchange event you have to use more than one option like so :

```<code><select id = "make" onchange="search2();">
<option>Audi</option>
<option>BMW</option>
</select>

<script>
function search2() { window.scrollTo({
  top: 300,
  left: 0,
  behavior: 'smooth'
}); };
</script>
</code>```

you can check my example too https://jsfiddle.net/kv263oyn/

Body:
I want the scroll to only occur after I select an option. But why is the scroll being triggered every time I load page instead?

function search2() { window.scrollTo({
  top: 300,
  left: 0,
  behavior: 'smooth'
}); };

<select id = "make" onchange="search2();">
<option>Audi</option>
</select>

Body:
i have tested your code but didnt notice what you said but for firing onchange event you have to use more than one option like so :

<select id = "make" onchange="search2();">
<option>Audi</option>
<option>BMW</option>
</select>

<script>
function search2() { window.scrollTo({
  top: 300,
  left: 0,
  behavior: 'smooth'
}); };
</script>

you can check my example too https://jsfiddle.net/kv263oyn/


问:
How to delete an element from a 2D Numpy array without knowing its position
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

```<code>>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])
</code>```

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

```<code>>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])
</code>```

And trying to find the location (as has been suggested) seems equally problematic:

```<code>>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))
</code>```

(Where did that 3 come from?!?)

答:
From the documentation:

numpy.delete(arr, obj, axis=None)

axis : int, optional

The axis along which to delete the subarray defined by obj. If axis
  is None, obj is applied to the flattened array

If you don't specify the axis(i.e. None), it will automatically flatten your array; you just need to specify the axis parameter, in your case np.delete(arr, [0,1],axis=0)

However, just like in the example above, [0,1] is a list of indices; you must provide the indices/location(you can do that with np.where(condition,array) for example)

Here you have a working example:

```<code>    my_array = np.array([[0, 1],
                         [1, 0],
                         [1, 1],
                         [0, 0]])

    row_index, = np.where(np.all(my_array == [0, 1], axis=1))
    my_array = np.delete(my_array, row_index,axis=0)
    print(my_array)

    #Output is below

        [[1 0]
         [1 1]
         [0 0]]
</code>```

Body:
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])

And trying to find the location (as has been suggested) seems equally problematic:

>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))

(Where did that 3 come from?!?)

Body:
From the documentation:

numpy.delete(arr, obj, axis=None)

axis : int, optional

The axis along which to delete the subarray defined by obj. If axis
  is None, obj is applied to the flattened array

If you don't specify the axis(i.e. None), it will automatically flatten your array; you just need to specify the axis parameter, in your case np.delete(arr, [0,1],axis=0)

However, just like in the example above, [0,1] is a list of indices; you must provide the indices/location(you can do that with np.where(condition,array) for example)

Here you have a working example:

    my_array = np.array([[0, 1],
                         [1, 0],
                         [1, 1],
                         [0, 0]])

    row_index, = np.where(np.all(my_array == [0, 1], axis=1))
    my_array = np.delete(my_array, row_index,axis=0)
    print(my_array)

    #Output is below

        [[1 0]
         [1 1]
         [0 0]]


问:
Error while using string.Format for strings with newline chars
Getting error while using string.Format

errorMessage is "OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title='Client nc.']"}"

code:

```<code>errorMessage = (exceptions.CurrentDotNetExceptionMessage.ToString() + "\n" + exceptions.CurrentDotNetInnerException.ToString().Split(new[] { '\r', '\n' }).FirstOrDefault()) ?? string.Empty;

 defectDetails = string.Format($"Issue: {actualResult} \n\n" +
                $"Steps To Reproduce: \n {stepsToReproduce} \n\n" +
                $"Failed Step: \n {failedStep} \n" +
                $"Failed Element: \n {failedElement} \n" +
                $"Test Data: \n {testData} \n\n" +
                $"Actual Result: \n {actualResult} \n" +
                $"Expected Result: \n {expectedResult} \n" +
                $"Error Message: \n {errorMessage.ToString()} \n\n" +
                $"Browser: {browser} \n" +
                $"Enviornment: {environment}\n\n" +
                $"Stack Trace: {stackTrace}" +
                $"\n---------------------------------------------------------------------------------------------------\n\n"
                );```
Error Line:
```string.Format($"Error Message: \n {errorMessage} \n");```

Error: string.FormatException
```

答:
Error is in the first line when assigning errorMessage .In the end of the assigned string you put {"method":"xpath","selector":"//div[@title='Apple nc.']"}";
when you want to use " in your string you must put a \ before, otherwise it's assumed as the end of the string.</p>

Body:
Getting error while using string.Format

errorMessage is "OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title='Client nc.']"}"

code:

errorMessage = (exceptions.CurrentDotNetExceptionMessage.ToString() + "\n" + exceptions.CurrentDotNetInnerException.ToString().Split(new[] { '\r', '\n' }).FirstOrDefault()) ?? string.Empty;

 defectDetails = string.Format($"Issue: {actualResult} \n\n" +
                $"Steps To Reproduce: \n {stepsToReproduce} \n\n" +
                $"Failed Step: \n {failedStep} \n" +
                $"Failed Element: \n {failedElement} \n" +
                $"Test Data: \n {testData} \n\n" +
                $"Actual Result: \n {actualResult} \n" +
                $"Expected Result: \n {expectedResult} \n" +
                $"Error Message: \n {errorMessage.ToString()} \n\n" +
                $"Browser: {browser} \n" +
                $"Enviornment: {environment}\n\n" +
                $"Stack Trace: {stackTrace}" +
                $"\n---------------------------------------------------------------------------------------------------\n\n"
                );```
Error Line:
```string.Format($"Error Message: \n {errorMessage} \n");```

Error: string.FormatException


问:
"internal/modules/cjs/loader.js:582 throw err"
I'm getting the following error in the console:
Error : Cannot find module.

Here is the full error. What should I do?

```<code>internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
</code>```

答:
Something weird happened to me last night.
I ran command node run watch instead of npm run watch.
I tried doing everything on this thread but nothing worked out for me. I was frustrated but eventually noticed that I ran the command wrong. I was laughing out loud. Sometimes this things happened. Enjoying learning Nodejs though.

Body:
I'm getting the following error in the console:
Error : Cannot find module.

Here is the full error. What should I do?

internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)


问:
change html dynamically using ajax and php
I'm developing my website. I have a comment section. I want to to show just two of them at a time. so I want to fetch comments from database and replace with another after a specific time(like slideshow). I want to just show name and comment of each user.

```<code><div class="testimonials-item">
              <div class="user row">
                <div class="col-lg-3 col-md-4">
                  <div class="user_image">
                    <img src="assets/images/face2.jpg">
                  </div>
                </div>
                <div class="testimonials-caption col-lg-9 col-md-8">
                  <div class="user_text ">
                    <p class="mbr-fonts-style  display-7" style="margin-left: 2em">
                       <em>a comment</em>
                    </p>
                  </div>
                  <div class="user_name mbr-bold mbr-fonts-style align-right pt-3 display-7">
                       maria
                  </div>
                </div>
              </div>
            </div>
</code>```

.

```<code>$sql = "select id, comment from comment where verify=1";
$res = mysqli_query($con, $sql);
</code>```

help me if you can.
thank you

答:
Hope this help you.</p>

```<code>index.php

<div class="testimonials-item"></div>

<form id="idForm" method="post">
    <button type="submit" name="submit">Submit</button>
</form>
   <script>
 $("#idForm").submit(function(e) {
    e.preventDefault(); // avoid to execute the actual submit of the form.
    $.ajax({
           type: "POST",
           url: 'AjaxFile.php',
           data: {data: "someData"}, // serializes the form's elements.
           success: function(data)
           {
               //alert(data); // show response from the php script.
               $('.testimonials-item').html(data);
           }
         });
});

    </script>

AjaxFile.php

<?php

//$sql = "select id, comment from comment where verify=1";
//$res = mysqli_query($con, $sql);

//can you change return data
//you have multple row use while or foreach

echo '<div class="user row">
                <div class="col-lg-3 col-md-4">
                  <div class="user_image">
                    <img src="https://picsum.photos/200/300">
                  </div>
                </div>
                <div class="testimonials-caption col-lg-9 col-md-8">
                  <div class="user_text ">
                    <p class="mbr-fonts-style  display-7" style="margin-left: 2em">
                       <em>a comment</em>
                    </p>
                  </div>
                  <div class="user_name mbr-bold mbr-fonts-style align-right pt-3 display-7">
                       maria
                  </div>
                </div>
              </div>';
echo '<div class="user row">
                <div class="col-lg-3 col-md-4">
                  <div class="user_image">
                    <img src="https://picsum.photos/seed/picsum/200/300">
                  </div>
                </div>
                <div class="testimonials-caption col-lg-9 col-md-8">
                  <div class="user_text ">
                    <p class="mbr-fonts-style  display-7" style="margin-left: 2em">
                       <em>B comment</em>
                    </p>
                  </div>
                  <div class="user_name mbr-bold mbr-fonts-style align-right pt-3 display-7">
                       Beta
                  </div>
                </div>
              </div>';
?>
</code>```

Body:
I'm developing my website. I have a comment section. I want to to show just two of them at a time. so I want to fetch comments from database and replace with another after a specific time(like slideshow). I want to just show name and comment of each user.

                       a comment

                       maria

.

$sql = "select id, comment from comment where verify=1";
$res = mysqli_query($con, $sql);

help me if you can.
thank you

Body:
Hope this help you.

index.php

<div class="testimonials-item"></div>

<form id="idForm" method="post">
    <button type="submit" name="submit">Submit</button>
</form>
   <script>
 $("#idForm").submit(function(e) {
    e.preventDefault(); // avoid to execute the actual submit of the form.
    $.ajax({
           type: "POST",
           url: 'AjaxFile.php',
           data: {data: "someData"}, // serializes the form's elements.
           success: function(data)
           {
               //alert(data); // show response from the php script.
               $('.testimonials-item').html(data);
           }
         });
});

    </script>

AjaxFile.php

<?php

//$sql = "select id, comment from comment where verify=1";
//$res = mysqli_query($con, $sql);

//can you change return data
//you have multple row use while or foreach

echo '<div class="user row">
                <div class="col-lg-3 col-md-4">
                  <div class="user_image">
                    <img src="https://picsum.photos/200/300">
                  </div>
                </div>
                <div class="testimonials-caption col-lg-9 col-md-8">
                  <div class="user_text ">
                    <p class="mbr-fonts-style  display-7" style="margin-left: 2em">
                       <em>a comment</em>
                    </p>
                  </div>
                  <div class="user_name mbr-bold mbr-fonts-style align-right pt-3 display-7">
                       maria
                  </div>
                </div>
              </div>';
echo '<div class="user row">
                <div class="col-lg-3 col-md-4">
                  <div class="user_image">
                    <img src="https://picsum.photos/seed/picsum/200/300">
                  </div>
                </div>
                <div class="testimonials-caption col-lg-9 col-md-8">
                  <div class="user_text ">
                    <p class="mbr-fonts-style  display-7" style="margin-left: 2em">
                       <em>B comment</em>
                    </p>
                  </div>
                  <div class="user_name mbr-bold mbr-fonts-style align-right pt-3 display-7">
                       Beta
                  </div>
                </div>
              </div>';
?>


问:
How would you design a good search UI?
I want to provide my users with an 'advanced' search engine.
I basically have a lot of search criteria to chose from :

some are very simple/common and will be largely use (ie time period, item id)

some are a bit less mainstream

and some won't be used a lot, but I still want to provide them

Overall, I have around 30+ criteria to chose from

The result is a dataset which I display in a grid.

I've search for inspiration on internet, and even google doesn't seem to have a nice solution for advanced search.

I've designed this kind of tools in the past, and I wasn't really pleased by the result, although the user were eventually able to use it quite effectively.

Do you think the search panel should be visible all the time (ie displayed on top of my result grid) or available in a separate form (which would let me use more place for all the controls)

Do you think it's better to display all the search criteria, or to let the user click on 'advanced' if he wants to see/use more criteria

How would you organize the criteria? by usage frequency, or rather by area (ie. criteria related to user, to location, to time, etc.)

Where should I put the 'Search' button? next to the more common search controls, or at the bottom, or both?

And more generally, do you have tips you want to share on how to design a nice search UI ?
What kind of functionalities do you usually miss in this kind of 'advanced' search engines?

答:
Take a look at quince, the infragistics ui patterns site: http://quince.infragistics.com.

Personally, I'd look at using a filterable grid, like the xtragrid from DevExpress: http://www.devexpress.com/Products/NET/Controls/WinForms/Grid/datafiltering.xml

coupled with a search bar above it to initially populate the grid.

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

Title: How would you design a good search UI?

LastEditorDisplayName: onnodb

OwnerDisplayName: codeburns


问:
Getting click event from parent container except certain children
Expected behavior: When I click on the .parent class, an item detail modal will be shown but the modal won't be shown if I click on the .dropdown or any of it's option.

```<code><div class="parent click-for-item-detail">

  <div class="dropdown">
    <a href="#" class="dropdown-toggle " data-toggle="dropdown">Options</a>
    <ul class="dropdown-menu">
      <li><a href="#">option-1</a></li>
      <li><a href="#">option-2</a></li>
    </ul>
  </div>

  <div class="item-image"><img class="click-for-item-detail" src="image.jpg></div>

  <div class="info">
    <a href="#" class="click-for-item-detail">Item title</a>
    <div class="click-for-item-detail"> item subtitle</div>
  </div>

</div>
</code>```

So far:

```<code>$(".click-for-item-detail").on("click",function(e){

        // show the modal if the target itself has been clicked
        if(e.target === this) {
            $('#itemDetailModal').modal('toggle');
        }
    });
</code>```

I have added click-for-item-detail class in every element that should trigger the item detail modal. Is there a better way to achieve this?

答:
You can use :not() selector to filter out the element you do not to be clicked:

$('.parent > :not(.dropdown)').click(function(e){
  alert('modal');
  //show modal
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">

  <div class="dropdown">
    Options
    <ul class="dropdown-menu">
      <li>option-1</li>
      <li>option-2</li>
    </ul>
  </div>

  <div class="item-image"><img src="image.jpg"></div>

  <div class="info">
    Item title
    <div> item subtitle</div>
  </div>

</div></code>```

Body:
Expected behavior: When I click on the .parent class, an item detail modal will be shown but the modal won't be shown if I click on the .dropdown or any of it's option.

    Options

option-1

option-2

    Item title

 item subtitle

So far:

$(".click-for-item-detail").on("click",function(e){

        // show the modal if the target itself has been clicked
        if(e.target === this) {
            $('#itemDetailModal').modal('toggle');
        }
    });

I have added click-for-item-detail class in every element that should trigger the item detail modal. Is there a better way to achieve this?

Body:
You can use :not() selector to filter out the element you do not to be clicked:

$('.parent > :not(.dropdown)').click(function(e){
  alert('modal');
  //show modal
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">

  <div class="dropdown">
    <a href="#" class="dropdown-toggle " data-toggle="dropdown">Options</a>
    <ul class="dropdown-menu">
      <li><a href="#">option-1</a></li>
      <li><a href="#">option-2</a></li>
    </ul>
  </div>

  <div class="item-image"><img src="image.jpg"></div>

  <div class="info">
    <a href="#">Item title</a>
    <div> item subtitle</div>
  </div>

</div>


问:
How to get data from my axios request without using a setTimeout?
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

```<code> let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;
</code>```

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

```<code>import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}
</code>```

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.

答:
I guess you can spent some time in understanding Promises and async/awiat

For eg: if you do this, your console will have all tasks listed.

```<code> data.then(response => {
   tasks = response;
   console.log(tasks);
 });
</code>```

Reason for that is the function you are passing to .then function of a promise is not executed immediately, its executed once a Promise is resolved(In your case after finishing execution of the http request.)

To get a more line by line execution feel you can use async/await

```<code>  let tasks = await Axios.get("http://localhost:8080/api/taskExecution?&search=&page=1&size=8")
    .then(response => {
      if (response.status !== 200) {
         console.log("LOADING");
      } else {
         return response.data;
      }
    });
    console.log(tasks);
    return tasks;
</code>```

The catch is that you can use await only inside an async function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Body:
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

 let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.

Body:
I guess you can spent some time in understanding Promises and async/awiat

For eg: if you do this, your console will have all tasks listed.

 data.then(response => {
   tasks = response;
   console.log(tasks);
 });

Reason for that is the function you are passing to .then function of a promise is not executed immediately, its executed once a Promise is resolved(In your case after finishing execution of the http request.)

To get a more line by line execution feel you can use async/await

  let tasks = await Axios.get("http://localhost:8080/api/taskExecution?&search=&page=1&size=8")
    .then(response => {
      if (response.status !== 200) {
         console.log("LOADING");
      } else {
         return response.data;
      }
    });
    console.log(tasks);
    return tasks;

The catch is that you can use await only inside an async function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


问:
How can I get a fixed address-bar in Google Chrome for Android with javascript
http://s7.picofile.com/file/8388260676/photo.jpg

When I click "No. 1", The page shows like a Nav-Mobile (No. 2);
But when I go "up/down-touch/move" on the "No. 3",
Address-bar (No. 4) is disabled in Google Chrome (Android Phone).
The load address is fixed in Google Chrome. (Like Website: Alibaba.com)
I want the address bar No. 6 to not be moved,
When I go up and down in  No. 5.
I added the following code in CSS, But it doesn't work.

```<code>position:fixed;
width: 100%;
height:100%
float:left;
</code>```

How can I get a fixed address-bar in Google Chrome for Android with javascript?

答:
Try this code below:</p>

```<code><style type="text/css">
  html, body {margin: 0; height: 100%; overflow: hidden}
</style>
</code>```

Body:
http://s7.picofile.com/file/8388260676/photo.jpg

When I click "No. 1", The page shows like a Nav-Mobile (No. 2);
But when I go "up/down-touch/move" on the "No. 3",
Address-bar (No. 4) is disabled in Google Chrome (Android Phone).
The load address is fixed in Google Chrome. (Like Website: Alibaba.com)
I want the address bar No. 6 to not be moved,
When I go up and down in  No. 5.
I added the following code in CSS, But it doesn't work.

position:fixed;
width: 100%;
height:100%
float:left;

How can I get a fixed address-bar in Google Chrome for Android with javascript?

Body:
Try this code below:

<style type="text/css">
  html, body {margin: 0; height: 100%; overflow: hidden}
</style>


问:
How to inject dependency into Jackson Custom serializer
In this question I've seen an interesting approach for injecting objects into custom deserializers for the Jackson mapping framework (I'm currently on version 2.10.x).
Essentially, one registers a dependency MyService in the ObjectMapper

 jsonMapper.setInjectableValues(new InjectableValues
                .Std()
                .addValue(MyService.class.getName(), myServiceInstance));
```

and then in a class that extends StdDeserializer it can be accessed through the DeserializationContext which has a findInjectableValue method.

Now, I hope the library provides a symmetric approach for serialisation, but honestly could not find it. Specifically, if you have a class that extends StdSerializer, you will need to implement a method  serialize(ProjectSerializable value, JsonGenerator jsonGenerator, SerializerProvider provider) which doesn't seems to have a class with similar features of DeserializationContext.

So, how can one achieve the same "injection" with a custom serializer without resorting to ugly solutions based on static access to instance providers or other untestable things.

答:
It seems to me that the only way to achieve this is via setting attributes for the SerializerProvider that will be used by the custom serializer.

When you create the ObjectMapper, then you have to hack it by creating a new one

ObjectMapper objectMapper = ...// here you create the ObjectMapper will all your configs

// Then you inject the service.

SerializationConfig initialSerializationConfig = objectMapper.getSerializationConfig();
ContextAttributes attributes = initialSerializationConfig.getAttributes();
// Here we create a new ContextAttributes with the class we want
//   to have shared for each serializer
ContextAttributes attributesWithInjectedValue =
         attributes.withSharedAttribute(MyService.class.getName(), myServiceInstance);
SerializationConfig serializationConfigWithInjectedValue =
         initialSerializationConfig.with(attributesWithInjectedValue);

return jsonMapper.setConfig(serializationConfigWithInjectedValue);
```

<p>Then in the instance of the <code>JsonSerializer</code> you simply do:</p>

<pre class="lang-java prettyprint-override"><code>MyService myService = (MyService) serializerProvider
        .getAttribute(MyService.class.getName());
</code>```

where serializerProvider is the instance of SerializerProvider given with the serialize method.

I don't like the asymmetry with the other approach shown for deserialization, but it works.

Body:
In this question I've seen an interesting approach for injecting objects into custom deserializers for the Jackson mapping framework (I'm currently on version 2.10.x).
Essentially, one registers a dependency MyService in the ObjectMapper

 jsonMapper.setInjectableValues(new InjectableValues
                .Std()
                .addValue(MyService.class.getName(), myServiceInstance));

and then in a class that extends StdDeserializer it can be accessed through the DeserializationContext which has a findInjectableValue method.

Now, I hope the library provides a symmetric approach for serialisation, but honestly could not find it. Specifically, if you have a class that extends StdSerializer, you will need to implement a method  serialize(ProjectSerializable value, JsonGenerator jsonGenerator, SerializerProvider provider) which doesn't seems to have a class with similar features of DeserializationContext.

So, how can one achieve the same "injection" with a custom serializer without resorting to ugly solutions based on static access to instance providers or other untestable things.

Body:
It seems to me that the only way to achieve this is via setting attributes for the SerializerProvider that will be used by the custom serializer.

When you create the ObjectMapper, then you have to hack it by creating a new one

ObjectMapper objectMapper = ...// here you create the ObjectMapper will all your configs

// Then you inject the service.

SerializationConfig initialSerializationConfig = objectMapper.getSerializationConfig();
ContextAttributes attributes = initialSerializationConfig.getAttributes();
// Here we create a new ContextAttributes with the class we want
//   to have shared for each serializer
ContextAttributes attributesWithInjectedValue =
         attributes.withSharedAttribute(MyService.class.getName(), myServiceInstance);
SerializationConfig serializationConfigWithInjectedValue =
         initialSerializationConfig.with(attributesWithInjectedValue);

return jsonMapper.setConfig(serializationConfigWithInjectedValue);

Then in the instance of the JsonSerializer you simply do:

MyService myService = (MyService) serializerProvider
        .getAttribute(MyService.class.getName());

where serializerProvider is the instance of SerializerProvider given with the serialize method.

I don't like the asymmetry with the other approach shown for deserialization, but it works.


问:
npm: import from outside the src folder
So I have this NodeJS project with the following folder tree

```<code>+ node-folder
   + react-app-folder
   + (other folders...)
   + config
       + default.json
</code>```

What I am trying to do is import that default.json file to any file in that react-app-folder.

The node-folder and react-app-folder have their own package.json file.

Is there any way of doing this?

Thank you all very much.

EDIT:
For more details about the node-folder . It is a NodeJS app server whose package.json has a script using concurrently to run both the nodejs-app on port 3000 and react-app on port 3001

答:
i think require is ok, isn't it?

commonjs

// node-folder/config/default.json
exports.PORT = 8080;
```

<pre class="lang-js prettyprint-override"><code>// node-folder/server/app.js
var config = require('../config/config');

console.log(config.PORT);
</code>```

Title: npm: import from outside the src folder

Body:
So I have this NodeJS project with the following folder tree

+ node-folder
   + react-app-folder
   + (other folders...)
   + config
       + default.json

What I am trying to do is import that default.json file to any file in that react-app-folder.

The node-folder and react-app-folder have their own package.json file.

Is there any way of doing this?

Thank you all very much.

EDIT:
For more details about the node-folder . It is a NodeJS app server whose package.json has a script using concurrently to run both the nodejs-app on port 3000 and react-app on port 3001

Body:
i think require is ok, isn't it?

commonjs

// node-folder/config/default.json
exports.PORT = 8080;

// node-folder/server/app.js
var config = require('../config/config');

console.log(config.PORT);


问:
Promise is not resolving even after calling resolve()
My question here may sound little repetitive. But I haven't found any answer on stackoverflow which can solve my problem.

I am returning a promise from one of my function. The promise will be resolved after getting some data from database. And will be rejected if there is no data in the db table. Also I have to do some processing on the fetched data before resolving the promise, that's why I am using callbacks.

My Code Snippet

```<code>return new Promise((resolve, reject) => {

            ResourceModel.getById(resource_ID).then((data) => {
                if (data.length > 0) {
                    console.log(data);
                    resolve(data);
                    console.log("Resolve Function Called");
                } else {
                    console.log("No data available");
                    reject(new Error("No data available"));
                }
            });
        });
</code>```

ResourceModel.getById()

```<code>static getById(id) {
        const _transaction = cds.transaction();

        return _transaction.run(SELECT.from(Resource).where({ ID: id }));
    }
</code>```

cds.transaction() is one of cds framework provided method by SAP.

What I expect it to do is after successfully fetching all the records it should call the provided callback where I have my processing logic written and call resolve() after the processing is done.

I am receiving the data in the callback, able to print Data available and the received data object end even the Promise Resolved on the console. But surprisingly the promise is not getting resolved

I can say the "promise is not getting resolved" because this returned promise will be collected in a Promise.all() by the framework (as stated in the official docs - https://cap.cloud.sap/docs/node.js/api#service-before) and return a response after resolving. But I am not getting any response (neither success nor failure). Postman stays in loading... state forever.

The above example works fine with setTimeout() example.

where am I going wrong?

答:
I have faced this type of error while making API calls or fetching data from the db.
Generally the issue used to be type mismatch of called resources or header is having wrong return type.
It would be good to have console.log in getById() and see what's happening thete in the stack trace.</p>

Body:
My question here may sound little repetitive. But I haven't found any answer on stackoverflow which can solve my problem.

I am returning a promise from one of my function. The promise will be resolved after getting some data from database. And will be rejected if there is no data in the db table. Also I have to do some processing on the fetched data before resolving the promise, that's why I am using callbacks.

My Code Snippet

return new Promise((resolve, reject) => {

            ResourceModel.getById(resource_ID).then((data) => {
                if (data.length > 0) {
                    console.log(data);
                    resolve(data);
                    console.log("Resolve Function Called");
                } else {
                    console.log("No data available");
                    reject(new Error("No data available"));
                }
            });
        });

ResourceModel.getById()

static getById(id) {
        const _transaction = cds.transaction();

        return _transaction.run(SELECT.from(Resource).where({ ID: id }));
    }

cds.transaction() is one of cds framework provided method by SAP.

What I expect it to do is after successfully fetching all the records it should call the provided callback where I have my processing logic written and call resolve() after the processing is done.

I am receiving the data in the callback, able to print Data available and the received data object end even the Promise Resolved on the console. But surprisingly the promise is not getting resolved

I can say the "promise is not getting resolved" because this returned promise will be collected in a Promise.all() by the framework (as stated in the official docs - https://cap.cloud.sap/docs/node.js/api#service-before) and return a response after resolving. But I am not getting any response (neither success nor failure). Postman stays in loading... state forever.

The above example works fine with setTimeout() example.

where am I going wrong?


答:
It is true what Phong is saying and that works. However, imagine now you had many child elements in your parent all matching that selector. With something like below, you would add an event listener to each of those elements.

$(".info, .item-image").on("click", function(){
  console.log("Trigger");
});
```

<p>While with your first approach you were already very close to only have one listener, no matter how many child elements are in the parent.</p>

<p>Consider following example:</p>

<pre class="lang-html prettyprint-override"><code>  <ul class='parent'>
    <li>No</li>
    <li>Click</li>
    <li>Event</li>
  </ul>

</code>```

$(".parent").on("click",function(e) {
  if(!e.target.classList.contains('parent')) {
     return console.log('no event')
}
  console.log('fire event')
});
```

<p>This is called event delegation, and you pretty much do this already. Here I am checking if the element, I am clicking on, is indeed of class parent, only then I fire my event.</p>

<p>You can of course do all sorts of checks, for example only the <code><li></code> elements.</p>

```$(".parent").on("click", (e) => e.target.tagName == 'LI' && console.log('fire event'))
```

Here check out this example https://codepen.io/bluebrown/pen/xxGVgYd?editors=1111

I would recommend doing a web search for event delegation and event bubbling.

Title: Getting click event from parent container except certain children

Body:
It is true what Phong is saying and that works. However, imagine now you had many child elements in your parent all matching that selector. With something like below, you would add an event listener to each of those elements.

$(".info, .item-image").on("click", function(){
  console.log("Trigger");
});

While with your first approach you were already very close to only have one listener, no matter how many child elements are in the parent.

Consider following example:

  <ul class='parent'>
    <li>No</li>
    <li>Click</li>
    <li>Event</li>
  </ul>

$(".parent").on("click",function(e) {
  if(!e.target.classList.contains('parent')) {
     return console.log('no event')
}
  console.log('fire event')
});

This is called event delegation, and you pretty much do this already. Here I am checking if the element, I am clicking on, is indeed of class parent, only then I fire my event.

You can of course do all sorts of checks, for example only the <li> elements.

$(".parent").on("click", (e) => e.target.tagName == 'LI' && console.log('fire event'))

Here check out this example https://codepen.io/bluebrown/pen/xxGVgYd?editors=1111

I would recommend doing a web search for event delegation and event bubbling.


问:
Android ViewPager get the current View
I have a ViewPager, and I'd like to get the current selected and visible view, not a position.

getChildAt(getCurrentItem) returns wrong View

This works not all the time. Sometimes returns null, sometimes just returns wrong View.

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser == true) {
        mFocusedListView = ListView;
    }
}
</code>```

PageListener on ViewPager with getChildAt() also not working, not giving me the correct View every time.

How can i get current visible View?

```<code>View view = MyActivity.mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()).getRootView();
ListView listview = (ListView) view.findViewById(R.id.ListViewItems);
</code>```

答:
```<code>viewpager.getChildAt(0)
</code>```

this always returns my currently selected view. this worked for me.

ContentLicense: CC BY-SA 3.0

Title: Android ViewPager get the current View

Body:
I have a ViewPager, and I'd like to get the current selected and visible view, not a position.

getChildAt(getCurrentItem) returns wrong View

This works not all the time. Sometimes returns null, sometimes just returns wrong View.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser == true) {
        mFocusedListView = ListView;
    }
}

PageListener on ViewPager with getChildAt() also not working, not giving me the correct View every time.

How can i get current visible View?

View view = MyActivity.mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()).getRootView();
ListView listview = (ListView) view.findViewById(R.id.ListViewItems);

Body:
viewpager.getChildAt(0)

this always returns my currently selected view. this worked for me.


问:
Rails 6 infinite scrolling Uncaught ReferenceError: InfiniteScroll is not defined
I'm adding infinite-scrolling to my app, when scrolling to the end of the page, the library infinite-scroll automatically fetch data and append in the page.

I'm using this library from metafizzy:
https://infinite-scroll.com/

Rails 6 app using webpacker to compile js files, libs. I'm installing infinite-scroll in this order:

```<code>yarn add infinite-scroll
</code>```

In app/javascript/packs/application.js:

require("infinite-scroll");

var elem = document.querySelector(".container");
var infScroll = new InfiniteScroll(elem, {
  // options
  path: ".pagination__next",
  append: ".post",
  history: false
});
```

<p>However, on running app I got this error:</p>

```application.js:21 Uncaught ReferenceError: InfiniteScroll is not defined
    at Object../app/javascript/packs/application.js (application.js:21)
    at __webpack_require__ (bootstrap:19)
    at Object.0 (log.js:56)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83
```

Here is a sample project:
https://github.com/truongnmt/rails-6-infinite-scroll-sample

答:
use this

```<code>var InfiniteScroll = require('infinite-scroll');

var infScroll = new InfiniteScroll('.container', {
  // options
  path: ".pagination__next",
  append: ".post",
  history: false
});
</code>```

docs

Body:
I'm adding infinite-scrolling to my app, when scrolling to the end of the page, the library infinite-scroll automatically fetch data and append in the page.

I'm using this library from metafizzy:
https://infinite-scroll.com/

Rails 6 app using webpacker to compile js files, libs. I'm installing infinite-scroll in this order:

yarn add infinite-scroll

In app/javascript/packs/application.js:

require("infinite-scroll");

var elem = document.querySelector(".container");
var infScroll = new InfiniteScroll(elem, {
  // options
  path: ".pagination__next",
  append: ".post",
  history: false
});

However, on running app I got this error:

application.js:21 Uncaught ReferenceError: InfiniteScroll is not defined
    at Object../app/javascript/packs/application.js (application.js:21)
    at __webpack_require__ (bootstrap:19)
    at Object.0 (log.js:56)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

Here is a sample project:
https://github.com/truongnmt/rails-6-infinite-scroll-sample

Body:
use this

var InfiniteScroll = require('infinite-scroll');

var infScroll = new InfiniteScroll('.container', {
  // options
  path: ".pagination__next",
  append: ".post",
  history: false
});

docs


问:
Why does my TCP/IP Socket receive inconsistent amounts of data per read?
I am on working a project with Socket TCP/IP ( Server-C# and Client-Python).
Streaming video after sometimes,the data of Recv Socket is splitted.
My data is buff = 22000 bytes,if it is splitted it will become :

```<code>buff = 1460
</code>```

```<code>buff = 20600
</code>```

I don't know why,i have researched some methods with MTU,Fragmentation,Windows Size,....but not have result
Specially,if i setsocketopt the process will appear less.

```<code>self.sk.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1048576)
</code>```

enter image description here --Image about the data is splitted

This is my Recv Socket.

```<code>buff = self.sk.recv(1048576)
print("BUFF RECEIVE  :::  ::::: ---->>>>>      ",len(buff))
if buff == b'' :
  self.sk=None
  buff = None
  return buff
</code>```

Suggestions: This just only happened to Chrome Browser(It mean,can't Streaming Video if loss data ).But at Firefox,it is not.It seem to blink a moment if loss data but It can continue stream after.
enter image description here - Chrome and FireFox

答:
After a long time,I have found the answer for my issue.

Solution for TCP/IP client socket message boundary problem

**1/**When you send a package from Server to Client with Send(Write).At Client side,the Receive will not get full data in sometimes.It not mean,Send/write at Server not send enough data.Just because this is TCP/IP protocol,Receive is not graduatee and the package will be fragmentation at Client Side ( your code ).

**2/**You can solve this issue by add more pattern at send/write Server Side. For example, send(data) --> send ( Pattern + data) and at Client side,you can use patern to check data.

**3/**Limitations of this method,the package after fragmentation,it can "combine together" or sometime it can't not.For example,your send data = 4000 and at Client side,your receive = 1460 + 2540.
This is what I understood with my issue.

Body:
I am on working a project with Socket TCP/IP ( Server-C# and Client-Python).
Streaming video after sometimes,the data of Recv Socket is splitted.
My data is buff = 22000 bytes,if it is splitted it will become :

buff = 1460

buff = 20600

I don't know why,i have researched some methods with MTU,Fragmentation,Windows Size,....but not have result
Specially,if i setsocketopt the process will appear less.

self.sk.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1048576)

enter image description here --Image about the data is splitted

This is my Recv Socket.

buff = self.sk.recv(1048576)
print("BUFF RECEIVE  :::  ::::: ---->>>>>      ",len(buff))
if buff == b'' :
  self.sk=None
  buff = None
  return buff

Suggestions: This just only happened to Chrome Browser(It mean,can't Streaming Video if loss data ).But at Firefox,it is not.It seem to blink a moment if loss data but It can continue stream after.
enter image description here - Chrome and FireFox


问:
Uniformly randomly sample binary strings of length N when N is large
I wish to generate a random binary string of length N such that each of the possible 2^N strings is uniformly randomly chosen. Note that choosing 1 or 0 with equal probability to build a string doesn't work because with high probability the string contains equal numbers of 0s and 1s, and so such strings are generated with higher probability. Another way is to generate the list of all 2^N strings and then choose one of them. However, this quickly becomes impractical when N is even 30. I need to work with N = 500. How can I achieve this? If python has an in-built function for such thing, it would be even better.

Edit
Clearly I posed a wrong question; apologies. What I wanted was a uniform distribution over the number of 1s in the string. So the string with just two 1s should be as probable as the string with all 1s. I could achieve this though.

答:
You've misunderstood how the probabilities work. Picking each bit uniformly at random produces exactly the desired distribution.

It's true that this will tend to generate strings with roughly equal numbers of 0s and 1s, but that's exactly what it should do, because most possible bitstrings have close to equal numbers of 0s and 1s. Each individual possible bitstring still has a 1/2^N probability of being selected.

(That doesn't mean you should implement this by manually picking bits one at a time with random.choice, though. That'd be slow. Something like '{:0{}b}'.format(random.getrandbits(N), N) would be faster.)


问:
How can I see which sqlite3 binary does the sqlite3 Python module use on Ubuntu 16.04?
How can I see which sqlite3 binary (containing the SQLite relational database management system) does the sqlite3 Python module use on Ubuntu 16.04?

I unsuccessfully looked at /usr/lib/python3.7/sqlite3 and https://docs.python.org/3/library/sqlite3.html. I use Python 3.7.

The output of

```<code>python -c "import sqlite3; print(sqlite3.__file__)"
</code>```

is /usr/lib/python3.7/sqlite3/__init__.py

答:
It's not going to use the sqlite3 executable directly if that's what you're thinking. It's going to be linked to the sqlite3 dynamic library installed on your system.  To find out which particularly library it's linked to, use ldd on the _sqlite3 python c extension.  The _sqlite3 module is the underlying interface that the sqlite3 module relies on.</p>

```
$ <b>ldd `find /usr/lib/python3.7/ -name '_sqlite3*'` | grep sqlite</b>
    libsqlite3.so.0 => /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 (0x00007f47705a2000)
```

Body:
How can I see which sqlite3 binary (containing the SQLite relational database management system) does the sqlite3 Python module use on Ubuntu 16.04?

I unsuccessfully looked at /usr/lib/python3.7/sqlite3 and https://docs.python.org/3/library/sqlite3.html. I use Python 3.7.

The output of

python -c "import sqlite3; print(sqlite3.__file__)"

is /usr/lib/python3.7/sqlite3/__init__.py

Body:
It's not going to use the sqlite3 executable directly if that's what you're thinking. It's going to be linked to the sqlite3 dynamic library installed on your system.  To find out which particularly library it's linked to, use ldd on the _sqlite3 python c extension.  The _sqlite3 module is the underlying interface that the sqlite3 module relies on.

$ ldd `find /usr/lib/python3.7/ -name '_sqlite3*'` | grep sqlite
    libsqlite3.so.0 => /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 (0x00007f47705a2000)


问:
Xamarian Webview only https sites working not http sites
How to make http  web sites work in xamarian webview.
its working only  when i use https sites

eg:
    http://www.google.com  // Not working

```<code>https://www.google.com  // working
</code>```

答:
//definition for WebViewClientAuthentication

```<code>public class WebViewClientAuthentication : WebViewClient
{
    public override void OnReceivedSslError(WebView view, SslErrorHandler handler, Android.Net.Http.SslError error)
    {
        handler.Proceed();
    }
}
</code>```

this will ignore the ssl error & it works

Found answer from the below link

Monodroid WebView Loading SSL page

Body:
How to make http  web sites work in xamarian webview.
its working only  when i use https sites

eg:
    http://www.google.com  // Not working

https://www.google.com  // working

Body:
//definition for WebViewClientAuthentication

public class WebViewClientAuthentication : WebViewClient
{
    public override void OnReceivedSslError(WebView view, SslErrorHandler handler, Android.Net.Http.SslError error)
    {
        handler.Proceed();
    }
}

this will ignore the ssl error & it works

Found answer from the below link

Monodroid WebView Loading SSL page


问:
Getting specific data from via facebook graph api
is there any possibility how to fetch any specific type of posts from facebook news feed via graph api?For example on my news feed I have statutuses, links, photos, vidoes, and so on..I only want to get the ones with type=status over graph api..I have seen some get parameters in documentation, but nothing like ?type=link..So I have tried /me/home?type=link, but unsurprisingly it have not worked:D

So does anyone know how to do that?I can filter it in my PHP app, but then I need to get some further data..When I got 20 posts and only 10 would be statuses, I need to add the 10 remaiming? It is too possible, but I dont know how to do that:D

Please help..!Thanks!

答:
Hey Sima, I understand exactly what you are talking about.

There is no way in Graph to do what you want (at least that I have found).  I do exactly what you want using FQL and filters.  You can filter the feed by photos, videos, a few other options.

1) query the filter_stream table to get list of filters.

```<code>SELECT name,filter_key FROM stream_filter WHERE uid=me()
</code>```

2) Filter the feed.

```<code>SELECT xxx FROM stream WHERE filter_key='app_xxxx'
</code>```

Reference: http://developers.facebook.com/docs/reference/fql/

Body:
Hey Sima, I understand exactly what you are talking about.

There is no way in Graph to do what you want (at least that I have found).  I do exactly what you want using FQL and filters.  You can filter the feed by photos, videos, a few other options.

1) query the filter_stream table to get list of filters.

SELECT name,filter_key FROM stream_filter WHERE uid=me()

2) Filter the feed.

SELECT xxx FROM stream WHERE filter_key='app_xxxx'

Reference: http://developers.facebook.com/docs/reference/fql/


问:
why i get the index of tag not index of class
when I'm use .index() in click function on element class i get the index of tag not the index of class.
here when i click element have class .mobapp-right i get (1 and 4) not (0 and 1).

$(document).ready(function(){
   $('.mobapp-right').click(function(){
        alert($(this).index());
    });
    $('.mobapp-left').click(function(){
        alert($(this).index());
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}</code>```

 right

 left

 right

 left
```

答:
You can achieve it by using .index(element).

 $('.mobapp-right').click(function(){
     var index = $(".mobapp-right").index(this);
     alert("index is: " + index);
    });

$('.mobapp-left').click(function(){
     var index = $(".mobapp-left").index(this);
     alert("index is: " + index);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}</code>```

 right

 left

 right

 left
```

Body:
when I'm use .index() in click function on element class i get the index of tag not the index of class.
here when i click element have class .mobapp-right i get (1 and 4) not (0 and 1).

$(document).ready(function(){
   $('.mobapp-right').click(function(){
        alert($(this).index());
    });
    $('.mobapp-left').click(function(){
        alert($(this).index());
    });
});

.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}

 right

 left

 right

 left

Body:
You can achieve it by using .index(element).

 $('.mobapp-right').click(function(){
     var index = $(".mobapp-right").index(this);
     alert("index is: " + index);
    });

$('.mobapp-left').click(function(){
     var index = $(".mobapp-left").index(this);
     alert("index is: " + index);
});

.mobapp-right{
    cursor: pointer;
}
.mobapp-left{
    cursor: pointer;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <ul >
        <li>  </li>
        <li></li>
        <li></li>
        <li>  </li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>
    <ul >
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <h1 class="mobapp-right"> right </h1>
    <h1 class="mobapp-left"> left </h1>


问:
How to write LaTeX in IPython Notebook?
How can I display LaTeX code in a IPython Notebook?</p>

答:
I wrote how to write LaTeX in Jupyter Notebook in this article.

You need to enclose them in dollar($) signs.

To align to the left use a single dollar($) sign.

$P(A)=\frac{n(A)}{n(U)}$

To align to the center use double dollar($$) signs.

$$P(A)=\frac{n(A)}{n(U)}$$

Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.

Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.

Try this one.

```<code>$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i  $$
</code>```

Matrices

Piecewise functions

```<code>$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$
</code>```

The above code will create this.

If you want to know how to add numbering to equations and align equations, please read this article for details.

Title: How to write LaTeX in IPython Notebook?

Body:
I wrote how to write LaTeX in Jupyter Notebook in this article.

You need to enclose them in dollar($) signs.

To align to the left use a single dollar($) sign.

$P(A)=\frac{n(A)}{n(U)}$

To align to the center use double dollar($$) signs.

$$P(A)=\frac{n(A)}{n(U)}$$

Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.

Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.

Try this one.

$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i  $$

Matrices

Piecewise functions

$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$

The above code will create this.

If you want to know how to add numbering to equations and align equations, please read this article for details.


问:
sumproduct if a cell contains a certain value, give all results otherwise just the specified result
My issue is that I need to reference a cell (A1) which will either be the name of a state that can be found in column L, or it can be "All States" which I then want to include all results of column L. I can't work out how to include this.

```<code>=SUMPRODUCT(--(IF(A1="All States",Data!$L:$L,Data!$L:$L=A1)),Data!Q:Q)
</code>```

I want to add a bunch more criteria based on the above so I don’t want to go down the route of imbedding the sumproduct in an if function because the formula will quickly become too unweildy.

答:
You have a lot of choices.  Using your initial formula I would tweak it to

```<code>(A)  =SUMPRODUCT((IF($A$1="All States",1,($L$2:$L$11=$A$1)))*($Q$2:$Q$11))
</code>```

But this would need to be entered as an array formula so instead of just confirming with ENTER, you need CONTROL+SHIFT+ENTER.  You will know you have done it right when { } show up around your formula.  Note that they cannot be added manually.

A non array type formula which would be faster I believe would be to look at your two options.  You are either dealing with a single state or all states.  Set up an IF check to determine if you need to sum all of column Q, or if you need to find a single value from column Q.  I used the following formula:

```<code>(B)  =IF(A1="all states",SUM($Q$2:$Q$11),INDEX($Q$2:$Q$11,MATCH($A$1,$L$2:$L$11,0)))
</code>```

A bit of a cheat but but simplifies things, is to add a final state to the bottom of your list in L and call is "All States".  In the corresponding row in Q place =sum(First Cell:Last Cell).  If you do that then you can use the following formula:

```<code>(C)  =SUMPRODUCT(($L$2:$L$12=$A$1)*($Q$2:$Q$12))
</code>```

That are other options out there as well, just thought I would show some options.

Body:
My issue is that I need to reference a cell (A1) which will either be the name of a state that can be found in column L, or it can be "All States" which I then want to include all results of column L. I can't work out how to include this.

=SUMPRODUCT(--(IF(A1="All States",Data!$L:$L,Data!$L:$L=A1)),Data!Q:Q)

I want to add a bunch more criteria based on the above so I don’t want to go down the route of imbedding the sumproduct in an if function because the formula will quickly become too unweildy.

Body:
You have a lot of choices.  Using your initial formula I would tweak it to

(A)  =SUMPRODUCT((IF($A$1="All States",1,($L$2:$L$11=$A$1)))*($Q$2:$Q$11))

But this would need to be entered as an array formula so instead of just confirming with ENTER, you need CONTROL+SHIFT+ENTER.  You will know you have done it right when { } show up around your formula.  Note that they cannot be added manually.

A non array type formula which would be faster I believe would be to look at your two options.  You are either dealing with a single state or all states.  Set up an IF check to determine if you need to sum all of column Q, or if you need to find a single value from column Q.  I used the following formula:

(B)  =IF(A1="all states",SUM($Q$2:$Q$11),INDEX($Q$2:$Q$11,MATCH($A$1,$L$2:$L$11,0)))

A bit of a cheat but but simplifies things, is to add a final state to the bottom of your list in L and call is "All States".  In the corresponding row in Q place =sum(First Cell:Last Cell).  If you do that then you can use the following formula:

(C)  =SUMPRODUCT(($L$2:$L$12=$A$1)*($Q$2:$Q$12))

That are other options out there as well, just thought I would show some options.


问:
Create x509 certificate with openssl/makecert tool
I'm creating a x509 certificate using makecert with the following parameters:

makecert -r -pe -n "CN=Client" -ss MyApp

I want to use this certificate to encrypt and decrypt data with RSA algoritm.
I look to generated certificate in windows certificate store and everything seems ok (It has a private key, public key is a RSA key with 1024 bits and so on..)

Now i use this C# code to encrypt data:

```<code>X509Store store = new X509Store("MyApp", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Client", false);
X509Certificate2 _x509 = certs[0];

using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_x509.PublicKey.Key)
{
    byte[] dataToEncrypt = Encoding.UTF8.GetBytes("hello");
    _encryptedData = rsa.Encrypt(dataToEncrypt, true);
}
</code>```

When executing the Encrypt method, i receive a CryptographicException with message "Bad key".

I think the code is fine. Probably i'm not creating the certificate properly.
Any comments?
Thanks

---------------- EDIT --------------

If anyone know how to create the certificate using OpenSsl, its also a valid answer for me.

答:
This was another page I stumbled across when I was trying to find examples of makcert usage with x509 certificates and rsa using c#, and unfortunately it only provided part of the solution. I put all the bits together in a blog entry that people might be interested in, and it can be found here:
http://nick-howard.blogspot.com/2011/05/makecert-x509-certificates-and-rsa.html</p>

Body:
I'm creating a x509 certificate using makecert with the following parameters:

makecert -r -pe -n "CN=Client" -ss MyApp

I want to use this certificate to encrypt and decrypt data with RSA algoritm.
I look to generated certificate in windows certificate store and everything seems ok (It has a private key, public key is a RSA key with 1024 bits and so on..)

Now i use this C# code to encrypt data:

X509Store store = new X509Store("MyApp", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Client", false);
X509Certificate2 _x509 = certs[0];

using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_x509.PublicKey.Key)
{
    byte[] dataToEncrypt = Encoding.UTF8.GetBytes("hello");
    _encryptedData = rsa.Encrypt(dataToEncrypt, true);
}

When executing the Encrypt method, i receive a CryptographicException with message "Bad key".

I think the code is fine. Probably i'm not creating the certificate properly.
Any comments?
Thanks

---------------- EDIT --------------

If anyone know how to create the certificate using OpenSsl, its also a valid answer for me.


问:
PropertyBuilder<T> Does Not Contain A Definition For HasColumnType
I just built up a bunch of POCO classes and a DbContext class utilizing EntityFramework Core and the Scaffold-DbContext NuGet Package Manager Console command.

It generated a bunch of code and most of it is fine, except there are several calls to HasColumnType and HasName methods that are not found by the compiler. Unfortunately, VS2017 isn't helping me locate them either. I installed EntityFramework Core via the NuGet Package Manager and I figured all dependencies would've been correctly installed, but this does not appear to be the case. I've tried googling the namespace for HasColumnType but have been unable to find it.

Could someone please tell me what namespace or NuGet package I'm missing?

答:
I also had the same question. As per this Microsoft docs link https://learn.microsoft.com/en-us/ef/core/providers/ you would need to add a specific database provider nuget package, such as Microsoft.EntityFrameworkCore.SqlServer.

EF Core providers for relational databases are build on the common Microsoft.EntityFrameworkCore.Relational library, which provides APIs for configuring table and column mappings, foreign key constraints, etc. Providers are usually distributed as NuGet packages.

So no need to add both packages, adding the more specific one Microsoft.EntityFrameworkCore.SqlServer worked for me.


问:
How to get URL of page in .net Core Partial View?
Is there a way to get the URL of the page inside a partial view without passing it in as part of the model?

Request.Path.Value gets me the URL, but how do we get the Request object?

答:
I found an object called Context from which I can grab it.

This link helped

thanks @Peter


问:
Get parent element of nested child by class or name
I have html elements like follows with unknown hierarchy:

          Nested Child 1

```

<pre class="lang-html prettyprint-override"><code><div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
</code>```

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

答:
you should loop "parent()" function jquery.

function get_parent(a){
  $(a).parent().parent();
  console.log("test",$(a).parent().parent());
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
<script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script></code>```

Body:
I have html elements like follows with unknown hierarchy:

          Nested Child 1

      Nested Child 2

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

Body:
you should loop "parent()" function jquery.

function get_parent(a){
  $(a).parent().parent();
  console.log("test",$(a).parent().parent());
}

<div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
<script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>


问:
How do I limit the number of times a block is called?
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

```<code>str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"
</code>```

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)

答:
How about just extracting the replacement as an argument and encapsulating the counter by having the block close over it inside a method?

```<code>str = "aaaaaaaaaaaaaaa"

def replacements(replacement, limit)
    count = limit
    lambda { |original| if count.zero? then original else count -= 1; replacement end }
end

p str.gsub(/a/, &replacements("x", 5))
</code>```

You can make it even more general by using a block for the replacement:

```<code>def limit(n, &block)
    count = n
    lambda do |original|
        if count.zero? then original else count -= 1; block.call(original) end
    end
end
</code>```

Now you can do stuff like

```<code>p str.gsub(/a/, &limit(5) { "x" })
p str.gsub(/a/, &limit(5, &:upcase))
</code>```

Body:
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)

Body:
How about just extracting the replacement as an argument and encapsulating the counter by having the block close over it inside a method?

str = "aaaaaaaaaaaaaaa"

def replacements(replacement, limit)
    count = limit
    lambda { |original| if count.zero? then original else count -= 1; replacement end }
end

p str.gsub(/a/, &replacements("x", 5))

You can make it even more general by using a block for the replacement:

def limit(n, &block)
    count = n
    lambda do |original|
        if count.zero? then original else count -= 1; block.call(original) end
    end
end

Now you can do stuff like

p str.gsub(/a/, &limit(5) { "x" })
p str.gsub(/a/, &limit(5, &:upcase))


问:
Can't style Fancybox modal
I'm having problems styling a modal I've set to open with fancy box. The content for the modal/div shows up after clicking with no issues but it seems all the styling I applied to that modal div refuses to show up.

.hidden{
display:none;
}

.red{
background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
</head>

<body>
  <div>
     Open modal  box
  </div>

  <div class="hidden">
     <div class="red" id="open">
          <h2>Hello</h2>
          <p>You are awesome.</p>
       </div>
   </div>

</body>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
</html></code>```

Here is my setup on Codepen

答:
If your common selectors can't able to apply styles then try to select elements more specifically.

IDs are Higher specific because they are unique.

Class names are specific too but they are used in other stylesheets also

Tag names are not most specific because they can found anywhere in page

And * selector has lowest specificity in css

```<code>div.red{background: red;} // Selects divs that have 'red' classname
</code>```

.hidden{
display:none;
}

div.red{
background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
</head>

<body>
  <div>
     Open modal  box
  </div>

  <div class="hidden">
     <div class="red" id="open">
          <h2>Hello</h2>
          <p>You are awesome.</p>
       </div>
   </div>

</body>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
</html></code>```

Title: Can't style Fancybox modal

Body:
I'm having problems styling a modal I've set to open with fancy box. The content for the modal/div shows up after clicking with no issues but it seems all the styling I applied to that modal div refuses to show up.

.hidden{
display:none;
}

.red{
background: red;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">

     Open modal  box

Hello

You are awesome.

Here is my setup on Codepen

Body:
If your common selectors can't able to apply styles then try to select elements more specifically.

IDs are Higher specific because they are unique.

Class names are specific too but they are used in other stylesheets also

Tag names are not most specific because they can found anywhere in page

And * selector has lowest specificity in css

div.red{background: red;} // Selects divs that have 'red' classname

.hidden{
display:none;
}

div.red{
background: red;
}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
</head>

<body>
  <div>
     <a data-fancybox data-src="#open" href="javascript:;">Open modal  box</a>
  </div>

  <div class="hidden">
     <div class="red" id="open">
          <h2>Hello</h2>
          <p>You are awesome.</p>
       </div>
   </div>

</body>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
</html>