问:
Null Calculation With SQL Select Statement
I have Following Table

```<code>Input           Output
---------------------------------
12.22
                2.22
</code>```

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

```<code>Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL
</code>```

If I wants The Output Like Below:

```<code>Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00
</code>```

Than What is SQL Transact Statement?

My Table Structure is as Below:

```<code>companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal
</code>```

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.

答:
```<code>Select Input,
       Output,
       @runbal:=@runbal+SUM(COALESCE(Input, 0) - COALESCE(Output, 0)) AS Balance
from (select @runbal:=0) rt,Stock
group by Input,Output
</code>```

Body:
I have Following Table

Input           Output
---------------------------------
12.22
                2.22

If I pass Following Sql Statement:

Select Input,Output,Balance=sum(Input - Output) from Stock group by input,output

So The Output is:

Input            Output       Balance
--------------------------------------
12.22            NULL         NULL
NULL             2.22         NULL

If I wants The Output Like Below:

Input            Output       Balance
--------------------------------------
12.22                         12.22
                 2.22         10.00

Than What is SQL Transact Statement?

My Table Structure is as Below:

companyID   int
transID     int    -- Primary Key (Auto Increment)
Date        datetime
particulars varchar
input       decimal
output      decimal

Note:- I have applied here Group By function on input and Output columns which doesn't make diference as there is transID columns which is autoincrement hence it should be display all the rows of the table.


来源: stackexchange

问:
JQuery if both conditions are true perform action
I have the following code which executes on mobile screens, but the problem is it also executes on large screens.
Can this be change to execute only if both conditions are true?

Thanks

```<code>$(window).scroll(function(){

        var ww = $(window).width();
        var sc = $(window).scrollTop();

        if (ww < 769 && sc > 100){
            $('header').addClass('fixed-header');
            $('.page-sidebar').css('top', 65);
        } else {
            $('header').removeClass('fixed-header');
            $('.page-sidebar').css('top', 115);
        }

    });
</code>```

答:
```<code>if($(window).width() < 769){
        $(window).scroll(function(){

            var ww = $(window).width();
            var sc = $(window).scrollTop();

            if (ww < 769 && sc > 100){
                $('header').addClass('fixed-header');
                $('.page-sidebar').css('top', 65);
            } else {
                $('header').removeClass('fixed-header');
                $('.page-sidebar').css('top', 115);
            }

        });
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code which executes on mobile screens, but the problem is it also executes on large screens.
Can this be change to execute only if both conditions are true?

Thanks

$(window).scroll(function(){

        var ww = $(window).width();
        var sc = $(window).scrollTop();

        if (ww < 769 && sc > 100){
            $('header').addClass('fixed-header');
            $('.page-sidebar').css('top', 65);
        } else {
            $('header').removeClass('fixed-header');
            $('.page-sidebar').css('top', 115);
        }

    });


问:
Change div display depending on a select in jQuery
I have this dropdown:

```<code><select>
    <option value='CAD'>CAD</option>
    <option value='USD'>USD</option>
    <option value='MXN'>MXN</option>
</select>

