问:
C# Streamreader add new line
I have searched for this but every solution I've come across involves regex witch is not a solution for me.

My question is simple, I want the streamreader to add a new line everytime it reads the word "ice". Keep in mind that the streamreader is reading the input as 1 line.

My code is as follow:

```<code>using (StreamReader sr = new StreamReader(stream))
{
    VarrileKeeper.s = sr.ReadToEnd();
    //Console.WriteLine(VarrileKeeper.s);
    if (VarrileKeeper.s.ToString().Contains("ice"))
    {
        //insert newline in string
    }
    sr.Close();
}
</code>```

答:
Something with string.Split and string.Join could reach your goal

```<code>string temp = File.ReadAllText("yourfilename");
var parts = temp.Split(new string[] {"ice"}, StringSplitOptions.None);
VarrileKeeper.s = string.Join("ice"+ Environment.NewLine, parts);
</code>```

but remember that this is indiscriminate on the character sequence ice, meaning that also more complex words will be truncated (venice for example.)

Title: C# Streamreader add new line

Body:
I have searched for this but every solution I've come across involves regex witch is not a solution for me.

My question is simple, I want the streamreader to add a new line everytime it reads the word "ice". Keep in mind that the streamreader is reading the input as 1 line.

My code is as follow:

using (StreamReader sr = new StreamReader(stream))
{
    VarrileKeeper.s = sr.ReadToEnd();
    //Console.WriteLine(VarrileKeeper.s);
    if (VarrileKeeper.s.ToString().Contains("ice"))
    {
        //insert newline in string
    }
    sr.Close();
}

Body:
Something with string.Split and string.Join could reach your goal

string temp = File.ReadAllText("yourfilename");
var parts = temp.Split(new string[] {"ice"}, StringSplitOptions.None);
VarrileKeeper.s = string.Join("ice"+ Environment.NewLine, parts);

but remember that this is indiscriminate on the character sequence ice, meaning that also more complex words will be truncated (venice for example.)


来源: stackexchange

问:
Exporting Windows Resource Monitor Data with Powershell
Problem Definition: We have done some configuration level changes in our web server which is basically a IIS server. We have increased number of threads from default 300 to somewhat 450.

And this changes might crash our server.

So we want to monitor the worker threads and we want to log this to a database periodically.

My Progress So far:

So far I was able to get details with one exe running with below mentioned Powershell command.

(Just replace w3wp.exe with any processes name to get result)

```<code>$name = "w3wp.exe"
$processHandle = (Get-CimInstance Win32_Process -Filter "Name = '$name'").ProcessId
$Threads = Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle = $processHandle"
$threads | Select-Object priority, thread*, User*Time, kernel*Time |
Out-GridView -Title "The $name process has $($threads.count) threads"
</code>```

Issue: In above mentioned PowerShell script it is not able to give me result for exes when w3wp.exe is running with multiple PIDs.

Is there a way we can get result for multiple running exes?

Table should be of

Processor name| PID| Worker Name| No. of Threads|

答:
So, I got an error running your code which I would have expected you to get as well

```<code> Get-CimInstance : Invalid query
 At line:3 char:12
 + $Threads = Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle ...
 +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidArgument: (:) [Get-CimInstance], CimException
     + FullyQualifiedErrorId : HRESULT 0x80041017,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
</code>```

Which makes sense since the -Filter would look like this... as it did for me using chrome.exe as a test. Which is not valid.

```<code>ProcessHandle = 7224 7420 8688 8800 8916 460 10884 7340 10956 6756 14604 13260 9588 18020 22264 11516 17684 12664
</code>```

So I just added in a loop to allow for multiple $processHandles and it seems to be working fine.

```<code>$Threads = $processHandle | Foreach-Object{
    Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle = $_"
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Problem Definition: We have done some configuration level changes in our web server which is basically a IIS server. We have increased number of threads from default 300 to somewhat 450.

And this changes might crash our server.

So we want to monitor the worker threads and we want to log this to a database periodically.

My Progress So far:

So far I was able to get details with one exe running with below mentioned Powershell command.

(Just replace w3wp.exe with any processes name to get result)

$name = "w3wp.exe"
$processHandle = (Get-CimInstance Win32_Process -Filter "Name = '$name'").ProcessId
$Threads = Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle = $processHandle"
$threads | Select-Object priority, thread*, User*Time, kernel*Time |
Out-GridView -Title "The $name process has $($threads.count) threads"

Issue: In above mentioned PowerShell script it is not able to give me result for exes when w3wp.exe is running with multiple PIDs.

Is there a way we can get result for multiple running exes?

Table should be of

Processor name| PID| Worker Name| No. of Threads|

Body:
So, I got an error running your code which I would have expected you to get as well

 Get-CimInstance : Invalid query
 At line:3 char:12
 + $Threads = Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle ...
 +            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidArgument: (:) [Get-CimInstance], CimException
     + FullyQualifiedErrorId : HRESULT 0x80041017,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand

Which makes sense since the -Filter would look like this... as it did for me using chrome.exe as a test. Which is not valid.

ProcessHandle = 7224 7420 8688 8800 8916 460 10884 7340 10956 6756 14604 13260 9588 18020 22264 11516 17684 12664

So I just added in a loop to allow for multiple $processHandles and it seems to be working fine.

$Threads = $processHandle | Foreach-Object{
    Get-CimInstance -Class Win32_Thread -Filter "ProcessHandle = $_"
}


问:
Angular - getting ng-bind to work on nested directives
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

```<code>app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("<span ng-bind='depth'/>");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
</code>```

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>```

答:
Since you don't want to the html(), don't use child.html().

Use the child itself.

Check the documentation here

element

html

Check the snippet below. Added based on the sample snippet in your question

var app = angular.module("app", []);
app.directive("test", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element, $attrs) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
});
app.directive("child", function($compile) {
  function getTemplate(depth) {
      return depth % 2 == 0 ? "<even depth='depth-1'/>" : "<odd depth='depth-1'/>"
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
app.directive("odd", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
})
app.directive("even", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
})
var controller = app.controller("controller", function($scope) {});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 5px 5px 5px 5px !important;
  font-size: 30px;
}

test,
child,
even,
odd {
  padding: 5px 5px 5px 5px;
  margin: 5px 5px 5px 5px;
  border: 1px solid black;
}

test {
  background-color: aliceblue !important;
}

child {
  background-color: beige !important;
}

even {
  background-color: lightgreen !important;
}

odd {
  background-color: lightcoral !important;
}</code>```

  <test depth="4"></test>
```

Body:
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>

Body:
Since you don't want to the html(), don't use child.html().

Use the child itself.

Check the documentation here

element

html

Check the snippet below. Added based on the sample snippet in your question

var app = angular.module("app", []);
app.directive("test", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element, $attrs) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
});
app.directive("child", function($compile) {
  function getTemplate(depth) {
      return depth % 2 == 0 ? "<even depth='depth-1'/>" : "<odd depth='depth-1'/>"
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("<span ng-bind='depth'/>");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
app.directive("odd", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
})
app.directive("even", function($compile) {
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      var child = angular.element("<child depth='depth'/>");
      child = $compile(child)($scope);
      $element.append(child);
    }
  }
})
var controller = app.controller("controller", function($scope) {});

body {
  padding: 5px 5px 5px 5px !important;
  font-size: 30px;
}

test,
child,
even,
odd {
  padding: 5px 5px 5px 5px;
  margin: 5px 5px 5px 5px;
  border: 1px solid black;
}

test {
  background-color: aliceblue !important;
}

child {
  background-color: beige !important;
}

even {
  background-color: lightgreen !important;
}

odd {
  background-color: lightcoral !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<body ng-app="app" ng-controller="controller">
  <test depth="4"></test>
</body>


问:
Build a Web Service API (SOAP) inside MVC app?
Can anyone help me on how to build a web service api (soap) inside an MVC app? WCF is fine :) (initially, WCF is not an option.)

Thank you very much.

答:
You can add a webservice to your mvc app, it (mvc) is asp.net after all.

If it's in the root of your app you can just call it (the webservice), if you put it in a subdirectory i think you have to create an ignore route (like the default one routes.IgnoreRoute("{resource}.axd/{*pathInfo}");), but i'm not sure if the ignore route is necessary.