<div id="currency-alert" class="hide">My alert message</div>
</code>```

I want to have the possibility to show t div depending the user selection.

So I used:

```<code>if(currency != 'CAD') {
    $('#currency-alert').toggleClass('show', 'hide');
}else{
    $('#currency-alert').toggleClass('hide', 'show');
}
</code>```

Problem is, when I select USD and after MXN, the box desaperes.

How can I change this please ?

The box should display only for USD and MXN but not for CAD.

Thanks.

答:
If you want to show the div only for CAD the just use show to show it and hide when the other currency is selected.

```<code>if(currency != 'CAD') {
    $('#currency-alert').show();
}else{
    $('#currency-alert').hide();
}
</code>```

If you don't want to show it at start up you can initialize it with display:none

Body:
I have this dropdown:

<select>
    <option value='CAD'>CAD</option>
    <option value='USD'>USD</option>
    <option value='MXN'>MXN</option>
</select>

My alert message

I want to have the possibility to show t div depending the user selection.

So I used:

if(currency != 'CAD') {
    $('#currency-alert').toggleClass('show', 'hide');
}else{
    $('#currency-alert').toggleClass('hide', 'show');
}

Problem is, when I select USD and after MXN, the box desaperes.

How can I change this please ?

The box should display only for USD and MXN but not for CAD.

Thanks.

Body:
If you want to show the div only for CAD the just use show to show it and hide when the other currency is selected.

if(currency != 'CAD') {
    $('#currency-alert').show();
}else{
    $('#currency-alert').hide();
}

If you don't want to show it at start up you can initialize it with display:none


问:
Dropdownlist value always returns zero in asp.net mvc
This is the sample of the model class

```<code>[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public int SelectedValue { get; set; }

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public List<Department> RoleList { get; set; }
</code>```

This is the view

```<code><div class="col-md-10">
    @Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
    @Html.ValidationMessageFor(model => model.SelectedValue, "",new { @class = "text-danger"})
</div>
</code>```

The list is populated perfectly from the database. Now when i select the item on the list, the select value has to be sent to the controller

```<code>public async Task<ActionResult> Register(RegisterViewModel model)
{
    int Selectedvalue = model.SelectedValue;
    if (ModelState.IsValid && (model.SelectedValue).ToString() != "0")
    {
</code>```

Here i have made a selection

Error

答:
You should change it

```<code>@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
</code>```

To

```<code>@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
</code>```

The first parameter of the DropDownListFor should be selected value in model. In your case, this property is Model.SelectedValue not Model.RoleList.

Body:
This is the sample of the model class

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public int SelectedValue { get; set; }

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public List<Department> RoleList { get; set; }

This is the view

    @Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
    @Html.ValidationMessageFor(model => model.SelectedValue, "",new { @class = "text-danger"})

The list is populated perfectly from the database. Now when i select the item on the list, the select value has to be sent to the controller

public async Task<ActionResult> Register(RegisterViewModel model)
{
    int Selectedvalue = model.SelectedValue;
    if (ModelState.IsValid && (model.SelectedValue).ToString() != "0")
    {

Here i have made a selection

Error

Body:
You should change it

@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

To

@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

The first parameter of the DropDownListFor should be selected value in model. In your case, this property is Model.SelectedValue not Model.RoleList.


问:
Highcharts heatmap logarithmic colorAxis fails when 0
I'm trying to implement a heatmap in highcharts with a logarithmic colorAxis, however, I keep getting highcharts error #10 (can't plot zero or subzero values on a logarithmic axis).

As I'm trying to apply the logarithmic property to the color axis and not the actual axis themselves, I believe my problem is caused by some of my bins having a frequency of zero (A heatmap colors by the frequency in each bin).

How can I get around this? Can I create a default function so that when a frequency is zero it assigns that bin a default color? I can't find any solutions in the docs.

Currently, my colorAxis object looks like this

```<code>colorAxis: {
  type: 'logarithmic',
  minColor: '#EEEEFF',
  maxColor: '#000022',
  stops: [
    [0, '#EFEFFF'],
    [0.67, '#4444FF'],
    [1, '#000022']
  ]
}
</code>```

答: My solution was to iterate through my data and change all the zeros to an extremely small number then set a min property on the colorAxis so the extremely small numbers would not interfere with the color scheme. This is obviously not the best solution because if the third dimension was measuring something other than frequency and this other thing could be a fraction less than 1 then the extremely small value could overlay with actual data and throw off the color scheme. Hopefully someone comes along and provides a better solution, but for now this is all the insight I have to give.

Body:
I'm trying to implement a heatmap in highcharts with a logarithmic colorAxis, however, I keep getting highcharts error #10 (can't plot zero or subzero values on a logarithmic axis).

As I'm trying to apply the logarithmic property to the color axis and not the actual axis themselves, I believe my problem is caused by some of my bins having a frequency of zero (A heatmap colors by the frequency in each bin).

How can I get around this? Can I create a default function so that when a frequency is zero it assigns that bin a default color? I can't find any solutions in the docs.

Currently, my colorAxis object looks like this

colorAxis: {
  type: 'logarithmic',
  minColor: '#EEEEFF',
  maxColor: '#000022',
  stops: [
    [0, '#EFEFFF'],
    [0.67, '#4444FF'],
    [1, '#000022']
  ]
}


问:
How to make a field required for customers but not for administrators in prestashop?
I made a custom field in prestashop.

I would like to know if there is some way to make this field only required on the frontend and not for administrators.

this is my code in Customer class

```<code>array('type' => self::TYPE_STRING,  'required' => true, 'size' => 64),
</code>```

Thanks in advance

答:
Can't think of a quick way to make this possible exactly as you want it, so here are two suggestions:

1 - Remove the 'required' => true from the definition and create some kind of custom validation like if (Tools::getValue('type ') == "") { return false; } in an override of the front office AuthController (Warning: code is completely untested and should definitely be improved, also according to your particular PS version).

2 - Use frontend validation by giving the frontend form field the required attribute (you should do this even if oyu use 1)

Body:
I made a custom field in prestashop.

I would like to know if there is some way to make this field only required on the frontend and not for administrators.

this is my code in Customer class

array('type' => self::TYPE_STRING,  'required' => true, 'size' => 64),

Thanks in advance


问:
Can't generate migration in phoenix
I've started to learn phoenix framework and having some troubles when trying to create my migration, here is my schema :

```<code>defmodule Lclp.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Lclp.User

  schema "users" do
    field :email, :string
    field :name, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :username, :string

    timestamps()
  end
</code>```

When i run the migration generator this output me something like this :

```<code>defmodule Lclp.Repo.Migrations.UserAdd do
  use Ecto.Migration

  def change do

  end
end
</code>```

The change function is empty when it should be something like :

```<code>    def change do
    create table(:users) do
      add :name, :string
      add :username, :string
      add :email, :string
      add :password, :string
      add :password_hash, :string

      timestamps()
    end
   end
</code>```

My User schema is in the main folder with repo.ex as you can see here :

Does anyone have an idea why the generator generate an empty migration ?

答: You will want to look at phx.gen.schema instead. ecto.gen.migration does not look at your code to attempt to build an actual migration for you. It just generates the scaffold file.

Title: Can't generate migration in phoenix

Body:
I've started to learn phoenix framework and having some troubles when trying to create my migration, here is my schema :

defmodule Lclp.User do
  use Ecto.Schema
  import Ecto.Changeset
  alias Lclp.User

  schema "users" do
    field :email, :string
    field :name, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    field :username, :string

    timestamps()
  end

When i run the migration generator this output me something like this :

defmodule Lclp.Repo.Migrations.UserAdd do
  use Ecto.Migration

  def change do

  end
end

The change function is empty when it should be something like :

    def change do
    create table(:users) do
      add :name, :string
      add :username, :string
      add :email, :string
      add :password, :string
      add :password_hash, :string

      timestamps()
    end
   end

My User schema is in the main folder with repo.ex as you can see here :

Does anyone have an idea why the generator generate an empty migration ?


问:
Subquery returned more than 1 value.4...Different query
Hello I have this query that i am trying to execute and i keep getting this error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.", Kindly help please.</p>

```<code>DECLARE @NUMCOUNT BIT

Select @NUMCOUNT = (SELECT
CASE WHEN

(SELECT COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ('A')
       ) IN
(SELECT   COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C') ) THEN 1 else  0 END AS NUMCOUNT1
       FROM         R5REQUISLINES JOIN
                      R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE

       GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS

 )

IF @NUMCOUNT = '1'

begin

UPDATE R5REQUISITIONS

SET R5REQUISITIONS.REQ_STATUS = 'CP'

end
</code>```

答:
Ok, it sounds like what you actually want to do is update R5REQUISITIONS when there is no RQL_STATUS = 'C' in R5REQUISLINES, since you said you want to count the records where the RQL_STATUS is A and where it's A or C, and then do the update if the counts are the same.. You can greatly simplify this task with the following query:

```<code>UPDATE r5
SET r5.REQ_STATUS = 'CP'
FROM R5REQUISITIONS r5
WHERE NOT EXISTS (SELECT 1 FROM R5REQUISLINES r5q WHERE r5q.RQL_REQ = r5.REQ_CODE AND r5q.RQL_STATUS = 'C')
</code>```

Body:
Hello I have this query that i am trying to execute and i keep getting this error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.", Kindly help please.

DECLARE @NUMCOUNT BIT

Select @NUMCOUNT = (SELECT
CASE WHEN

(SELECT COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ('A')
       ) IN
(SELECT   COUNT(R5REQUISLINES.RQL_REQ)

       WHERE R5REQUISLINES.RQL_STATUS IN ( 'A','C') ) THEN 1 else  0 END AS NUMCOUNT1
       FROM         R5REQUISLINES JOIN
                      R5REQUISITIONS ON R5REQUISLINES.RQL_REQ = R5REQUISITIONS.REQ_CODE

       GROUP BY R5REQUISLINES.RQL_REQ, R5REQUISITIONS.REQ_CODE,R5REQUISLINES.RQL_STATUS

 )

IF @NUMCOUNT = '1'

begin

UPDATE R5REQUISITIONS

SET R5REQUISITIONS.REQ_STATUS = 'CP'

end

Body:
Ok, it sounds like what you actually want to do is update R5REQUISITIONS when there is no RQL_STATUS = 'C' in R5REQUISLINES, since you said you want to count the records where the RQL_STATUS is A and where it's A or C, and then do the update if the counts are the same.. You can greatly simplify this task with the following query:

UPDATE r5
SET r5.REQ_STATUS = 'CP'
FROM R5REQUISITIONS r5
WHERE NOT EXISTS (SELECT 1 FROM R5REQUISLINES r5q WHERE r5q.RQL_REQ = r5.REQ_CODE AND r5q.RQL_STATUS = 'C')


问:
How many times Database is hit in Spring DATA JPA's save(Iterable<S> entities)
I have the following lines of code:

```<code>@RequestMapping(value="/persons",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<List<Person>> saveUsers(@RequestBody List<Person> persons) {
        persons = (List<Person>) userRepository.save(persons);
        return new ResponseEntity<List<Person>>(persons, HttpStatus.OK);
}
</code>```

And here is the repository:

```<code>@Transactional
public interface UserRepository  extends UserBaseRepository<User> {
}

@NoRepositoryBean
public interface UserBaseRepository<T extends User> extends CrudRepository<T, Long> {
    public T findByEmail(String email);
}
</code>```

It runs fine. While running the code I see the following logs.

```<code>Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
</code>```

It seems that, the DataBase is hit 4 times. I have seen the implementation of save(iterable e) method, where the for loop is run to save each entity. So, my questions is:

is the DB hit 4 times ?

if so, then can it be done in 1 db hit (using Spring Data JPA) ? By doing so, will it give a performance boost in case of inserting a large number of records ?

答:
From the docs on Hibernate Batching:

Hibernate disables insert batching at the JDBC level transparently if
  you use an identity identifier generator.

So, if Person is using an Identity generator (as opposed to the Sequence generator or TABLE generator) batching won't take place. See this section for more details on why that is so.

Body:
I have the following lines of code:

@RequestMapping(value="/persons",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<List<Person>> saveUsers(@RequestBody List<Person> persons) {
        persons = (List<Person>) userRepository.save(persons);
        return new ResponseEntity<List<Person>>(persons, HttpStatus.OK);
}

And here is the repository:

@Transactional
public interface UserRepository  extends UserBaseRepository<User> {
}

@NoRepositoryBean
public interface UserBaseRepository<T extends User> extends CrudRepository<T, Long> {
    public T findByEmail(String email);
}

It runs fine. While running the code I see the following logs.

Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')
Hibernate: insert into user (email, firstname, lastname, user_type) values (?, ?, ?, 'Person')

It seems that, the DataBase is hit 4 times. I have seen the implementation of save(iterable e) method, where the for loop is run to save each entity. So, my questions is:

is the DB hit 4 times ?

if so, then can it be done in 1 db hit (using Spring Data JPA) ? By doing so, will it give a performance boost in case of inserting a large number of records ?


问:
Emit data using Observable between Shared Service and Component
Suppose I have a Service that I am sharing among a modal and a component. I want to do something like the following:

Click a button

Open modal

Fill input fields

Hit continue button on modal to confirm and close modal

Create network request using above input field values

How can I, in my component, wait for the user to click on the continue button from the modal before continuing to making the request?

I was thinking of creating an Observable from the Shared service that could emit the data once I clicked on the continue button. My component would then subscribe to this Observable and on success, continue on with the network request.

Here is some code:

```<code>this.modalService.open('custom-modal');

// The following should only happen after entering values in the appropriate input fields and clicking on the continue button

this.sharedService.getFormFields.subscribe(values => {
    this.httpService.post(values[0], values[1]);
});
</code>```

Is this the correct way of going about it? Any thoughts?

答:
I think that's an wrong way of approaching, at least sounds a bit over complicated to me.

My suggestion would be, you have a modal in the markup of the component. I would create an output event for when the user clicks the OK button in the pop up, and from there, I will emit an event that I will capture in the component. When I capture this, I will call my request with a normal service, receiving the values filled in through the same output event.

Sample:

Modal A:

```<code>@Output() clickEvt = new EventEmitter<MyModel>();

okButtonClicked(model: MyModel) {
   this.clickEvt.emit(model);
}

// This would be triggered once the click button has been pressed.
</code>```

Component A: (markup)

```<code><my-modal-component (clickEvt)="doRequest($event)"></...>
</code>```

ComponentB: (ts)

```<code>doRequest(model: MyModel) {
   this.myNormalService.doRequest(model).subscriber()...
}
</code>```

Body:
Suppose I have a Service that I am sharing among a modal and a component. I want to do something like the following:

Click a button

Open modal

Fill input fields

Hit continue button on modal to confirm and close modal

Create network request using above input field values

How can I, in my component, wait for the user to click on the continue button from the modal before continuing to making the request?

I was thinking of creating an Observable from the Shared service that could emit the data once I clicked on the continue button. My component would then subscribe to this Observable and on success, continue on with the network request.

Here is some code:

this.modalService.open('custom-modal');

// The following should only happen after entering values in the appropriate input fields and clicking on the continue button

this.sharedService.getFormFields.subscribe(values => {
    this.httpService.post(values[0], values[1]);
});

Is this the correct way of going about it? Any thoughts?

Body:
I think that's an wrong way of approaching, at least sounds a bit over complicated to me.

My suggestion would be, you have a modal in the markup of the component. I would create an output event for when the user clicks the OK button in the pop up, and from there, I will emit an event that I will capture in the component. When I capture this, I will call my request with a normal service, receiving the values filled in through the same output event.

Sample:

Modal A:

@Output() clickEvt = new EventEmitter<MyModel>();

okButtonClicked(model: MyModel) {
   this.clickEvt.emit(model);
}

// This would be triggered once the click button has been pressed.

Component A: (markup)

<my-modal-component (clickEvt)="doRequest($event)"></...>

ComponentB: (ts)

doRequest(model: MyModel) {
   this.myNormalService.doRequest(model).subscriber()...
}


问:
iPhone device vs. iPhone simulator
I have heard of apps not working properly on the simulator but working properly on the actual iPhone device.  Has anyone experienced an app that runs perfectly in the simulator but not on the actual iPhone device?</p>

答:
Also note that you will be compiling against the OS X frameworks (where applicable) when building for the simulator so you could be using methods and classes that aren't available on the iPhone versions of the frameworks.

One example I can think of off the top of my head is NSPredicate. I was able to compile and run an app using NSPredicate in the simulator, but it wouldn't compile for the device since that class isn't available.

ContentLicense: CC BY-SA 2.5

Title: iPhone device vs. iPhone simulator

OwnerDisplayName: Martin Gordon


问:
global initialize function and global constants in Python without using sys.path.append()
My use case is the following:

several scripts that can be run individually

one 'mother' script that can run all the scripts

each script has global variables it uses (paths to specific locations, constants used by all scripts)

some of these global variables are inputted in a settings.yaml file which gets dynamically loaded with yaml.load()

several people are running the system, we want to avoid environment variables or any kind of low-level path settings

The use cases were satisfied with an

```<code>import settings
</code>```

at the beginning of each export module.

The settings.py script is our 'initialize' script that loads and create variables used for all the modules, e.g.:

```<code>import os
import yaml
from utils import create_dir

input_f = open("settings.yml")
settings = yaml.load(input_f.read())
input_f.close()

TOHELLO = settings['TOHELLO']
TOBONJOUR = settings['TOBONJOUR']

#check for needed directories and create if necessary
create_dir(TOHELLO)
create_dir(TOBONJOUR)
</code>```

The 'mother module' export_all.py uses Subprocess.Popen() to run all the scripts sequentially.

Originally all files were in the root:

```<code>+--settings.py
+--settings.yml
+--export_foo1.py
+--export_foo2.py
+--export_foo3.py
+--export_foo4.py
+--export_bar1.py
+--export_bar2.py
+--export_bar3.py
+--export_bar4.py
+--export_all.py
</code>```

With time, though, this became messy and we decided to restructure it:

```<code>+--settings.py
+--settings.yml
+--Foo
+  +--export_foo1.py
+  +--export_foo2.py
+  +--export_foo3.py
+  +--export_foo4.py
+--Bar
+  +--export_bar1.py
+  +--export_bar2.py
+  +--export_bar3.py
+  +--export_bar4.py
+--export_all.py
</code>```

And then all hell broke loose.

We discovered that one can only use 'import' for modules that are either underneath the module or specifically within sys.path.

The solution we've come up with involves inserting this beauty at the top of all of our scripts:

```<code>PACKAGE_PARENT = os.path.join('..','..')
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
</code>```

but it just seems like overkill to us.

We tried

```<code>from settings import functionname
</code>```

but that doesn't run the code that generates the constants from the yaml file

Also, we tried squeezing the imports in __init.py__ in each directory, but then the Subprocess.Popen() didn't work.

We're kind of missing a pythonesque way to have some global constants, and an initialiazing script that runs only once (even when the 'mother' script is running).

Is it us, or is python just weird and ugly here?

答:
I am not sure what exactly the problem is, but here are several options you can choose from:

The best approach is to reference your scripts as if they are submodules of a package. In this case, everything should work if you run all scripts from the directory where export_all.py lives. The only change is that you should run them as modules, and not as scripts:

```<code>$ python export_all.py
</code>```

but

```<code>$ python -m Foo.export_foo
</code>```

You can use PYTHONPATH environment variable to pass additional paths for sys.path to your script. The variable will be inherited by subprocesses.

Assuming you run your scripts in a virtual environment, you can put a .pth file in your site-packages directory with absolute paths of the Foo and Bar directories. The paths will be added to sys.path each time a script is started with python without -S switch. You can read about .pth files in the documentation for standard site module.

Body:
My use case is the following:

several scripts that can be run individually

one 'mother' script that can run all the scripts

each script has global variables it uses (paths to specific locations, constants used by all scripts)

some of these global variables are inputted in a settings.yaml file which gets dynamically loaded with yaml.load()

several people are running the system, we want to avoid environment variables or any kind of low-level path settings

The use cases were satisfied with an

import settings

at the beginning of each export module.

The settings.py script is our 'initialize' script that loads and create variables used for all the modules, e.g.:

import os
import yaml
from utils import create_dir

input_f = open("settings.yml")
settings = yaml.load(input_f.read())
input_f.close()

TOHELLO = settings['TOHELLO']
TOBONJOUR = settings['TOBONJOUR']

#check for needed directories and create if necessary
create_dir(TOHELLO)
create_dir(TOBONJOUR)

The 'mother module' export_all.py uses Subprocess.Popen() to run all the scripts sequentially.

Originally all files were in the root:

+--settings.py
+--settings.yml
+--export_foo1.py
+--export_foo2.py
+--export_foo3.py
+--export_foo4.py
+--export_bar1.py
+--export_bar2.py
+--export_bar3.py
+--export_bar4.py
+--export_all.py

With time, though, this became messy and we decided to restructure it:

+--settings.py
+--settings.yml
+--Foo
+  +--export_foo1.py
+  +--export_foo2.py
+  +--export_foo3.py
+  +--export_foo4.py
+--Bar
+  +--export_bar1.py
+  +--export_bar2.py
+  +--export_bar3.py
+  +--export_bar4.py
+--export_all.py

And then all hell broke loose.

We discovered that one can only use 'import' for modules that are either underneath the module or specifically within sys.path.

The solution we've come up with involves inserting this beauty at the top of all of our scripts:

PACKAGE_PARENT = os.path.join('..','..')
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

but it just seems like overkill to us.

We tried

from settings import functionname

but that doesn't run the code that generates the constants from the yaml file

Also, we tried squeezing the imports in __init.py__ in each directory, but then the Subprocess.Popen() didn't work.

We're kind of missing a pythonesque way to have some global constants, and an initialiazing script that runs only once (even when the 'mother' script is running).

Is it us, or is python just weird and ugly here?

Body:
I am not sure what exactly the problem is, but here are several options you can choose from:

The best approach is to reference your scripts as if they are submodules of a package. In this case, everything should work if you run all scripts from the directory where export_all.py lives. The only change is that you should run them as modules, and not as scripts:

$ python export_all.py

but

$ python -m Foo.export_foo

You can use PYTHONPATH environment variable to pass additional paths for sys.path to your script. The variable will be inherited by subprocesses.

Assuming you run your scripts in a virtual environment, you can put a .pth file in your site-packages directory with absolute paths of the Foo and Bar directories. The paths will be added to sys.path each time a script is started with python without -S switch. You can read about .pth files in the documentation for standard site module.


问:
python3 programme raising TypeError: 'dict' object is not callable
I basically tried to write a programme which will send mails to a list of users.i ran the programme below and it is telling me that TypeError: 'dict' object is not callable. I cant understand what is wrong here and how to fix it.I know it's a long code but any kind of help would be appreciated. I may have made some silly mistakes but i cant reach it.

```<code>import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

host = "smtp.gmail.com"
port = 587
username = "testmail3018"
password = "******" #not disclosing the password
from_email = username
to_mail_list = ["testmail3018@gmail.com",
"rasel_cse07@gmail.com"]#to_email always have to be a list
#not using this list anymore in this programme

class MessageUser():
  User_Details = []
  Messages = []
  Email_Message = []
  base_message = """Hi {name}!
  Thank you for the purchase on {date}.
  We hope you are exicted about using it. Just as a
  reminder the purcase total was ${total}.
  Have a great time!

  from Pritom_Mazhi
  """

  def add_user(self, name, amount, email=None):
    name = name[0].upper() + name[1:].lower() #Capitalizing the first
    letter of all names - formatted name
    amount = "%.2f" %(amount) #formatted amount
    detail = {
      "name" : name,
      "amount" : amount,
    }
    today = datetime.date.today()
    date_text =
    '{tday.day}/{tday.month}/{tday.year}'.format(tday=today)
    #formatted date
    detail["date"] = date_text
    if email is not None:
      detail["email"] = email
    self.User_Details.append(detail)

  def get_details(self):
      return self.User_Details

  def make_message(self):
      if len(self.User_Details) > 0:
        for detail in self.get_details():  #for detail in
              self.User_Details
          name = detail["name"]
          amount = detail["amount"]
          date = detail["date"]
          #email = detail["email"]
          message = self.base_message
          formatted_message = message.format(
            name = name,
            total = amount,
            date = date
            )
          user_email = detail.get("email")
          if user_email:
              user_data = {
              "email" : user_email,
              "message" : formatted_message
              }
              self.Email_Message.append(user_data)
          else:
              self.Messages.append(formatted_message)

        return self.Messages
      else:
          return []

  def send_email(self):
      self.make_message()
      if len(self.Email_Message) > 0:
          for item in self.Email_Message:
              user_email = item("email")
              user_message = item("message")
              try:
                  gmail_connection = smtplib.SMTP(host, port)
                  gmail_connection.ehlo()
                  gmail_connection.starttls()
                  gmail_connection.login(username, password)

                  the_message = MIMEMultipart("alternative")
                  the_message["Subject"] = "hi there! trying to send
           some billing messages or messages like that"
                  the_message["From"] = from_email
                  the_message["To"] = user_email

                  part1 = MIMEText(user_message, 'plain')
                  the_message.attach(part1)

                  gmail_connection.sendmail(from_email, [user_email],
        the_message.as_string())
                  #to_email always have to be a list
                  gmail_connection.quit()

              except smtplib.SMTPException:
                  print("error sending mails or messages")
                  #return False - could be used here instead of using
    below but while iterating this wouldn't be good
          return True
      return False

obj = MessageUser()
obj.add_user("Pritom", 123.32, email='testmail3018@gmail.com')
obj.add_user("jon Snow", 94.23, email='testmail3018@gmail.com')
obj.add_user("Sean", 93.23, email='testmail3018@gmail.com')
obj.add_user("Emilee", 193.23, email='testmail3018@gmail.com')
obj.add_user("Marie", 13.23, email='testmail3018@gmail.com')
obj.get_details()

obj.send_email()
</code>```

the output is in attached screenshot.

the terminal is showing error as follows:
Traceback (most recent call last):
  File "day_12.py", line 118, in
    obj.send_email()
  File "day_12.py", line 78, in send_email
    user_email = item("email")
TypeError: 'dict' object is not callable

答:
in python, in order to access values in a dict, you have two ways:

dict['key']

dict.get('key')

dict('key') will not work.

Body:
I basically tried to write a programme which will send mails to a list of users.i ran the programme below and it is telling me that TypeError: 'dict' object is not callable. I cant understand what is wrong here and how to fix it.I know it's a long code but any kind of help would be appreciated. I may have made some silly mistakes but i cant reach it.

import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

host = "smtp.gmail.com"
port = 587
username = "testmail3018"
password = "******" #not disclosing the password
from_email = username
to_mail_list = ["testmail3018@gmail.com",
"rasel_cse07@gmail.com"]#to_email always have to be a list
#not using this list anymore in this programme

class MessageUser():
  User_Details = []
  Messages = []
  Email_Message = []
  base_message = """Hi {name}!
  Thank you for the purchase on {date}.
  We hope you are exicted about using it. Just as a
  reminder the purcase total was ${total}.
  Have a great time!

  from Pritom_Mazhi
  """

  def add_user(self, name, amount, email=None):
    name = name[0].upper() + name[1:].lower() #Capitalizing the first
    letter of all names - formatted name
    amount = "%.2f" %(amount) #formatted amount
    detail = {
      "name" : name,
      "amount" : amount,
    }
    today = datetime.date.today()
    date_text =
    '{tday.day}/{tday.month}/{tday.year}'.format(tday=today)
    #formatted date
    detail["date"] = date_text
    if email is not None:
      detail["email"] = email
    self.User_Details.append(detail)

  def get_details(self):
      return self.User_Details

  def make_message(self):
      if len(self.User_Details) > 0:
        for detail in self.get_details():  #for detail in
              self.User_Details
          name = detail["name"]
          amount = detail["amount"]
          date = detail["date"]
          #email = detail["email"]
          message = self.base_message
          formatted_message = message.format(
            name = name,
            total = amount,
            date = date
            )
          user_email = detail.get("email")
          if user_email:
              user_data = {
              "email" : user_email,
              "message" : formatted_message
              }
              self.Email_Message.append(user_data)
          else:
              self.Messages.append(formatted_message)

        return self.Messages
      else:
          return []

  def send_email(self):
      self.make_message()
      if len(self.Email_Message) > 0:
          for item in self.Email_Message:
              user_email = item("email")
              user_message = item("message")
              try:
                  gmail_connection = smtplib.SMTP(host, port)
                  gmail_connection.ehlo()
                  gmail_connection.starttls()
                  gmail_connection.login(username, password)

                  the_message = MIMEMultipart("alternative")
                  the_message["Subject"] = "hi there! trying to send
           some billing messages or messages like that"
                  the_message["From"] = from_email
                  the_message["To"] = user_email

                  part1 = MIMEText(user_message, 'plain')
                  the_message.attach(part1)

                  gmail_connection.sendmail(from_email, [user_email],
        the_message.as_string())
                  #to_email always have to be a list
                  gmail_connection.quit()

              except smtplib.SMTPException:
                  print("error sending mails or messages")
                  #return False - could be used here instead of using
    below but while iterating this wouldn't be good
          return True
      return False

obj = MessageUser()
obj.add_user("Pritom", 123.32, email='testmail3018@gmail.com')
obj.add_user("jon Snow", 94.23, email='testmail3018@gmail.com')
obj.add_user("Sean", 93.23, email='testmail3018@gmail.com')
obj.add_user("Emilee", 193.23, email='testmail3018@gmail.com')
obj.add_user("Marie", 13.23, email='testmail3018@gmail.com')
obj.get_details()

obj.send_email()

the output is in attached screenshot.

the terminal is showing error as follows:
Traceback (most recent call last):
  File "day_12.py", line 118, in
    obj.send_email()
  File "day_12.py", line 78, in send_email
    user_email = item("email")
TypeError: 'dict' object is not callable


问:
Search a Dynamic Number of rows in Column A for a specific string in VBA
I have a worksheet that contains a varying amount of Rows of data in Column A , within this worksheet I need to search for a specific string then copy the data contained in the Cell adjacent to it and paste into Column C, i.e if data was found in A2 then i need to copy the data from B2 and paste into C1. I can easily find and copy when the string appears once but the string will appear more than once 100% of time. here is when i run into issues.

The temporary code I have written for ease of understanding, searches the spreadsheet for the last Mention of A, get the row number, copy the B cell for that row number then pastes the value into C1.

I guess you need to use range variables for this but not 100% sure how to do it.

i have found no way to copy all mentions of A into a column, or ideally sum up the contents of the B cells. (I can do this, just long winded)

Ive placed my code below.

```<code>Sub ValueFinder()
Dim LastALocation As String
Dim ValueContent As String

LastALocation = Range("A:A").Find(What:="A", after:=Range("A1"), searchdirection:=xlPrevious).Row
ValueContent = Cells(LastALocation, 2)
Cells(1, 3) = ValueContent

End Sub
</code>```

The spreadsheet that its using for more information, contains A,B,C on a loop in Column A and the odd numbers in Column B.

Thanks for any help your able to provide.

Mark

答:
Consider:

```<code>Sub LookingForA()
    Dim s As String, rng As Range, WhichRows() As Long
    Dim rFound As Range

    ReDim WhichRows(1)

    s = "A"
    Set rng = Range("A:A")
    Set rFound = rng.Find(What:=s, After:=rng(1))
    WhichRows(1) = rFound.Row
    Cells(1, 3) = Cells(rFound.Row, 2)

    Do
        Set rFound = rng.FindNext(After:=rFound)
        If rFound.Row = WhichRows(1) Then Exit Do
        ReDim Preserve WhichRows(UBound(WhichRows) + 1)
        WhichRows(UBound(WhichRows)) = rFound.Row
        Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, 3) = Cells(rFound.Row, 2)
    Loop
End Sub
</code>```

This code builds column C.  It also builds an internal array of the row numbers in the event they are needed later.

EDIT#1:

To read about dynamic arrays:

Dynamic Arrays

or Google:

Excel VBA dynamic array

Body:
I have a worksheet that contains a varying amount of Rows of data in Column A , within this worksheet I need to search for a specific string then copy the data contained in the Cell adjacent to it and paste into Column C, i.e if data was found in A2 then i need to copy the data from B2 and paste into C1. I can easily find and copy when the string appears once but the string will appear more than once 100% of time. here is when i run into issues.

The temporary code I have written for ease of understanding, searches the spreadsheet for the last Mention of A, get the row number, copy the B cell for that row number then pastes the value into C1.

I guess you need to use range variables for this but not 100% sure how to do it.

i have found no way to copy all mentions of A into a column, or ideally sum up the contents of the B cells. (I can do this, just long winded)

Ive placed my code below.

Sub ValueFinder()
Dim LastALocation As String
Dim ValueContent As String

LastALocation = Range("A:A").Find(What:="A", after:=Range("A1"), searchdirection:=xlPrevious).Row
ValueContent = Cells(LastALocation, 2)
Cells(1, 3) = ValueContent

End Sub

The spreadsheet that its using for more information, contains A,B,C on a loop in Column A and the odd numbers in Column B.

Thanks for any help your able to provide.

Mark

Body:
Consider:

Sub LookingForA()
    Dim s As String, rng As Range, WhichRows() As Long
    Dim rFound As Range

    ReDim WhichRows(1)

    s = "A"
    Set rng = Range("A:A")
    Set rFound = rng.Find(What:=s, After:=rng(1))
    WhichRows(1) = rFound.Row
    Cells(1, 3) = Cells(rFound.Row, 2)

    Do
        Set rFound = rng.FindNext(After:=rFound)
        If rFound.Row = WhichRows(1) Then Exit Do
        ReDim Preserve WhichRows(UBound(WhichRows) + 1)
        WhichRows(UBound(WhichRows)) = rFound.Row
        Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, 3) = Cells(rFound.Row, 2)
    Loop
End Sub

This code builds column C.  It also builds an internal array of the row numbers in the event they are needed later.

EDIT#1:

To read about dynamic arrays:

Dynamic Arrays

or Google:

Excel VBA dynamic array


问:
C# Telerik Grid data binding not reloading
I want to bind data in telerik grid dynamically.
Initially I used below code.

```<code>protected void radGridItemList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var gridItemList = sender as RadGrid;
            var repoItemMaster = CreateIItemMasterRepository();
            var ItemList = repoItemMaster.GetAll();
            gridItemList.DataSource = ItemList;
}
</code>```

Now I want to reload gridItemList with filtered ItemNumbers (E.g select ItemNumber from ItemMaster where ItemNumber LIKE 'a%') and bind new data source to grid again.

I did something like this but It does not work.

```<code>private void LoadItemListByItemNumber(string ItemNumber)
        {
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            string whereCondition = "a.ItemNumber LIKE '"+ ItemNumber + "%'";

            var repoItemMaster = CreateIItemMasterRepository();
            List<ItemMaster> itemList = repoItemMaster.FindbyItemNumber(ItemNumber, whereCondition);
            gridItemList.DataSource = itemList;
        }
</code>```

Any suggestions?

答:
You can use the built in RadGrid functionality to filter a DataSource consisting of custom objects when using Advanced Data Binding(RadGrid1_OnNeedDataSource()).

To do so from within the RadGrid just enable filtering by setting AllowFilteringByColumn="True" and the RadGrid will automatically filter your DataSource.

You can also do this externally by setting the current Filter Expression and calling rebind() on the RadGrid.

ASPX:

```<code><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Button ID="Button1" runat="server" Text="Filter by 1" OnClick="Button1_Click" />
<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AllowFilteringByColumn="True" CellSpacing="-1" GridLines="Both" EnableLinqExpressions="false" AllowPaging="True"></telerik:RadGrid>
</code>```

C#:

```<code> // <summary>
// Demo cusotm object
// </summary>
public class MyObject
{
    public int ItemNumber { get; set; }
    public string ItemName { get; set; }
}

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    //  Bind RadGrid
    RadGrid1.DataSource = this.GetData();
}

// <summary>
// Returns a Demo custom object DataSource
// </summary>
// <returns></returns>
private List<MyObject> GetData()
{
    List<MyObject> data = new List<MyObject>();
    for (int i = 0; (i <= 100); i++)
    {
        var item = new MyObject();
        item.ItemNumber = i;
        item.ItemName = ("Item # " + i);
        data.Add(item);
    }
    return data;
}

protected void Button1_Click(object sender, EventArgs e)
{
    RadGrid1.MasterTableView.FilterExpression = "([ItemName] LIKE \'%1%\')";
    RadGrid1.Rebind();
}
</code>```

Some links to look at:

Advanced DataBinding

Advanced Data Binding Tips

Manual Filtering

Body:
I want to bind data in telerik grid dynamically.
Initially I used below code.

protected void radGridItemList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var gridItemList = sender as RadGrid;
            var repoItemMaster = CreateIItemMasterRepository();
            var ItemList = repoItemMaster.GetAll();
            gridItemList.DataSource = ItemList;
}

Now I want to reload gridItemList with filtered ItemNumbers (E.g select ItemNumber from ItemMaster where ItemNumber LIKE 'a%') and bind new data source to grid again.

I did something like this but It does not work.

private void LoadItemListByItemNumber(string ItemNumber)
        {
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            string whereCondition = "a.ItemNumber LIKE '"+ ItemNumber + "%'";

            var repoItemMaster = CreateIItemMasterRepository();
            List<ItemMaster> itemList = repoItemMaster.FindbyItemNumber(ItemNumber, whereCondition);
            gridItemList.DataSource = itemList;
        }

Any suggestions?

Body:
You can use the built in RadGrid functionality to filter a DataSource consisting of custom objects when using Advanced Data Binding(RadGrid1_OnNeedDataSource()).

To do so from within the RadGrid just enable filtering by setting AllowFilteringByColumn="True" and the RadGrid will automatically filter your DataSource.

You can also do this externally by setting the current Filter Expression and calling rebind() on the RadGrid.

ASPX:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Button ID="Button1" runat="server" Text="Filter by 1" OnClick="Button1_Click" />
<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AllowFilteringByColumn="True" CellSpacing="-1" GridLines="Both" EnableLinqExpressions="false" AllowPaging="True"></telerik:RadGrid>

C#:

 // <summary>
// Demo cusotm object
// </summary>
public class MyObject
{
    public int ItemNumber { get; set; }
    public string ItemName { get; set; }
}

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    //  Bind RadGrid
    RadGrid1.DataSource = this.GetData();
}

// <summary>
// Returns a Demo custom object DataSource
// </summary>
// <returns></returns>
private List<MyObject> GetData()
{
    List<MyObject> data = new List<MyObject>();
    for (int i = 0; (i <= 100); i++)
    {
        var item = new MyObject();
        item.ItemNumber = i;
        item.ItemName = ("Item # " + i);
        data.Add(item);
    }
    return data;
}

protected void Button1_Click(object sender, EventArgs e)
{
    RadGrid1.MasterTableView.FilterExpression = "([ItemName] LIKE \'%1%\')";
    RadGrid1.Rebind();
}

Some links to look at:

Advanced DataBinding

Advanced Data Binding Tips

Manual Filtering


问:
Sticky nav and scroll to top confusion
I have a sticky nav in the middle of the page (Agenda days) that becomes fixed while the content of the sticky nav is being scrolled down.  The nav is Bootstrap tabs, this is how the HTML look like:

```<code><ul class="nav nav-tabs followMeBar agenda-days text-center">
  <li class="active"><a class="day" href="#1" data-toggle="tab">Day 1</a></li>
  <li><a class="day" href="#2" data-toggle="tab">Day 2</a></li>
  <li><a class="day" href="#3" data-toggle="tab">Day 3</a></li>
</ul>
</code>```

and the tab contents are located in divs with corresponding ids, like this:

```<code><div class="tab-pane" id="1">
    <h3>Day 1</h3>
</code>```

Everything is working fine except one thing, if you are half way scrolled down on Day 1 and then click on Day 2, the content switches to Day 2 but you're still halfway scrolled down. How do I make Day 1, Day 2, Day 3 to switch the content AND scroll to the top of the Agenda content (not to the top of the page).

Here's my full code example: https://codepen.io/anon/pen/POvGPr

答:
First of all add class to li container of days link. Second for instance add a selector before days navigation.</p>

```<code><div class="test"></div>

<li class="active scroll-top"><a  href="#1" data-toggle="tab">Day 1</a></li>

  $('.scroll-top').click(function(){
     $('html,body').animate({
       scrollTop: $(".test").offset().top},
       'slow');
  });
</code>```

Title: Sticky nav and scroll to top confusion

Body:
I have a sticky nav in the middle of the page (Agenda days) that becomes fixed while the content of the sticky nav is being scrolled down.  The nav is Bootstrap tabs, this is how the HTML look like:

Day 1

Day 2

Day 3

and the tab contents are located in divs with corresponding ids, like this:

Day 1

Everything is working fine except one thing, if you are half way scrolled down on Day 1 and then click on Day 2, the content switches to Day 2 but you're still halfway scrolled down. How do I make Day 1, Day 2, Day 3 to switch the content AND scroll to the top of the Agenda content (not to the top of the page).

Here's my full code example: https://codepen.io/anon/pen/POvGPr

Body:
First of all add class to li container of days link. Second for instance add a selector before days navigation.

<div class="test"></div>

<li class="active scroll-top"><a  href="#1" data-toggle="tab">Day 1</a></li>

  $('.scroll-top').click(function(){
     $('html,body').animate({
       scrollTop: $(".test").offset().top},
       'slow');
  });


问:
"undefined symbol: mg_free_type" when installing mod_perl 2.0.10 with Apache 2.4.26 and Perl 5.10.1
I'm trying to install mod_perl 2.0.10 for use with a new Apache 2.4 instance. I've got Apache 2.4.26 up and running by itself, but I also need mod_perl installed for a couple of modules to work.

Here's the problem: mod_perl always fails its tests claiming:

```<code>Syntax error on line 82 of .../t/conf/httpd.conf: Cannot load .../src/modules/perl/mod_perl.so into server: .../src/modules/perl/mod_perl.so: undefined symbol: mg_free_type
</code>```

The only information I could find on this is here: Error when installing mod_perl2. Unfortunately, it didn't solve the problem.

Using CentOS release 6.8 (Final)
x86_64 x86_64 x86_64 GNU/Linux

More from the log:

```<code>> make test
cd "src/modules/perl" && make
make[1]: Entering directory `/software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl'
...
make[1]: Leaving directory `/software/apa/mod_perl/mod_perl-2.0.10/xs'
/usr/bin/perl -Iblib/arch -Iblib/lib \
    t/TEST -clean
[warning] setting ulimit to allow core files
ulimit -c unlimited; /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -clean
APACHE_TEST_APXS= APACHE_TEST_GROUP= APACHE_TEST_HTTPD= APACHE_TEST_PORT= APACHE_TEST_USER= \
    /usr/bin/perl -Iblib/arch -Iblib/lib \
    t/TEST -bugreport -verbose=0
[warning] setting ulimit to allow core files
ulimit -c unlimited; /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -bugreport -verbose=0
/software/apa/apa24/bin/httpd.prefork  -d /software/apa/mod_perl/mod_perl-2.0.10/t -f /software/apa/mod_perl/mod_perl-2.0.10/t/conf/httpd.conf -D APACHE2 -D APACHE2_4 -D PERL_USEITHREADS
using Apache/2.4.26 (prefork MPM)

waiting 300 seconds for server to start: .httpd.prefork: Syntax error on line 82 of /software/apa/mod_perl/mod_perl-2.0.10/t/conf/httpd.conf: Cannot load /software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl/mod_perl.so into server: /software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl/mod_perl.so: undefined symbol: mg_free_type
[  error]
server has died with status 255 (t/logs/error_log wasn't created, start the server in the debug mode)
sh: line 1:  3359 Terminated              /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -bugreport -verbose=0
make: *** [run_tests] Error 143
</code>```

答:
This bug was introduced when they added support of perl version 5.22, in mod_perl 2.0.10: https://github.com/apache/mod_perl/commit/82827132efd3c2e25cc413c85af61bb63375da6e#diff-0a249c57fb8151f85647e167a883be1b

And then was fixed in a mod_Perl patch on 4 January 2018 (2.0.11-dev):
https://github.com/apache/mod_perl/commit/f4d886fdf7d79d54a0647336b5623b840a053eab

To fix this problem you must compile from source of this commit of mod_perl 2.0.11-dev (or the trunk version) to fix the problem if you have perl <=5.13.6, or if you can upgrade Perl to version >5.13.6 you can compile with mod_perl 2.0.10.

This change in Perl as been introduced in source of Perl version 5.13.6 in this perl commit :
https://perl5.git.perl.org/perl.git/commit/d908838680ec40ea0e85f59ee66f5f56a225f9b4

The mod_perl fix (in last 2.0.11-dev) in src/modules/perl/modperl_env.c use contextual usage of mg_free to fix the problem :

```<code>#if MP_PERL_VERSION_AT_LEAST(5, 13, 6)
    mg_free_type((SV*)ENVHV, PERL_MAGIC_env);
#else
    mg_free((SV*)ENVHV);
#endif
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to install mod_perl 2.0.10 for use with a new Apache 2.4 instance. I've got Apache 2.4.26 up and running by itself, but I also need mod_perl installed for a couple of modules to work.

Here's the problem: mod_perl always fails its tests claiming:

Syntax error on line 82 of .../t/conf/httpd.conf: Cannot load .../src/modules/perl/mod_perl.so into server: .../src/modules/perl/mod_perl.so: undefined symbol: mg_free_type

The only information I could find on this is here: Error when installing mod_perl2. Unfortunately, it didn't solve the problem.

Using CentOS release 6.8 (Final)
x86_64 x86_64 x86_64 GNU/Linux

More from the log:

> make test
cd "src/modules/perl" && make
make[1]: Entering directory `/software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl'
...
make[1]: Leaving directory `/software/apa/mod_perl/mod_perl-2.0.10/xs'
/usr/bin/perl -Iblib/arch -Iblib/lib \
    t/TEST -clean
[warning] setting ulimit to allow core files
ulimit -c unlimited; /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -clean
APACHE_TEST_APXS= APACHE_TEST_GROUP= APACHE_TEST_HTTPD= APACHE_TEST_PORT= APACHE_TEST_USER= \
    /usr/bin/perl -Iblib/arch -Iblib/lib \
    t/TEST -bugreport -verbose=0
[warning] setting ulimit to allow core files
ulimit -c unlimited; /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -bugreport -verbose=0
/software/apa/apa24/bin/httpd.prefork  -d /software/apa/mod_perl/mod_perl-2.0.10/t -f /software/apa/mod_perl/mod_perl-2.0.10/t/conf/httpd.conf -D APACHE2 -D APACHE2_4 -D PERL_USEITHREADS
using Apache/2.4.26 (prefork MPM)

waiting 300 seconds for server to start: .httpd.prefork: Syntax error on line 82 of /software/apa/mod_perl/mod_perl-2.0.10/t/conf/httpd.conf: Cannot load /software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl/mod_perl.so into server: /software/apa/mod_perl/mod_perl-2.0.10/src/modules/perl/mod_perl.so: undefined symbol: mg_free_type
[  error]
server has died with status 255 (t/logs/error_log wasn't created, start the server in the debug mode)
sh: line 1:  3359 Terminated              /usr/bin/perl /software/apa/mod_perl/mod_perl-2.0.10/t/TEST -bugreport -verbose=0
make: *** [run_tests] Error 143

Body:
This bug was introduced when they added support of perl version 5.22, in mod_perl 2.0.10: https://github.com/apache/mod_perl/commit/82827132efd3c2e25cc413c85af61bb63375da6e#diff-0a249c57fb8151f85647e167a883be1b

And then was fixed in a mod_Perl patch on 4 January 2018 (2.0.11-dev):
https://github.com/apache/mod_perl/commit/f4d886fdf7d79d54a0647336b5623b840a053eab

To fix this problem you must compile from source of this commit of mod_perl 2.0.11-dev (or the trunk version) to fix the problem if you have perl <=5.13.6, or if you can upgrade Perl to version >5.13.6 you can compile with mod_perl 2.0.10.

This change in Perl as been introduced in source of Perl version 5.13.6 in this perl commit :
https://perl5.git.perl.org/perl.git/commit/d908838680ec40ea0e85f59ee66f5f56a225f9b4

The mod_perl fix (in last 2.0.11-dev) in src/modules/perl/modperl_env.c use contextual usage of mg_free to fix the problem :

#if MP_PERL_VERSION_AT_LEAST(5, 13, 6)
    mg_free_type((SV*)ENVHV, PERL_MAGIC_env);
#else
    mg_free((SV*)ENVHV);
#endif


问:
RecyclerView onItemClick Interface: get values in the Adapter or in the Activity?
I have a ViewHolder with an OnClickListener, which sends the click over an Interface to the underlying Activity. The only information i send is the AdapterPosition. In the Activity i then get the information out of the Activitie's reference to the ArrayList (which also fills the Adapter), using the position i get passed from the Adapter. I then use this to open a new Activity where i show this data.
Now, this works, but i just came to mind that this could cause problems, if i don't properly call notifyDataSetChanged/ItemInserted/Removed etc. and the Adapter shows a different List than the actualy up-to-date List in the Activity. I am right about this? Should i get the values out of the Objects IN the Adapter and pass them to the Activity or is my approach correct?

ViewHolder:

```<code>public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImageView;
    public TextView mTextViewCreator;
    public TextView mTextViewLikes;

    public ExampleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.image_view);
        mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
        mTextViewLikes = itemView.findViewById(R.id.text_view_likes);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        mListener.onItemClick(position);
                    }
                }
            }
        });
    }
}
</code>```

MainActivity OnItemClick implementation:

```<code>@Override
public void onItemClick(int position) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    ExampleItem clickedItem = mExampleList.get(position);

    detailIntent.putExtra("imageUrl", clickedItem.getImageUrl());
    detailIntent.putExtra("creatorName", clickedItem.getCreator());
    detailIntent.putExtra("likeCount", clickedItem.getLikeCount());

    startActivity(detailIntent);
}
</code>```

答:
The answer is simple: Always make sure that you notify the adapter about changes.
Otherwise its behavior becomes unpredictable.

Apart from that, your code seems to be fine

Body:
I have a ViewHolder with an OnClickListener, which sends the click over an Interface to the underlying Activity. The only information i send is the AdapterPosition. In the Activity i then get the information out of the Activitie's reference to the ArrayList (which also fills the Adapter), using the position i get passed from the Adapter. I then use this to open a new Activity where i show this data.
Now, this works, but i just came to mind that this could cause problems, if i don't properly call notifyDataSetChanged/ItemInserted/Removed etc. and the Adapter shows a different List than the actualy up-to-date List in the Activity. I am right about this? Should i get the values out of the Objects IN the Adapter and pass them to the Activity or is my approach correct?

ViewHolder:

public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImageView;
    public TextView mTextViewCreator;
    public TextView mTextViewLikes;

    public ExampleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.image_view);
        mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
        mTextViewLikes = itemView.findViewById(R.id.text_view_likes);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        mListener.onItemClick(position);
                    }
                }
            }
        });
    }
}

MainActivity OnItemClick implementation:

@Override
public void onItemClick(int position) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    ExampleItem clickedItem = mExampleList.get(position);

    detailIntent.putExtra("imageUrl", clickedItem.getImageUrl());
    detailIntent.putExtra("creatorName", clickedItem.getCreator());
    detailIntent.putExtra("likeCount", clickedItem.getLikeCount());

    startActivity(detailIntent);
}


问:
Finding filenames with specific string in a shell script
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

```<code>#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'
</code>```

The only output that I get is the following error message

```<code>-name: command not found
</code>```

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

```<code>anatomical_scans=$(find $input_path -name "*mprage*")
</code>```

Thanks

答:
You can try as below, hope it can help.</p>

```<code>#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=`find $inputpath -name '*mprage'`

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'
</code>```

Body:
I am trying to write a bash script to do a batch processing of some fMRI data. My problem is that I am not able to get the filenames that match a specific pattern within the directory of interest.

My scripts looks like this

#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=$find `$inputpath` -name *mprage

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'

The only output that I get is the following error message

-name: command not found

I am definetely not familiar with shell scripting so I am sorry if the question may sound trivial.
Any help will be much appreciated.

Antonio

EDIT:: SOLVED

Exploring the suggestions I found the correct way to make it running with no errors