ContentLicense: CC BY-SA 2.5


问:
A custom domain object isn't being shown while using @ModelAttribute
I am using Springfox and Swagger to generate swagger files. Right now I'm using @ModelAttribute to pull the variables from an object (NetworkCmd) to show as query params in the swagger doc.

I currently have the following controller:

```<code>@RequestMapping(value = "/{product_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseHeader()
public ResponseEntity<?> networkResponse(
    @RequestHeader HttpHeaders headers,
    @PathVariable("product_id")String productId,
    @Valid @ModelAttribute NetworkCmd cmd,
    BindingResult result)
    throws Exception {

    ...
}
</code>```

And here is a sample of NetworkCmd:

```<code>@ItemId
@NotNull(message = "product cannot be null")
@ApiModelProperty(
    value = "testing")
private String product_id;

@ApiModelProperty(
    value = "key",
private String key;

@ApiModelProperty(
    value = "parent")
private Boolean is_parent_id;

@Min(0)
@ApiModelProperty(
    value = "radius")
private double radius = 10d;
</code>```

One of the variables in this class is a custom domain object Nearby.

```<code>private Nearby nearby = null;

public Nearby getNearby() {
    return nearby;
}

public void setNearby(String nearby) throws ParseException {
    this.nearby = Nearby.parse(nearby);
}
</code>```

This is kind of a special variable because it takes in a String, and then parses that string and turns it into the Nearby object.

My problem is that this Nearby variable isn't showing up on the generated swagger document through @ModelAttribute. I'm happy to provide any more information.

答:
One way to get around this problem is to create an alternate type rule in your docket. This way anytime we encounter the nearby type we treat it as a string.</p>

```<code>new Docket(...)
     .directModelSubstitute(Nearby.class, String.class)
</code>```

Body:
I am using Springfox and Swagger to generate swagger files. Right now I'm using @ModelAttribute to pull the variables from an object (NetworkCmd) to show as query params in the swagger doc.

I currently have the following controller:

@RequestMapping(value = "/{product_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseHeader()
public ResponseEntity<?> networkResponse(
    @RequestHeader HttpHeaders headers,
    @PathVariable("product_id")String productId,
    @Valid @ModelAttribute NetworkCmd cmd,
    BindingResult result)
    throws Exception {

    ...
}

And here is a sample of NetworkCmd:

@ItemId
@NotNull(message = "product cannot be null")
@ApiModelProperty(
    value = "testing")
private String product_id;

@ApiModelProperty(
    value = "key",
private String key;

@ApiModelProperty(
    value = "parent")
private Boolean is_parent_id;

@Min(0)
@ApiModelProperty(
    value = "radius")
private double radius = 10d;

One of the variables in this class is a custom domain object Nearby.

private Nearby nearby = null;

public Nearby getNearby() {
    return nearby;
}

public void setNearby(String nearby) throws ParseException {
    this.nearby = Nearby.parse(nearby);
}

This is kind of a special variable because it takes in a String, and then parses that string and turns it into the Nearby object.

My problem is that this Nearby variable isn't showing up on the generated swagger document through @ModelAttribute. I'm happy to provide any more information.

Body:
One way to get around this problem is to create an alternate type rule in your docket. This way anytime we encounter the nearby type we treat it as a string.

new Docket(...)
     .directModelSubstitute(Nearby.class, String.class)


问:
react-native-router-flux: onLeft scene
I'm trying to add onLeft for a scene employeeEdit scene when returning from the scene should the user not wish to make changes to the current selected employee that they'll be able to return to the employee list and the fields will be emptied when going onto Add by using type: 'reset' as if were to save changes. </p>

<p>It seems that the onLeft is not working in this case here in that the function is not actually being executed. </p>

```<code><Router sceneStyle={{ paddingTop: 65 }}>
    <Scene key="auth">
        <Scene key="login" component={LoginForm} title="Please Login" initial />
    </Scene>

    <Scene key="main">
        <Scene
            onRight={() => Actions.employeeCreate()}
            rightTitle="Add"
            key="employeeList"
            component={EmployeeList}
            title="Employees"
            initial
        />
        <Scene
            key="employeeCreate"
            component={EmployeeCreate}
            title="Create Employee"
        />
        <Scene
            onLeft={() => Actions.employeeList({ type: 'reset' })}
            key="employeeEdit"
            component={EmployeeEdit}
            title="Edit Employee"
        />
    </Scene>
</Router>
</code>```

答:
A longer approach.

Using componentWillUnmount, this is effective when leaving the component i.e. EmployeeEdit

```<code>componentWillUnmount () {
    this.props.employeeInitial();
}
</code>```

and this can then call a prop of gigInitial; having an action which will return a dispatch say of type: 'EMPLOYEE_INITIAL'

```<code>export const employeeInitial = () => {
    return (dispatch) => {
        dispatch({ type: EMPLOYEE_INITIAL });
    };
};
</code>```

which at the EmployeeFormReducer will then just return INITIAL_STATE

```<code>case EMPLOYEE_INITIAL:
    return INITIAL_STATE;
</code>```

Title: react-native-router-flux: onLeft scene

Body:
I'm trying to add onLeft for a scene employeeEdit scene when returning from the scene should the user not wish to make changes to the current selected employee that they'll be able to return to the employee list and the fields will be emptied when going onto Add by using type: 'reset' as if were to save changes.

It seems that the onLeft is not working in this case here in that the function is not actually being executed.

<Router sceneStyle={{ paddingTop: 65 }}>
    <Scene key="auth">
        <Scene key="login" component={LoginForm} title="Please Login" initial />
    </Scene>

    <Scene key="main">
        <Scene
            onRight={() => Actions.employeeCreate()}
            rightTitle="Add"
            key="employeeList"
            component={EmployeeList}
            title="Employees"
            initial
        />
        <Scene
            key="employeeCreate"
            component={EmployeeCreate}
            title="Create Employee"
        />
        <Scene
            onLeft={() => Actions.employeeList({ type: 'reset' })}
            key="employeeEdit"
            component={EmployeeEdit}
            title="Edit Employee"
        />
    </Scene>
</Router>

Body:
A longer approach.

Using componentWillUnmount, this is effective when leaving the component i.e. EmployeeEdit

componentWillUnmount () {
    this.props.employeeInitial();
}

and this can then call a prop of gigInitial; having an action which will return a dispatch say of type: 'EMPLOYEE_INITIAL'

export const employeeInitial = () => {
    return (dispatch) => {
        dispatch({ type: EMPLOYEE_INITIAL });
    };
};

which at the EmployeeFormReducer will then just return INITIAL_STATE

case EMPLOYEE_INITIAL:
    return INITIAL_STATE;


问:
rails_admin searchable association
I am using rails_admin together with globalize3 and cannot get searchable associations to work. Here are the models (Person has_one/belongs_to Name has_many/belongs_to NameTranslation):

```<code>class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person
end

class Name < ActiveRecord::Base
  belongs_to :person, inverse_of: :name
  translates :first_name, :last_name
  has_many :name_translations, inverse_of: :name, dependent: :destroy
end

class NameTranslation < ActiveRecord::Base
  belongs_to :name, inverse_of: :name_translations
end
</code>```

The NameTranslation model is coming from globalize3, it contains the same attributes as name (first_name and last_name) plus locale and name_id,.

In config/initializers/rails_admin.rb I have

```<code>config.model Person do
  list do
    field :name do
      searchable name_translations: :last_name
    end
  end
end
</code>```

Then, in the GUI, when I add a filter on name, I get:

```<code>SQLite3::SQLException: no such column: name_translations.last_name: SELECT  "people".* FROM "people"  WHERE (((name_translations.last_name LIKE '%freud%'))) ORDER BY people.id desc LIMIT 20 OFFSET 0
</code>```

Obviously, rails_admin is looking for a column named name_translations.last_name in people instead of joining/including names and name_translations - why?

What I need rails_admin to do is this, working in irb:

```<code>>> Person.joins( name: :name_translations ).where('name_translations.last_name like "test"')
</code>```

which generates the following SQL:

```<code>SELECT "people".* FROM "people" INNER JOIN "names" ON "names"."person_id" = "people"."id" INNER JOIN "name_translations" ON "name_translations"."name_id" = "names"."id" WHERE (name_translations.last_name like "test")
</code>```

Can this be done in rails_admin? Thanks for your help...

答:
I had a similar problem with a has one relationship.
The way I solved it was to set a default_scope on the model and join it with the associated table (it is was the only way I could get rails admin to join these two tables).

I also had to set queryable true on the associated field.

Imagine that you had to search only inside the name association, then here's how it would work:

```<code>class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person

  default_scope { eager_load(:name) }
end

config.model Person do
  list do
    field :name do
      queryable true
      searchable [:column1, :column2, ..]
    end
  end
end
</code>```

However, you need to search through the has many association and I don't know whether that approach would still work, but here's a guess:

```<code>class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person
  has_many :name_translations, through: :name

  default_scope { eager_load(:name_translations) }
end

config.model Person do
  list do
    field :name_translations do
      queryable true
      searchable :last_name
    end
  end
end
</code>```

Title: rails_admin searchable association

Body:
I am using rails_admin together with globalize3 and cannot get searchable associations to work. Here are the models (Person has_one/belongs_to Name has_many/belongs_to NameTranslation):

class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person
end

class Name < ActiveRecord::Base
  belongs_to :person, inverse_of: :name
  translates :first_name, :last_name
  has_many :name_translations, inverse_of: :name, dependent: :destroy
end

class NameTranslation < ActiveRecord::Base
  belongs_to :name, inverse_of: :name_translations
end

The NameTranslation model is coming from globalize3, it contains the same attributes as name (first_name and last_name) plus locale and name_id,.

In config/initializers/rails_admin.rb I have

config.model Person do
  list do
    field :name do
      searchable name_translations: :last_name
    end
  end
end

Then, in the GUI, when I add a filter on name, I get:

SQLite3::SQLException: no such column: name_translations.last_name: SELECT  "people".* FROM "people"  WHERE (((name_translations.last_name LIKE '%freud%'))) ORDER BY people.id desc LIMIT 20 OFFSET 0

Obviously, rails_admin is looking for a column named name_translations.last_name in people instead of joining/including names and name_translations - why?

What I need rails_admin to do is this, working in irb:

>> Person.joins( name: :name_translations ).where('name_translations.last_name like "test"')

which generates the following SQL:

SELECT "people".* FROM "people" INNER JOIN "names" ON "names"."person_id" = "people"."id" INNER JOIN "name_translations" ON "name_translations"."name_id" = "names"."id" WHERE (name_translations.last_name like "test")

Can this be done in rails_admin? Thanks for your help...

Body:
I had a similar problem with a has one relationship.
The way I solved it was to set a default_scope on the model and join it with the associated table (it is was the only way I could get rails admin to join these two tables).

I also had to set queryable true on the associated field.

Imagine that you had to search only inside the name association, then here's how it would work:

class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person

  default_scope { eager_load(:name) }
end

config.model Person do
  list do
    field :name do
      queryable true
      searchable [:column1, :column2, ..]
    end
  end
end

However, you need to search through the has many association and I don't know whether that approach would still work, but here's a guess:

class Person < ActiveRecord::Base
  has_one :name, inverse_of: :person
  has_many :name_translations, through: :name

  default_scope { eager_load(:name_translations) }
end

config.model Person do
  list do
    field :name_translations do
      queryable true
      searchable :last_name
    end
  end
end


问:
How to solve Bootstrap navbar hidden
In the output below I can't see my navbar menu correctly. Where is the problem?

Please anyone help me.

I just changed my code bootstrap.css and make this line comment the line name: padding-bottom.

```<code><nav class="navbar navbar-inverse" style="height:120px;">
  <div class="container" style="padding-top:30px;">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
        <a><img class="pull-left" src="images/mt-626_header_logo01.png"></a>
      <a class="navbar-brand" href="#"><strong style="color:white">SOFT</strong><strong style="color:#3EC7C2">APP</strong></a>
    </div>
    <div class="collapse navbar-collapse" id="navbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">BLOG</a></li>
        <li><a href="#">CONTACTS</a></li>
      </ul>
    </div>
  </div>
</nav>

<!-- First Container -->
<div class="container-fluid fcontaner">
    <div class="row">
        <div class="col-md-12">
            <div class="col-md-6">
                <img src="images/mt-0626-img.png" style="height:100%;width:100%"/>
            </div>
            <div class="col-md-6">
                <h1 style="padding-top:150px"><strong style="color:white;">SOFT</strong><strong style="color:">APP</strong></h1>
                <h1>INNOVATIVE SOLUTIONS</h1>
                <h3 style="color:white;padding-bottom:50px;">Innovative solutions delivering a product, which <br>includes tomorrow’s technology – already today!</h3>
                <a href="#"><img src="images/mt-0626-img2.png"></a>
            </div>
        </div>
    </div>
</div>
</code>```

答:
You have added inline style here  just remove it your problem will solve.

See Demo

Title: How to solve Bootstrap navbar hidden

Body:
In the output below I can't see my navbar menu correctly. Where is the problem?

Please anyone help me.

I just changed my code bootstrap.css and make this line comment the line name: padding-bottom.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">

      </button>

      SOFTAPP

HOME

ABOUT

SERVICES

BLOG

CONTACTS

SOFTAPP

INNOVATIVE SOLUTIONS

Innovative solutions delivering a product, which
includes tomorrow’s technology – already today!

Body:
You have added inline style here <nav class="navbar navbar-inverse" style="height:120px;"> just remove it your problem will solve.

See Demo


问:
Page redirection using if statement with javascript and php
I want to redirect a php page using php if statement. I did the redirect code with javascript but its not working.

Can someone please help me modify my code if i missed something out or help me out with a better solution.

Below is the code;

```<code>$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){'<script>window.location.href = "http://www.url.com/login.php";
</script>
';}
else {echo "NOT WORKING";}
</code>```

I tried this too

```<code>$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){header("Location: www.url.com/login.php");}
else {echo "NOT WORKING";}
</code>```

答:
You can use header function :

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

```<code><?php
    $vbi = 'blocked';
    if ($vbi == "blocked")
    {
      header("Location: http://www.yourwebsite.com/user.php");
    }
    else
    {
      echo "NOT WORKING";
    }
?>
</code>```

see this link for more information and discuss :

How to make a redirect in PHP?

Body:
I want to redirect a php page using php if statement. I did the redirect code with javascript but its not working.

Can someone please help me modify my code if i missed something out or help me out with a better solution.

Below is the code;

$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){'
';}
else {echo "NOT WORKING";}

I tried this too

$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){header("Location: www.url.com/login.php");}
else {echo "NOT WORKING";}

Body:
You can use header function :

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<?php
    $vbi = 'blocked';
    if ($vbi == "blocked")
    {
      header("Location: http://www.yourwebsite.com/user.php");
    }
    else
    {
      echo "NOT WORKING";
    }
?>

see this link for more information and discuss :

How to make a redirect in PHP?


问:
add column to table and set value based on the value of another column
I have encountered the following issue: I have a table with several columns, now I need to add a new column to this table and then fill it with the encrypted (md5) value of another column.

1)

```<code>ALTER TABLE myTable ADD md5_city VARCHAR(255);
</code>```

2)

```<code>"UPDATE myTable SET md5_city = " . md5($cityValue) . ";"
</code>```

Is there a better way to do this?

答:
Your method actually adds the column into the table.  One alternative is to calculate it on the fly:

```<code>ALTER TABLE myTable ADD md5_city as md5(col);
</code>```

This calculates the value only when you need it.

Body:
I have encountered the following issue: I have a table with several columns, now I need to add a new column to this table and then fill it with the encrypted (md5) value of another column.

1)

ALTER TABLE myTable ADD md5_city VARCHAR(255);

2)

"UPDATE myTable SET md5_city = " . md5($cityValue) . ";"

Is there a better way to do this?

Body:
Your method actually adds the column into the table.  One alternative is to calculate it on the fly:

ALTER TABLE myTable ADD md5_city as md5(col);

This calculates the value only when you need it.


问:
Process.Start wait for excel to exit error
Here is my code:

```<code>Dim sTemplateSharedPath As String = sSharedDrive & ":\Excel Templates\ImportTemplate.xlsx"
Dim objProcess As System.Diagnostics.Process
                    Try
                        objProcess = New System.Diagnostics.Process()
                        objProcess.StartInfo.FileName = sTemplateSharedPath
                        objProcess.Start()
                        objProcess.WaitForExit()
                    Catch
                        MessageBox.Show("Could not start process " & sTemplateSharedPath, "Error")
                    End Try
</code>```

Excel opens up the file I requested, but the system crashes at the objProcess.WaitForExit() part.The error I get is the following:

No process is associated with this object.

I want the system to open the template, have the user add his/her data, save and close MS Excel. Once the system detects the process is not running anymore, point to the sTemplateSharedPath and import said changes into the system. It's fine if the UI of the app is non responsive while the user is editing the excel document.

I have added the following to the code above before I start the process:

```<code>objProcess.StartInfo.UseShellExecute = false
</code>```

But I then get this error:

the specified executable is not a valid application for this os platform

I do hope someone will be able to asssist me with this issue.

Thanks in advance.

答:
Did you try to open an excel instance first with the file as parameter?

```<code>Dim sSharedDrive = "C"
    Dim sTemplateSharedPath As String = "excel.exe"
    Dim FileParam As String = ControlChars.Quote + sSharedDrive + ":\test new\test.xlsx" + ControlChars.Quote
    Dim objProcess As System.Diagnostics.Process
    Try
        objProcess = New System.Diagnostics.Process()
        objProcess.StartInfo.FileName = sTemplateSharedPath
        objProcess.StartInfo.Arguments = FileParam
        objProcess.Start()
        objProcess.WaitForExit()
    Catch
        Console.WriteLine("Could not start process " & sTemplateSharedPath, "Error")
        Console.ReadLine()
    End Try
</code>```

I dont know if the .xlsx filetype is definied in your os. Can you open the .xlsx manually ?

Body:
Here is my code:

Dim sTemplateSharedPath As String = sSharedDrive & ":\Excel Templates\ImportTemplate.xlsx"
Dim objProcess As System.Diagnostics.Process
                    Try
                        objProcess = New System.Diagnostics.Process()
                        objProcess.StartInfo.FileName = sTemplateSharedPath
                        objProcess.Start()
                        objProcess.WaitForExit()
                    Catch
                        MessageBox.Show("Could not start process " & sTemplateSharedPath, "Error")
                    End Try

Excel opens up the file I requested, but the system crashes at the objProcess.WaitForExit() part.The error I get is the following:

No process is associated with this object.

I want the system to open the template, have the user add his/her data, save and close MS Excel. Once the system detects the process is not running anymore, point to the sTemplateSharedPath and import said changes into the system. It's fine if the UI of the app is non responsive while the user is editing the excel document.

I have added the following to the code above before I start the process:

objProcess.StartInfo.UseShellExecute = false

But I then get this error:

the specified executable is not a valid application for this os platform

I do hope someone will be able to asssist me with this issue.

Thanks in advance.

Body:
Did you try to open an excel instance first with the file as parameter?

Dim sSharedDrive = "C"
    Dim sTemplateSharedPath As String = "excel.exe"
    Dim FileParam As String = ControlChars.Quote + sSharedDrive + ":\test new\test.xlsx" + ControlChars.Quote
    Dim objProcess As System.Diagnostics.Process
    Try
        objProcess = New System.Diagnostics.Process()
        objProcess.StartInfo.FileName = sTemplateSharedPath
        objProcess.StartInfo.Arguments = FileParam
        objProcess.Start()
        objProcess.WaitForExit()
    Catch
        Console.WriteLine("Could not start process " & sTemplateSharedPath, "Error")
        Console.ReadLine()
    End Try

I dont know if the .xlsx filetype is definied in your os. Can you open the .xlsx manually ?


问:
Handle multiple connections in Flask API
I'm writing a simple internal REST API for our solution using Flask, serving JSON objects through get calls (including authentication). We have multiple backends to fetch data from. From what I understand these should be connected to in a function decorated with @app.before_request and assigned to the g global for use in the specific route being requested. It's not a pattern I'm used to.

Here is a toy example of what I'm doing:

```<code>@app.before_request
def before_request():
    g.some_conn_a = create_connection('a')
    g.some_conn_b = create_connection('b')
    g.some_client = create_client()

@app.route('/get_some_data')
@requires_auth
def get_some_data():
    # Fetch something from all connections in g
    payload = ... # Construct payload using above connections
    return jsonify(payload)

@app.route('/get_some_other_data')
@requires_auth
def get_some_other_data():
    # Fetch something from maybe just g.some_conn_b
    payload = ... # Construct payload using g.some_conn_b
    return jsonify(payload)
</code>```

This seems wasteful to me if the user makes a request for data residing in only one or two of these connections/clients, like in the get_some_other_data route example.

I'm considering just making the connections/clients in the route functions instead, or load it lazily. What's the "correct" way? I hope it isn't to make a new module, that seems extreme for what I'm doing.

答:
Riffing on the Flask docs Database Connections example
you could modify get_db() to accept an argument for each of your multiple connections.

```<code>def get_db(conn):
    """Open specificied connection if none yet for the current app context. """
    if conn == 'some_conn_a':
        if not hasattr(g, 'some_conn_a'):
            g.some_conn_a = create_connection('a')
        db = g.some_conn_a
    elif conn == 'some_conn_b':
        if not hasattr(g, 'some_conn_b'):
            g.some_conn_b = create_connection('b')
        db = g.some_conn_b
    elif conn == 'some_client':
        if not hasattr(g, 'some_client'):
            g.some_client = create_client()
        db = g.some_client
    else:
        raise Exception("Unknown connection: %s" % conn)

    return db

@app.teardown_appcontext
def close_db(error):
    """Closes the db connections. """
    if hasattr(g, 'some_conn_a'):
        g.some_conn_a.close()
    if hasattr(g, 'some_conn_b'):
        g.some_conn_b.close()
    if hasattr(g, 'some_client'):
        g.some_client.close()
</code>```

Then you could query each connection as needed:

```<code>@app.route('/get_some_data')
def get_some_data():
    data_a = get_db('some_conn_a').query().something()
    data_b = get_db('some_conn_b').query().something()
    data_c = get_db('some_client').query().something()
    payload = {'a': data_a, 'b': data_b, 'c': data_c}
    return jsonify(payload)
</code>```

The get_db() pattern is preferred over the before_request pattern for lazy loading database connections. The docs examples for Flask 0.11 and up utilize the get_db() pattern to a larger extent.

Body:
I'm writing a simple internal REST API for our solution using Flask, serving JSON objects through get calls (including authentication). We have multiple backends to fetch data from. From what I understand these should be connected to in a function decorated with @app.before_request and assigned to the g global for use in the specific route being requested. It's not a pattern I'm used to.

Here is a toy example of what I'm doing:

@app.before_request
def before_request():
    g.some_conn_a = create_connection('a')
    g.some_conn_b = create_connection('b')
    g.some_client = create_client()

@app.route('/get_some_data')
@requires_auth
def get_some_data():
    # Fetch something from all connections in g
    payload = ... # Construct payload using above connections
    return jsonify(payload)

@app.route('/get_some_other_data')
@requires_auth
def get_some_other_data():
    # Fetch something from maybe just g.some_conn_b
    payload = ... # Construct payload using g.some_conn_b
    return jsonify(payload)

This seems wasteful to me if the user makes a request for data residing in only one or two of these connections/clients, like in the get_some_other_data route example.

I'm considering just making the connections/clients in the route functions instead, or load it lazily. What's the "correct" way? I hope it isn't to make a new module, that seems extreme for what I'm doing.

Body:
Riffing on the Flask docs Database Connections example
you could modify get_db() to accept an argument for each of your multiple connections.

def get_db(conn):
    """Open specificied connection if none yet for the current app context. """
    if conn == 'some_conn_a':
        if not hasattr(g, 'some_conn_a'):
            g.some_conn_a = create_connection('a')
        db = g.some_conn_a
    elif conn == 'some_conn_b':
        if not hasattr(g, 'some_conn_b'):
            g.some_conn_b = create_connection('b')
        db = g.some_conn_b
    elif conn == 'some_client':
        if not hasattr(g, 'some_client'):
            g.some_client = create_client()
        db = g.some_client
    else:
        raise Exception("Unknown connection: %s" % conn)

    return db