anatomical_scans=$(find $input_path -name "*mprage*")

Thanks

Body:
You can try as below, hope it can help.

#!/bin/bash

inputpath="/Volumes/External_HD/Experiments/MRI_Data"
outputpath="/Volumes/External_HD/Experiments/MRI_Data_output"

anatomical_scans=`find $inputpath -name '*mprage'`

# RUN BET
bet $anatomical_scans $outputpath

echo 'Finished!!!'


问:
ORA-01748: only simple column names allowed here in Oracle
What I am trying to do ?

I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).

What is the problem ?

I get the following error while creating Attendence table:

ERROR at line 5: ORA-01748: only simple column names allowed here

My code:

Student table:

```<code>create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);
</code>```

Attendence table:

```<code>create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);
</code>```

答:
Your foreign key constraint syntax is wrong; it should be:

```<code>constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
</code>```

You are preceding the FK column name with the table name, which is wrong in itself, but also have it in the wrong place.

```<code>create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);

Table STUDENT created.

create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
);

Table ATTENDENCE created.
</code>```

Body:
What I am trying to do ?

I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).

What is the problem ?

I get the following error while creating Attendence table:

ERROR at line 5: ORA-01748: only simple column names allowed here

My code:

Student table:

create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);

Attendence table:

create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);

Body:
Your foreign key constraint syntax is wrong; it should be:

constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)

You are preceding the FK column name with the table name, which is wrong in itself, but also have it in the wrong place.

create table Student (

            ST_ROLLNO  NUMBER(6) constraint s_pk primary key,
            ST_NAME    VARCHAR(30) not null,
            ST_ADDRESS  varchar(35) not null
);

Table STUDENT created.

create table Attendence (

            ST_ROLLNO  NUMBER(6),
            ST_DATE    VARCHAR(30) not null,
            ST_PRESENT_ABSENT  varchar(1) not null,
            constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
);

Table ATTENDENCE created.


问:
C++ lambda function as class member: strange behaviour
I have a class where I would like to use lambda function (for example, just write a value of public member). Lambda is keeped in the std::function object:

```<code>class Tester
{

public:

    Tester() {};
    Tester(double val);
    ~Tester() {}

    //- variable
    double v;

    //- write v using lambda
    std::function<void()> writeV;

    //- write v using simple function
    void writeVexp();
};

Tester::Tester(double val)
{
    v = val;

    writeV = [this]() { std::cout << "inside lambda " << v << '\n'; };
}

void Tester::writeVexp()
{
    std::cout << "inside simple function " << v << '\n';
}
</code>```

I have another class which collects these testers in std::vector:

```<code>class vectorTester
{
    std::vector<Tester> vtst;

    double size;

public:

    //- default constructor
    vectorTester() {}

    //- construct by number of testers
    vectorTester(double num);

    ~vectorTester() {}

    //- write publuc members of all Testers
    void useTesterLambda();
    void useTesterSimple();
    void useTesterVar();
};

vectorTester::vectorTester(double num)
{
    vtst.reserve(num);

    size = num;

    for (int i = 0; i < num; ++i)
    {
        Tester tst (i + 0.365);
        vtst.push_back(tst);
    }
}

void vectorTester::useTesterLambda()
{
    cout << "\n tester's lambda \n";

    for (int i = 0; i < size; ++i)
    {
        vtst[i].writeV();
    }
}

void vectorTester::useTesterSimple()
{
    cout << "\n tester's simple function \n";

    for (int i = 0; i < size; ++i)
    {
        vtst[i].writeVexp();
    }
}

void vectorTester::useTesterVar()
{
    cout << "\n tester's vars \n";

    for (int i = 0; i < size; ++i)
    {
        cout << vtst[i].v << endl;
    }
}
</code>```