@app.teardown_appcontext
def close_db(error):
    """Closes the db connections. """
    if hasattr(g, 'some_conn_a'):
        g.some_conn_a.close()
    if hasattr(g, 'some_conn_b'):
        g.some_conn_b.close()
    if hasattr(g, 'some_client'):
        g.some_client.close()

Then you could query each connection as needed:

@app.route('/get_some_data')
def get_some_data():
    data_a = get_db('some_conn_a').query().something()
    data_b = get_db('some_conn_b').query().something()
    data_c = get_db('some_client').query().something()
    payload = {'a': data_a, 'b': data_b, 'c': data_c}
    return jsonify(payload)

The get_db() pattern is preferred over the before_request pattern for lazy loading database connections. The docs examples for Flask 0.11 and up utilize the get_db() pattern to a larger extent.


问:
In UINavigationController, I have to use two rightBarButtonItem with Image in swift
In my Application, i have to use two rightBarButtonItem in UINavigationController with image in swift 3.0, I'm posting the Image below,

In the given image, i'm very worried about Create Account and Login rightBarbuttonItem's image, how do i add those images and the border between the buttons exactly like the given sample.

Any help will be appreciable.

答: What my work around is to add a UIView inside of navigation bar's title view and expend it as much as required and then you can place as much control as you want.


问:
Can't replace string in a text file
Following this thread:

I have a text file storing usernames password and bestscore for that user.

Trying to make a simple quiz game. I have a signup panel and when user signs up I store the data in this file and make his best score 0 for the new user.

The text file format for every single line is

{username} {password} {bestScore}

And when the user makes more than his bestScore i try to replace the actual score in the text file with the bestScore.

Well, back to that thread. I did everything line @meriton posted but the text file still hadn't changed. Here is my code:

```<code>if (gameData.getBestScore() < gameData.getScore()) {
            int oldBestScore = gameData.getBestScore();
            String oldLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + oldBestScore;
            gameData.setBestScore(gameData.getScore());
            String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();

            // TODO replace the points in the text file
            //first method
            /*try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
                String line = br.readLine();

                while (line != null) {
                    if (line.contains(gameData.getCurrentUser())) {
                        String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
                        line = line.replace(line, newLine);
                        break;
                    }
                    line = br.readLine();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/

            //second method
            Path path = Paths.get("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt");
            Charset charset = StandardCharsets.UTF_8;

            String content = null;
            try {
                content = new String(Files.readAllBytes(path), charset);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(content);
            content = content.replaceAll(oldLine, newLine);
            System.out.println(content);

            gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Congratulations! New High Score: " + gameData.getBestScore() + "</h3></html>");
        }
        else {
            gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Your score: " + gameData.getBestScore() + "</h3></html>");
        }
    }
</code>```

As you can see I println before editing the content and after that to the console and everything is ok there. The old content is replaced with the new one but the file is not updated with the new content.

Also i tried to do it my way you can see the commented section in my code under the //first method comment. That way still didn't work.

答:
Try to write the content of the variable into the source file.

```<code>Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
</code>```

You have just loaded the content of file in memory and applied the replaceAll on the content variable.

But you must save change into source file.

Title: Can't replace string in a text file

Body:
Following this thread:

I have a text file storing usernames password and bestscore for that user.

Trying to make a simple quiz game. I have a signup panel and when user signs up I store the data in this file and make his best score 0 for the new user.

The text file format for every single line is

{username} {password} {bestScore}

And when the user makes more than his bestScore i try to replace the actual score in the text file with the bestScore.

Well, back to that thread. I did everything line @meriton posted but the text file still hadn't changed. Here is my code:

if (gameData.getBestScore() < gameData.getScore()) {
            int oldBestScore = gameData.getBestScore();
            String oldLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + oldBestScore;
            gameData.setBestScore(gameData.getScore());
            String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();

            // TODO replace the points in the text file
            //first method
            /*try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
                String line = br.readLine();

                while (line != null) {
                    if (line.contains(gameData.getCurrentUser())) {
                        String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
                        line = line.replace(line, newLine);
                        break;
                    }
                    line = br.readLine();
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/

            //second method
            Path path = Paths.get("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt");
            Charset charset = StandardCharsets.UTF_8;

            String content = null;
            try {
                content = new String(Files.readAllBytes(path), charset);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(content);
            content = content.replaceAll(oldLine, newLine);
            System.out.println(content);

            gameOverPanel.gameOverLabel.setText("
You didn't answer correctly!

The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "

Congratulations! New High Score: " + gameData.getBestScore() + "
");
        }
        else {
            gameOverPanel.gameOverLabel.setText("
You didn't answer correctly!

The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "

Your score: " + gameData.getBestScore() + "
");
        }
    }

As you can see I println before editing the content and after that to the console and everything is ok there. The old content is replaced with the new one but the file is not updated with the new content.

Also i tried to do it my way you can see the commented section in my code under the //first method comment. That way still didn't work.

Body:
Try to write the content of the variable into the source file.

Files.write(path, content.getBytes(), StandardOpenOption.CREATE);

You have just loaded the content of file in memory and applied the replaceAll on the content variable.

But you must save change into source file.


问:
JQuery hide Class if other class is visible or shown
Found similar questions but nothing that covers exactly what I need.  I kept it simple in my example and I want to use JQuery.

I have two classes.  I want to hide the "filter" div if the "category" div is shown on page load.  There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

```<code><script language="text/javascript">
if(!$(this).hasClass("category")){
$('filter').css('display', 'none');
}
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>
</code>```

Thanks in advance!

答:
```<code>var $filter = $(".filter");
var $category = $(".category");

$category.is(":visible") ? $filter.hide() : $filter.show();
</code>```

Body:
Found similar questions but nothing that covers exactly what I need.  I kept it simple in my example and I want to use JQuery.

I have two classes.  I want to hide the "filter" div if the "category" div is shown on page load.  There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

By Category

By Custom Filter

Thanks in advance!


问:
How do I print oldest file and include its timestamp from a directory via UNIX
I have a number of files in a directory, and I would like to print the oldest file along with its timestamp.

The following command is giving me the correct filename, however it does not show me the timestamp.

```<code>ls -ltr | head -1
</code>```

EDIT: non-gnu based system.

答:
None of the answers so far (aside from anubhava's edit, which I either overlooked or was added after I last looked) accommodate file names that contain newlines. However, you don't actually need to see the timestamp for each file to determine which one is the oldest in bash. There is a conditional operator, -ot, to determine if one file is older than another.

```<code>oldest=
for f in *; do
  [[ -z $oldest || $f -ot $oldest ]] && oldest=$f
done
ts=$(stat -f %m "$oldest")  # Get the timestamp for the oldest file
</code>```

stat is not covered by the POSIX specification, so you'll need to consult your documentation to determine the correct call for your system. (BSD stat shown here.)

Body:
I have a number of files in a directory, and I would like to print the oldest file along with its timestamp.

The following command is giving me the correct filename, however it does not show me the timestamp.

ls -ltr | head -1

EDIT: non-gnu based system.

Body:
None of the answers so far (aside from anubhava's edit, which I either overlooked or was added after I last looked) accommodate file names that contain newlines. However, you don't actually need to see the timestamp for each file to determine which one is the oldest in bash. There is a conditional operator, -ot, to determine if one file is older than another.

oldest=
for f in *; do
  [[ -z $oldest || $f -ot $oldest ]] && oldest=$f
done
ts=$(stat -f %m "$oldest")  # Get the timestamp for the oldest file

stat is not covered by the POSIX specification, so you'll need to consult your documentation to determine the correct call for your system. (BSD stat shown here.)


问:
How to take full customer export from hybris
How can we take full hybris customer export.
i wrote an impex to export the data but there are 2 million records in database so impex is not working.Please suggest a way.</p>

答:
Impex should work, maybe it takes some time but it shouldn't failed (and if it's failing you should post the error if you want to be helped).

You have to do it by code for better perfomance, using a flexibleSearch.

```<code>String flexiString = "SELECT * from {Customer}"
FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(flexiString);
flexibleSearchQuery.setResultClassList(Arrays.asList(CustomerModel.class));

final SearchResult<CustomerModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);

List<CustomerModel> results = searchResult.getResult();
if(!results.isEmpty()){
    //Iterate over CustomerModel and append what you want in a file.
}
</code>```

There is also a old method in a manager that could be used but I don't recommend it because manager are likely to be deprecated because they use jalo classes (some class are deprecated some aren't).

```<code>import de.hybris.platform.jalo.user.*
import de.hybris.platform.jalo.type.*
import de.hybris.platform.core.model.user.*

Collection<Customer> users=UserManager.getInstance().findUsers(TypeManager.getInstance().getComposedType(Customer.class),null,null,null)

for(Customer cust : users){
    //Iterate over Customer and append what you want in a file.
}
</code>```

Body:
Impex should work, maybe it takes some time but it shouldn't failed (and if it's failing you should post the error if you want to be helped).

You have to do it by code for better perfomance, using a flexibleSearch.

String flexiString = "SELECT * from {Customer}"
FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(flexiString);
flexibleSearchQuery.setResultClassList(Arrays.asList(CustomerModel.class));

final SearchResult<CustomerModel> searchResult = flexibleSearchService.search(flexibleSearchQuery);

List<CustomerModel> results = searchResult.getResult();
if(!results.isEmpty()){
    //Iterate over CustomerModel and append what you want in a file.
}

There is also a old method in a manager that could be used but I don't recommend it because manager are likely to be deprecated because they use jalo classes (some class are deprecated some aren't).

import de.hybris.platform.jalo.user.*
import de.hybris.platform.jalo.type.*
import de.hybris.platform.core.model.user.*

Collection<Customer> users=UserManager.getInstance().findUsers(TypeManager.getInstance().getComposedType(Customer.class),null,null,null)

for(Customer cust : users){
    //Iterate over Customer and append what you want in a file.
}


问:
I want to know how to store some data in Matlab which I can later call from Java code?
I want to store some data generated via Matlab and want to access it from Java code base for further processing. Please let me know how I can do it ?</p>

答: Export Data from Matlab to Text Files</p>

Body: Export Data from Matlab to Text Files


问:
Saving the toggle condition
I have written a code for the flip switch but the state always changes while refreshing the page:

答:
I'll assume you are trying to replace the Ajax post request you have with something else.

My suggestion would be to use a cookie which will save some information locally for js to use.

Firstly, add jQuery & jQuery Cookie to the top of your webpage like this (within the  tag):

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js.js" charset="utf-8"></script>
</code>```

Then, in your javascript file, do the following:

```<code>(function($) {
  // Grabs cookie and puts into a js variable.
  var toggled = $.cookie('toggled');

//  On click of checkbox, check if set/unset. Then set cookie to true/false.

  $('#switch').change(function()) {
      if($(this).is(':checked')) { // If set to true, set toggled to true.
        $.cookie('toggled', true, { expires: 1, path: '/' });
      } else { // Else, set to false.
        $.cookie('toggled', null, { expires: 1, path: '/' });
      }
  }

})(jQuery);
</code>```

You'll need to then check the toggled cookie on refresh and add behaviour to check the box if toggled is true:

```<code>if(toggled == 'true') { //If cookie set to true...
 $('#switch').attr('checked','checked').flipswitch("refresh") // Flip the switch (Important for jquery mobile).
}
</code>```

Please see jsFiddle for a working example.

I hope this helps.

Title: Saving the toggle condition

Body:
I'll assume you are trying to replace the Ajax post request you have with something else.

My suggestion would be to use a cookie which will save some information locally for js to use.

Firstly, add jQuery & jQuery Cookie to the top of your webpage like this (within the <head> tag):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js.js" charset="utf-8"></script>

Then, in your javascript file, do the following:

(function($) {
  // Grabs cookie and puts into a js variable.
  var toggled = $.cookie('toggled');

//  On click of checkbox, check if set/unset. Then set cookie to true/false.

  $('#switch').change(function()) {
      if($(this).is(':checked')) { // If set to true, set toggled to true.
        $.cookie('toggled', true, { expires: 1, path: '/' });
      } else { // Else, set to false.
        $.cookie('toggled', null, { expires: 1, path: '/' });
      }
  }

})(jQuery);

You'll need to then check the toggled cookie on refresh and add behaviour to check the box if toggled is true:

if(toggled == 'true') { //If cookie set to true...
 $('#switch').attr('checked','checked').flipswitch("refresh") // Flip the switch (Important for jquery mobile).
}

Please see jsFiddle for a working example.

I hope this helps.


问:
How can I do role based access for the pages using AngularJS?
I want to do a role based access for the pages in AngularJS.

Based on the role pages should be shown to the user.

Can any give me an example? Which should be a best solution.

答:
To access the page based on the role is very easy.

Suppose if the web/dashboard have three roles like admin, support, employee.

assign the field as userrole to the users.

Now assign the roles for those pages as ng-if="userrole=='admin'" or vice versa

now based on the roles the pages are accessible


问:
php: edit selected "select" on button click
I have a select (dropdown) box. On each button click, I'd like it to load previously saved position. My code is:

```<code><select name="myVariables" style="width:150px">
<?php
foreach ( $variables as $var ) {
    echo "<option value=\"" . $var . "\"". $var . " </option>";}
?>
</select>
</code>```

I have a variable $previouslySelected, and every time the button is clicked, this variable can change. I'd like to also change the currently selected option in the select box to the same value. I've tried with:

```<code>echo "<option value=\"" . $var . "\" <?=$previouslySelected==$var ? ' selected=\"selected\"' : '';?\>>". $var . " </option>";}
</code>```

but this doesn't seem to work.

Also, I've tried this but it only works the first time.

答:
How do you submit the form. With GET or POST?

With GET, than you must take the submitted value in this way:

```<code>$previouslySelected = isset($_GET['myVariables']) ? $_GET['myVariables'] : '';
</code>```

Otherwise with POST:

```<code>$previouslySelected = isset($_POST['myVariables']) ? $_POST['myVariables'] : '';
</code>```

In PHP 7 you can also do:

```<code>$previouslySelected = $_POST['myVariables'] ?? '';
</code>```

EDIT: Write your echo more readable.

```<code>$selected = ($previouslySelected === $var) ? ' selected="selected"' : '';
echo '<option value="' . $var . '" ' . $selected . '>' . $var . '</option>';
</code>```

Body:
I have a select (dropdown) box. On each button click, I'd like it to load previously saved position. My code is:

<select name="myVariables" style="width:150px">
<?php
foreach ( $variables as $var ) {
    echo "<option value=\"" . $var . "\"". $var . " </option>";}
?>
</select>

I have a variable $previouslySelected, and every time the button is clicked, this variable can change. I'd like to also change the currently selected option in the select box to the same value. I've tried with:

echo "<option value=\"" . $var . "\" <?=$previouslySelected==$var ? ' selected=\"selected\"' : '';?\>>". $var . " </option>";}

but this doesn't seem to work.

Also, I've tried this but it only works the first time.

Body:
How do you submit the form. With GET or POST?

With GET, than you must take the submitted value in this way:

$previouslySelected = isset($_GET['myVariables']) ? $_GET['myVariables'] : '';

Otherwise with POST:

$previouslySelected = isset($_POST['myVariables']) ? $_POST['myVariables'] : '';

In PHP 7 you can also do:

$previouslySelected = $_POST['myVariables'] ?? '';

EDIT: Write your echo more readable.

$selected = ($previouslySelected === $var) ? ' selected="selected"' : '';
echo '<option value="' . $var . '" ' . $selected . '>' . $var . '</option>';


问:
How to avoid overflow in realloc?
One can safely allocate x elements of size y in C by using calloc(x, y) and calloc() will take care of the multiplication x*y.

However realloc() for example only takes the new size as parameter and I was wondering how I could safely realloc x*y bytes using realloc().

What if x*y doesn't fit in size_t? How does calloc() handle this?

答:
The short answer is that you can't do it safely.   The most you can do is limit the amount of memory you attempt to allocate so it does not exceed SIZE_MAX.

SIZE_MAX is the maximum value that can be produced by the sizeof operator.

Every data type in C must have a size that can be computed using sizeof, including arrays, and any contiguous block of memory allocated using malloc(), calloc(), or realloc().

If x*y is mathematically greater than SIZE_MAX, then it is not possible to allocate that amount of memory by any means.   Even if the underlying system supports that, the C program will not be able to use that memory block entirely.

There is also a concern that computing x*y (assuming x and y are of type size_t) will use modulo arithmetic, so will actually give the result mathematically equivalent to (x*y)%(SIZE_MAX + 1).

Title: How to avoid overflow in realloc?


问:
Creation of Socket instance blocks thread for random time if no connection available
Trying to open socket connection in separate thread by calling this:

```<code>Socket sc = sc = new Socket(address, Integer. parseInt(port));
</code>```

But there is a problem, if there is no active internet connection this thread is blocking, on my htc hero 2.1 for 30 seconds, and my android emulator 2.2 for 2 minutes.

I tryed to use this method before opening connection:

```<code>public static boolean isOnline()
{
             ConnectivityManager cm = (ConnectivityManager) app.getInstance().getSystemService(Context. CONNECTIVITY_SERVICE);
             if(null != cm.getActiveNetworkInfo())
                   return cm.getActiveNetworkInfo().isConnectedOrConnecting();
             return false ;
}

public void run()
{
    if(!isOnline())
        throw new IOException("internet not connected");
    Socket sc = new Socket(address, Integer. parseInt(port));
}
</code>```

And everything is good, But if active connection will lost after isOnline was called, and before new Socket call, its still blocks for random time.

My question is there any possibility to solve that problem? or just block this thread for fixed time for about 2-3 seconds?

答:
I suggest calling thread.interrupt() after a timeout.

You might also want to get the Android source and see where it's spending all that time.  It might give you some insight on other approaches to dealing with this.

Body:
Trying to open socket connection in separate thread by calling this:

Socket sc = sc = new Socket(address, Integer. parseInt(port));

But there is a problem, if there is no active internet connection this thread is blocking, on my htc hero 2.1 for 30 seconds, and my android emulator 2.2 for 2 minutes.

I tryed to use this method before opening connection:

public static boolean isOnline()
{
             ConnectivityManager cm = (ConnectivityManager) app.getInstance().getSystemService(Context. CONNECTIVITY_SERVICE);
             if(null != cm.getActiveNetworkInfo())
                   return cm.getActiveNetworkInfo().isConnectedOrConnecting();
             return false ;
}

public void run()
{
    if(!isOnline())
        throw new IOException("internet not connected");
    Socket sc = new Socket(address, Integer. parseInt(port));
}

And everything is good, But if active connection will lost after isOnline was called, and before new Socket call, its still blocks for random time.

My question is there any possibility to solve that problem? or just block this thread for fixed time for about 2-3 seconds?


问:
Wordpress | Custom editable permalink per post
On my website I have a page showing all portfolio items.
Every portfolio item has a link to their own detail page.

My client wants to display every portfolio item on that page (Portfolio page), but not every item needs a detail page.

Some portfolio items only have a title and a preview image.
On their current (Wordpress) website they are overwritting the permalink to '#'. (Using a plugin which I don't seem to find)

I thought about adding a checkbox to the Custom Post Type to wether use the real link or not. But this seems to be way too much work editing every post.

Does anyone know how to solve this easily?

Thank you!

答: You can use jQuery to remove link from the post and use post id as class or id for identify the post.</p>


问:
Variable column names in the pipe
I have the following code:

```<code>install.packages('tidyverse')
library(tidyverse)
x <- 1:10
y <- x^2
df <- data.frame(first_column = x, second_column = y)
tibble <- as_tibble(df)

tibble %>%
  filter(second_column != 16) %>%
  ggplot(aes(x = first_column, y = second_column)) +
  geom_line()
</code>```

Now I would like to create the following function

```<code>test <- function(colname) {
  tibble %>%
    filter(colname != 16) %>%
    ggplot(aes(x = first_column, y = colname)) +
    geom_line()
}

test('second_column')
</code>```

But running it creates a vertical line instead of the function. How can I make this function work?
Edit: My focus is on getting the pipe to work, not ggplot.

答:
In order to pass character strings for variable names, you have to use the standard evaluation version of each function. It is aes_string for aes, and filter_ for filter. See the NSE vignette for more details.

Your function could look like:

```<code>test <- function(colname) {
  tibble %>%
    filter_(.dots= paste0(colname, "!= 16")) %>%
    ggplot(aes_string(x = "first_column", y = colname)) +
    geom_line()
}
</code>```

Title: Variable column names in the pipe

Body:
I have the following code:

install.packages('tidyverse')
library(tidyverse)
x <- 1:10
y <- x^2
df <- data.frame(first_column = x, second_column = y)
tibble <- as_tibble(df)

tibble %>%
  filter(second_column != 16) %>%
  ggplot(aes(x = first_column, y = second_column)) +
  geom_line()

Now I would like to create the following function

test <- function(colname) {
  tibble %>%
    filter(colname != 16) %>%
    ggplot(aes(x = first_column, y = colname)) +
    geom_line()
}

test('second_column')

But running it creates a vertical line instead of the function. How can I make this function work?
Edit: My focus is on getting the pipe to work, not ggplot.

Body:
In order to pass character strings for variable names, you have to use the standard evaluation version of each function. It is aes_string for aes, and filter_ for filter. See the NSE vignette for more details.

Your function could look like:

test <- function(colname) {
  tibble %>%
    filter_(.dots= paste0(colname, "!= 16")) %>%
    ggplot(aes_string(x = "first_column", y = colname)) +
    geom_line()
}


问:
A Function with multiple outputs in C#
I want to define a function with two outputs. The first one is a boolean variable and the second one is 2D array with unknown numbers of rows and columns but the array will be defined if the boolean variable is true and if the boolean variable is false, the array is not defined. how can I define this function? I am thankful if anybody can exemplify it in an example.
Thanks</p>

答:
Why not return null if array is not defined?

```<code>  public static bool MyMethod(out int[,] array) {
    array = null;

    ...
  }
</code>```

....

```<code>  int[,] data;

  if (MyMethod(out data)) {
    ....
  }
</code>```

Or in case of C# 7.0+

```<code>  if (MyMethod(out var data)) {
    ....
  }
</code>```

Edit: if you want to return an array, but you don't know its Length (or want to adjust it) you can try working with List<T> and put .ToArray() in the end:

```<code>  using System.Linq;
  ...

  List<int> list = new List<int>();

  list.Add(1);
  list.Add(5);
  list.Add(10);
  ...
  list.Remove(5);
  ...
  list.RemoveAt(0);
  ...
  array = list.ToArray();
</code>```

Title: A Function with multiple outputs in C#

Body:
Why not return null if array is not defined?

  public static bool MyMethod(out int[,] array) {
    array = null;

    ...
  }

....

  int[,] data;

  if (MyMethod(out data)) {
    ....
  }

Or in case of C# 7.0+

  if (MyMethod(out var data)) {
    ....
  }

Edit: if you want to return an array, but you don't know its Length (or want to adjust it) you can try working with List<T> and put .ToArray() in the end:

  using System.Linq;
  ...

  List<int> list = new List<int>();

  list.Add(1);
  list.Add(5);
  list.Add(10);
  ...
  list.Remove(5);
  ...
  list.RemoveAt(0);
  ...
  array = list.ToArray();


问:
How to retrieve data that is not in the same order as the query in SQL?
I am trying to retrieve a record from a table in SQL.

Here is what I want. For example:

I have a table name studentScore with two columns:

```<code>studentName -----  Scores
John Smith  ----- 75,83, 96
</code>```

I want to do this: When I type the score in a search box, I want it to show me the name of the student. For example: I could type "83, 96, 75", (the scores can be in any order) and this should show me the student name "John Smith". But I'm wondering how we could specify in the WHERE clause so that it picks up the correct record, if what we type in the box is not in the same order as the original data in the column?

答: I suppose it is solvable, but it would be simpler if the scores for each student were stored as separate rows, for example in a scores table.  Otherwise, the code would have to permute the entry into every conceivable order.  Or the scores entry would have to be in a standard order somehow.

Body:
I am trying to retrieve a record from a table in SQL.

Here is what I want. For example:

I have a table name studentScore with two columns:

studentName -----  Scores
John Smith  ----- 75,83, 96

I want to do this: When I type the score in a search box, I want it to show me the name of the student. For example: I could type "83, 96, 75", (the scores can be in any order) and this should show me the student name "John Smith". But I'm wondering how we could specify in the WHERE clause so that it picks up the correct record, if what we type in the box is not in the same order as the original data in the column?


问:
Advanced Method Call Hierarchy generation for Java?
I have some large corporate Spring project unknown for me and I need to perform this kind of task above it:

"I have method A and method B. During the execution of method A, can
  method B be called?"

Well I found there is function Method Call Hierarchy in IntelliJ Idea. I can perform this function on method B and generate call hierarchy, where I can perform serarch for method A. Unfortunatelly, IntelliJ freeze during computing of this hierarchy becouse its so large and crashed after 5 hours of working.

I need Method Call Hierarchy utility with better performance than IntelliJ Idea have but I failed to find it. Can you help me?

答:
A workaround may be to use the Debugger. Set breakpoint 1 in method A and set  breakpoint 2 in method B.
Then in the Breakpoints dialog configure breakpoint 1 to not suspend. And configure the breakpoint 2 to be disabled until selected breakpoint is hit and select breakpoint 1. Now run the project or some tests in the debugger and check if breakpoint 2 is hit.


问:
How to load home page after refreshing or reloading in any view in AngularJS?
Suppose I have 3 views (login, chat and Map) in an AngularJS application. If I'm in Map View and clicked on refresh button my page must get redirect to chat view after refreshing page. Experts please suggest how to implement.</p>

答:
you can implement you'r state navigation inside beforeunload browser event

```<code>var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
   // your code for state navigation
   event.preventDefault();
});
</code>```

Body:
you can implement you'r state navigation inside beforeunload browser event

var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
   // your code for state navigation
   event.preventDefault();
});


问:
Expand ImageView height when zoomed in
I have an ImageView of fixed height 350dp displayed in a dialog box when a button is clicked. I am using this library compile 'com.commit451:PhotoView:1.2.4' with the following codes:

```<code>PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();
</code>```

It works well on zooming in/out but it does not expand the imageview's size upon zooming in. The picture can be zoomed but it is still contained inside the fixed 350dp of imageview. How can I expand the height/width of the imageview when I zoom in to the picture inside?

I've tried approach here Change the size of ImageView on zooming but still to no avail. Any helps please?

答:
You can do it without adding any dependency. Just you have to create a customImageView and perform action on that.

Check this TouchImageView

and in your Main Activity do this:

```<code>imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
imgDisplay.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);
        return true;
    }
});
imgDisplay.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);

        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }
});
</code>```

and in xml create like this

```<code> <com.example.TouchImageView
        android:id="@+id/imgDisplay"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:scaleType="matrix"
        android:layout_centerVertical="true"
        />
</code>```

Title: Expand ImageView height when zoomed in

Body:
I have an ImageView of fixed height 350dp displayed in a dialog box when a button is clicked. I am using this library compile 'com.commit451:PhotoView:1.2.4' with the following codes:

PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();

It works well on zooming in/out but it does not expand the imageview's size upon zooming in. The picture can be zoomed but it is still contained inside the fixed 350dp of imageview. How can I expand the height/width of the imageview when I zoom in to the picture inside?

I've tried approach here Change the size of ImageView on zooming but still to no avail. Any helps please?

Body:
You can do it without adding any dependency. Just you have to create a customImageView and perform action on that.

Check this TouchImageView

and in your Main Activity do this:

imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
imgDisplay.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);
        return true;
    }
});
imgDisplay.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Display display = _activity.getWindowManager().getDefaultDisplay();
        android.view.ViewGroup.LayoutParams layoutParams = imgDisplay.getLayoutParams();
        layoutParams.width = display.getWidth();
        layoutParams.height = display.getHeight();
        imgDisplay.setLayoutParams(layoutParams);

        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }
});

and in xml create like this

 <com.example.TouchImageView
        android:id="@+id/imgDisplay"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:scaleType="matrix"
        android:layout_centerVertical="true"
        />


问:
C++ Assigning an int to a char - why does this work without at least a warning?
Why does C++ (and probably C as well) allow me to assign and int to a char without at least giving me a warning?

Is it okay to directly assign the value, like in

```<code>int i = 12;
char c = i;
</code>```

i.e. do an implicit conversion, or shall I use a static_cast<>?

EDIT

Btw, I'm using gcc.

答:
It was allowed in C before an explicit cast syntax was invented.
Then it remained a common practice, so C++ inherited it in order to not break a huge amount of code.

Actually most compilers issue a warning. If your doesn't, try change its settings.

Body:
Why does C++ (and probably C as well) allow me to assign and int to a char without at least giving me a warning?

Is it okay to directly assign the value, like in

int i = 12;
char c = i;

i.e. do an implicit conversion, or shall I use a static_cast<>?

EDIT

Btw, I'm using gcc.


问:
Devise with roles
I am using devise for authentication, Now in registration steps i want to add extra parameter, so I use devise_parameter_sanitizer like following

```<code>def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :email, :subdomain, :phone, :company, role_ids: []])
end
</code>```

If I pass role_ids rails will automatically add roles for user, but I want to pass role_names instead of role_ids but its give me error

```<code>ActiveModel::UnknownAttributeError (unknown attribute 'roles_name' for User.)
</code>```

Edited:

```<code>models/user.rb
has_many :roles_user, dependent: :destroy
has_many :roles, through: :roles_user
</code>```

答: Is role_names= defined on User? Do you have a database field or relation for role_names? Perhaps you simply have to rename role_ids column to role_names in your database.

Title: Devise with roles

Body:
I am using devise for authentication, Now in registration steps i want to add extra parameter, so I use devise_parameter_sanitizer like following

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :email, :subdomain, :phone, :company, role_ids: []])
end

If I pass role_ids rails will automatically add roles for user, but I want to pass role_names instead of role_ids but its give me error

ActiveModel::UnknownAttributeError (unknown attribute 'roles_name' for User.)

Edited:

models/user.rb
has_many :roles_user, dependent: :destroy
has_many :roles, through: :roles_user


问:
Click on a button and display new html element
```<code>     <div>
        ToDo<br>
        <input ng-show="add" type="checkbox" >{{val}}
    </div>

    <div>
        <input type="text" ng-model="ToDo">
        <input type="button" ng-click="addToDo()" name="btn" placeholder="add todo here" ng-model="add" value="add" />
    </div>
</code>```

And the javascript:

```<code>  var app = angular.module("myapp",[]);
        app.controller("myctrl",function($scope,$log){
            $scope.addToDo = function(){
                $scope.val = $scope.ToDo;
            }
        });
</code>```

If i click on the 'add' button, a checkbox should appear along with the text of the texxtbox. But only text is showing, no checkbox. How do i display the checkbox?

答:
You have  to call the function in your controller and update some variable to true/ false. Based on the value and using ng-if directive, you can toggle the HTML element.

$scope.displayCheckBox = false;
$scope.val = "someRandoValue";

$scope.addToDo = function() {
  $scope.displayCheckBox = true;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  ToDo<br>
  <span ng-if="displayCheckBox">
    <input type="checkbox" >{{val}}
  </span>
</div></code>```

Body:
        ToDo

        <input ng-show="add" type="checkbox" >{{val}}

        <input type="text" ng-model="ToDo">
        <input type="button" ng-click="addToDo()" name="btn" placeholder="add todo here" ng-model="add" value="add" />

And the javascript:

  var app = angular.module("myapp",[]);
        app.controller("myctrl",function($scope,$log){
            $scope.addToDo = function(){
                $scope.val = $scope.ToDo;
            }
        });

If i click on the 'add' button, a checkbox should appear along with the text of the texxtbox. But only text is showing, no checkbox. How do i display the checkbox?

Body:
You have  to call the function in your controller and update some variable to true/ false. Based on the value and using ng-if directive, you can toggle the HTML element.

$scope.displayCheckBox = false;
$scope.val = "someRandoValue";

$scope.addToDo = function() {
  $scope.displayCheckBox = true;
};

<div>
  ToDo<br>
  <span ng-if="displayCheckBox">
    <input type="checkbox" >{{val}}
  </span>
</div>