And the main function is simple:

```<code>int main()
{
    vectorTester vtst(5);

    vtst.useTesterLambda();
    vtst.useTesterSimple();
    vtst.useTesterVar();

    return 0;
}
</code>```

The output said me that lambda function can not see the value V of class Tester!

```<code>     tester's lambda
inside lambda 0
inside lambda 4.94066e-324
inside lambda 9.88131e-324
inside lambda 1.4822e-323
inside lambda 1.97626e-323

 tester's simple function
inside simple function 0.365
inside simple function 1.365
inside simple function 2.365
inside simple function 3.365
inside simple function 4.365

 tester's vars
0.365
1.365
2.365
3.365
4.365
</code>```

What is the reason of this strange behaviour?

答:
As state in comment you have broken rule of 0/3/5, you have to implement copy constructor

```<code>class Tester
{
public:
    Tester(double val) : v(val) {
        writeV = [this](){std::cout << "inside lambda " << v << '\n';};
    }

    Tester(const Tester& rhs) : v(rhs.v) {
        writeV = [this](){std::cout << "inside lambda " << v << '\n';};
    }

    Tester& operator =(const Tester& rhs) {
        v = rhs.v;
        // Keep function
        return *this;
    }

    void writeVexp() const { std::cout << "inside simple function " << v << '\n'; }
private:
    double v;
    std::function<void()> writeV;
};
</code>```

Demo

Body:
I have a class where I would like to use lambda function (for example, just write a value of public member). Lambda is keeped in the std::function object:

class Tester
{

public:

    Tester() {};
    Tester(double val);
    ~Tester() {}

    //- variable
    double v;

    //- write v using lambda
    std::function<void()> writeV;

    //- write v using simple function
    void writeVexp();
};

Tester::Tester(double val)
{
    v = val;

    writeV = [this]() { std::cout << "inside lambda " << v << '\n'; };
}

void Tester::writeVexp()
{
    std::cout << "inside simple function " << v << '\n';
}

I have another class which collects these testers in std::vector:

class vectorTester
{
    std::vector<Tester> vtst;

    double size;

public:

    //- default constructor
    vectorTester() {}

    //- construct by number of testers
    vectorTester(double num);

    ~vectorTester() {}

    //- write publuc members of all Testers
    void useTesterLambda();
    void useTesterSimple();
    void useTesterVar();
};

vectorTester::vectorTester(double num)
{
    vtst.reserve(num);

    size = num;

    for (int i = 0; i < num; ++i)
    {
        Tester tst (i + 0.365);
        vtst.push_back(tst);
    }
}

void vectorTester::useTesterLambda()
{
    cout << "\n tester's lambda \n";

    for (int i = 0; i < size; ++i)
    {
        vtst[i].writeV();
    }
}

void vectorTester::useTesterSimple()
{
    cout << "\n tester's simple function \n";

    for (int i = 0; i < size; ++i)
    {
        vtst[i].writeVexp();
    }
}

void vectorTester::useTesterVar()
{
    cout << "\n tester's vars \n";

    for (int i = 0; i < size; ++i)
    {
        cout << vtst[i].v << endl;
    }
}

And the main function is simple:

int main()
{
    vectorTester vtst(5);

    vtst.useTesterLambda();
    vtst.useTesterSimple();
    vtst.useTesterVar();

    return 0;
}

The output said me that lambda function can not see the value V of class Tester!

     tester's lambda
inside lambda 0
inside lambda 4.94066e-324
inside lambda 9.88131e-324
inside lambda 1.4822e-323
inside lambda 1.97626e-323

 tester's simple function
inside simple function 0.365
inside simple function 1.365
inside simple function 2.365
inside simple function 3.365
inside simple function 4.365

 tester's vars
0.365
1.365
2.365
3.365
4.365

What is the reason of this strange behaviour?

Body:
As state in comment you have broken rule of 0/3/5, you have to implement copy constructor

class Tester
{
public:
    Tester(double val) : v(val) {
        writeV = [this](){std::cout << "inside lambda " << v << '\n';};
    }

    Tester(const Tester& rhs) : v(rhs.v) {
        writeV = [this](){std::cout << "inside lambda " << v << '\n';};
    }

    Tester& operator =(const Tester& rhs) {
        v = rhs.v;
        // Keep function
        return *this;
    }

    void writeVexp() const { std::cout << "inside simple function " << v << '\n'; }
private:
    double v;
    std::function<void()> writeV;
};

Demo


问:
Spark save as CSV dont ignore spaces
I am trying to save Dataframe as CSV file, I want to retain the spaces. I am using Spark 2.1.1, But when I try to save it as CSV file, all the spaces are trimmed.

I tried these options, but they didn't work.

```<code>option("ignoreLeadingWhiteSpace",false")
  .option("ignoreTrailingWhiteSpace", "false")
</code>```

Expected CSV format

```<code>SiteNumber, batch ,DayBatchDate,RecordType
    190000,    TBD,  12/12/2017,  +00000001
</code>```

My current output:

```<code>SiteNumber, batch ,DayBatchDate,RecordType
190000,TBD,12/12/2017,+00000001
</code>```

答:
ignoreLeadingWhiteSpace and ignoreTrailingWhiteSpace options for the writer have been introduced in Spark 2.2 (
SPARK-18579) so won't have effect in Spark 2.1.

Title: Spark save as CSV dont ignore spaces

Body:
I am trying to save Dataframe as CSV file, I want to retain the spaces. I am using Spark 2.1.1, But when I try to save it as CSV file, all the spaces are trimmed.

I tried these options, but they didn't work.

option("ignoreLeadingWhiteSpace",false")
  .option("ignoreTrailingWhiteSpace", "false")

Expected CSV format

SiteNumber, batch ,DayBatchDate,RecordType
    190000,    TBD,  12/12/2017,  +00000001

My current output:

SiteNumber, batch ,DayBatchDate,RecordType
190000,TBD,12/12/2017,+00000001


问:
need to store ajax response to a global variable
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

```<code>var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });
</code>```

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

答:
So lets say you have an ajax call that you are making to and endpoint, whose response you may want to use at a later time, not immediately upon the success of the ajax call, for whatever reason.  One way to do that is to pass around the promise/deferred that the $.ajax method returns.  With this object you can attach any of the promise/deferred methods for handling the resolution or rejection of the promise.  For instance:

//first we'll create a dummy deferred.  we will pretend that this is our ajax call.  in actual code this would look something like
//var dummyDeferred = $.ajax(...);
var dummyDeferred = $.Deferred();

//lets say, maybe you do want something to happen immediately upon the request success.  you can do that.
dummyDeferred.then(function(data){
  console.log("immediate then", data);
});

//now lets say that the ajax finishes, you should see the console log as you'd expect from the above then()
dummyDeferred.resolve("hello!");

//now lets say that some time later, you want to use that result inside another method to do something.  to do that you can simply attach another then() to the promise/deferred
//we'll use a timeout to simulate later usage of the promise/deferred
setTimeout(function(){
  doOtherStuff(dummyDeferred);
}, 5000);

function doOtherStuff(promise) {
  //maybe you want to take the data response and put it on the page some how.  you can!
  promise.then(function(data){
    $(document.body).append(data);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I am using ajax to get some values from a database. In my java script file I have a global variable that some functions need to access it. I need to fill that variable from the values from the database. When I use ajax then the variable stays empty. If I use the async:false in my ajax code I get that warning message in my browser's dev tools:

jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Moreover using the above it doesn't fill the variable resulting to errors in the other functions. Plus, from what I read this is deprecated and should not be used in any circumstances.

my code

var array ={};
var flag = 'true';
        $.ajax({
            url: "name.php",
            method: "post",
            data:{flag:JSON.stringify(flag)},
            success: function(data) {
                array = JSON.parse(data);

            },
             async: false,
            error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            }
        });

What, basically I'm trying to do, is to fill the array variable and make it an proper array.

the data from the the database is like this

{
'something': { 'act1': 'act1a','act2': 'act2a'},
 'something2': { 'act1': 'act1a','act2': 'act2a'}
}

anyone have any suggestions on how to achieve that?

PS:
I need to fill a variable with the ajax response which will be accessible by other functions... not Convert a JSON Object into Javascript array...Im retrieving the data in string format

Body:
So lets say you have an ajax call that you are making to and endpoint, whose response you may want to use at a later time, not immediately upon the success of the ajax call, for whatever reason.  One way to do that is to pass around the promise/deferred that the $.ajax method returns.  With this object you can attach any of the promise/deferred methods for handling the resolution or rejection of the promise.  For instance:

//first we'll create a dummy deferred.  we will pretend that this is our ajax call.  in actual code this would look something like
//var dummyDeferred = $.ajax(...);
var dummyDeferred = $.Deferred();

//lets say, maybe you do want something to happen immediately upon the request success.  you can do that.
dummyDeferred.then(function(data){
  console.log("immediate then", data);
});

//now lets say that the ajax finishes, you should see the console log as you'd expect from the above then()
dummyDeferred.resolve("hello!");

//now lets say that some time later, you want to use that result inside another method to do something.  to do that you can simply attach another then() to the promise/deferred
//we'll use a timeout to simulate later usage of the promise/deferred
setTimeout(function(){
  doOtherStuff(dummyDeferred);
}, 5000);

function doOtherStuff(promise) {
  //maybe you want to take the data response and put it on the page some how.  you can!
  promise.then(function(data){
    $(document.body).append(data);
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
WP rest api jwt auth
I would like use WP REST API auth with this plugin : https://github.com/Tmeister/wp-api-jwt-auth

I get the token with this req on POST : http://localhost/wp_rest/wp-json/jwt-auth/v1/token

But I can't do the request for post mehod:
localhost/wp_rest/wp-json/wp/v2/posts

I get the error 403:

```<code>{
    "code": "rest_forbidden"
    "message": "You don't have permission to do this."
    "data": {
        "status": 403
    }
}
</code>```

In my header I have this :

```<code>Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3dwX3Jlc3QiLCJpYXQiOjE0NTAzNDEwMTgsIm5iZiI6MTQ1MDM0MTAxOCwiZXhwIjoxNDUwOTQ1ODE4LCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.rGNPsU4EocClWLYWaSDs1hDJMODszg-eKfqnKSEsiw0
</code>```

I'm trying with localhost/wp_rest/wp-json/jwt-auth/v1/token/validate but I get this error:

```<code>{
    "code": "jwt_auth_no_auth_header",
    "message": "Authorization header not found.",
    "data": {
        "status": 403
    }
}
</code>```

Any idea?

答:
I had exactly the same issue. My solution was simple.

Using the tool (in my case postman (https://www.getpostman.com)), I selected to add the Authentication header (forcing the header) manually. You might want to set it manually when using code, under the HTTP Header section (not as a paramater, just in case :) ).

Kind regards,
Reinhard

Title: WP rest api jwt auth

Body:
I would like use WP REST API auth with this plugin : https://github.com/Tmeister/wp-api-jwt-auth

I get the token with this req on POST : http://localhost/wp_rest/wp-json/jwt-auth/v1/token

But I can't do the request for post mehod:
localhost/wp_rest/wp-json/wp/v2/posts

I get the error 403:

{
    "code": "rest_forbidden"
    "message": "You don't have permission to do this."
    "data": {
        "status": 403
    }
}

In my header I have this :

Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3dwX3Jlc3QiLCJpYXQiOjE0NTAzNDEwMTgsIm5iZiI6MTQ1MDM0MTAxOCwiZXhwIjoxNDUwOTQ1ODE4LCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.rGNPsU4EocClWLYWaSDs1hDJMODszg-eKfqnKSEsiw0

I'm trying with localhost/wp_rest/wp-json/jwt-auth/v1/token/validate but I get this error:

{
    "code": "jwt_auth_no_auth_header",
    "message": "Authorization header not found.",
    "data": {
        "status": 403
    }
}

Any idea?


问:
How to read integers elegantly using C++ stream?
I have a file full of lines in this format:

```<code>1 - 2: 3
</code>```

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

答:
```<code>    int a,b,c;

    cin >> a;
    cin.ignore(100,'-');
    cin >> b;
    cin.ignore(100,':');
    cin >> c;

    cout << "a = "<< a <<endl;
    cout << "b = "<< b <<endl;
    cout << "c = "<< c <<endl;
</code>```

Input:

1 - 2: 3

Output:

a = 1

  b = 2

  c = 3

See yourself here : http://www.ideone.com/DT9KJ

Note: this can handle extra spaces also. So you can read even this:

``` 1     -        2      :      3```

Similar topic:

Using ifstream as fscanf

Body:
I have a file full of lines in this format:

1 - 2: 3

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

Body:
    int a,b,c;

    cin >> a;
    cin.ignore(100,'-');
    cin >> b;
    cin.ignore(100,':');
    cin >> c;

    cout << "a = "<< a <<endl;
    cout << "b = "<< b <<endl;
    cout << "c = "<< c <<endl;

Input:

1 - 2: 3

Output:

a = 1

  b = 2

  c = 3

See yourself here : http://www.ideone.com/DT9KJ

Note: this can handle extra spaces also. So you can read even this:

 1     -        2      :      3

Similar topic:

Using ifstream as fscanf


问:
getting cross origin error while calling local Node service from html
I have node service that runs on locahost and i am calling this service in HTML standalone page using ajax GET method.
But this gives me no access control allow origin error please help</p>

答:
This question has already partially been answered here

If you Did write the API yourself, please add the following header to your API:

NodeJS:

```<code>app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
});
</code>```

More detailed information can be find in the stack overflow question that has already been answered.

Body:
This question has already partially been answered here

If you Did write the API yourself, please add the following header to your API:

NodeJS:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
});

More detailed information can be find in the stack overflow question that has already been answered.