qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | changes you make to the controls on client side are not accessible to the code behind at the server, unless those changes are made to the values of input controls.
so, youu can also use hiddenfield along with label which youu want to change in javascript/ Jquery then, store the new label value in hiddenfield as well
then, instead of reading value from label in codebehind, read it from hiddenfield.
```
<asp:hiddenfied id="hdnLblValue" runat="server"/>
``` | **Need to Keep in Mind**
1. If any Server Control Example: TextBox. is Disabled or ReadOnly from Aspx Page or Code behind.
2. It's value is being changed from JQuery or Javascipt.
3. You try to get the changed value of this control from code behind then you will never get it.
4. When you post back this control then server will validate the property (If it is Disabled or ReadOnly then server will not entertain this control's changed value.
5. You Need to use hidden field and populate this hidden field with changed value of this control.
<asp:HiddenField runat="server" ID="hdnTextBoxValue"/>
**You need to set the changed value by JQuery or Javascript to hidden Field and get the value from Code behind.** |
30,704,258 | I have a factory, how do i call 'getAccountDetails' service inside getAccountInformation() function.
I tried in the following way, but not working.
```
AccountService.getAccountDetails.getAccountDetailsService
```
factory
-------
```
tellerApp.factory('AccountService',['$resource', function ($resource) {
return{
getAccountDetails: $resource(XXX, {}, {
getAccountDetailsService: {}
}),
getAccountInformation: function($scope, number, transaction, index){
AccountService.getAccountDetails.getAccountDetailsService({number : number})
.$promise.then(function(response){});
}
}]);
``` | 2015/06/08 | [
"https://Stackoverflow.com/questions/30704258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376984/"
] | I suggest you define your code dependencies out of the returned provider:
```
tellerApp.factory('AccountService',['$resource', function ($resource) {
var getAccountDetails = $resource(XXX, {}, {getAccountDetailsService: {}});
return {
getAccountDetails : getAccountDetails,
getAccountInformation: function($scope, number, transaction, index){
getAccountDetails.getAccountDetailsService({number : number}).$promise.then(function(response){
...
})
}
};
}]);
```
Or, inside an object, you can also use `this` to refer to the current object, instead of using `AccountService.getAccountDetails`, you should use `this.getAccountDetails`.
```
tellerApp.factory('AccountService',['$resource', function ($resource) {
return {
getAccountDetails : $resource(XXX, {}, {getAccountDetailsService: {}});,
getAccountInformation: function($scope, number, transaction, index){
this.getAccountDetails.getAccountDetailsService({number : number}).$promise.then(function(response){
...
})
}
};
}]);
```
Plus, be careful, because your naming convention is confusing (`getAccountDetails` is not a function, since you don't call it with `()`, but it is named "get", `getAccountServices` is first defined as an object, but the same name is used later for a funtion...), especially if you want an accurate answer ;) | This should work, havent tested it though.
```
tellerApp.factory('AccountService',['$resource', function ($resource) {
var AccountService = {
getAccountDetails: $resource(XXX, {}, {
getAccountDetailsService: {}
}),
getAccountInformation: function($scope, number, transaction, index){
AccountService.getAccountDetails.getAccountDetailsService({number : number}).$promise.then(function(response){
}
};
}
return AccountService
}]);
``` |
5,808,650 | Here are my models:
```
class Player < ActiveRecord::Base
has_many :registrations, :class_name => "PlayerRegistration"
end
class PlayerRegistration < ActiveRecord::Base
belongs_to :player
belongs_to :payment
def self.paid
where("payment_id IS NOT NULL")
end
def self.unpaid
where(:payment_id => nil)
end
end
class Payment < ActiveRecord::Base
has_many :registrations, :class_name => "PlayerRegistration"
end
```
What I would like to do is create a scope on Player that returns all players who have an unpaid registration, so something like:
BAD PSUEDO CODE AHEAD
```
class Player < ActiveRecord::Base
def self.paid
registrations.unpaid #But actually return the players
end
end
```
Is this possible? It must be, considering that all the data I need is out there, I just have no idea how to write that sort of an AREL query. Can anybody help?
FWIW I've tried this:
```
class Player < ActiveRecord::Base
def self.paid
includes(:registrations).where("registrations.payment_id IS NOT NULL")
end
end
```
but that provides me with the following error:
```
ActiveRecord::StatementInvalid:
PGError: ERROR: missing FROM-clause entry for table "registrations"
LINE 1: ...registrations"."player_id" = "players"."id" WHERE "registrat...
^
: SELECT "players"."id" AS t0_r0, "players"."first_name" AS t0_r1, "players"."last_name" AS t0_r2, "players"."birthday" AS t0_r3, "players"."gender" AS t0_r4, "players"."created_at" AS t0_r5, "players"."updated_at" AS t0_r6, "players"."user_id" AS t0_r7, "player_registrations"."id" AS t1_r0, "player_registrations"."player_id" AS t1_r1, "player_registrations"."grade_id" AS t1_r2, "player_registrations"."shirt_size_id" AS t1_r3, "player_registrations"."division_id" AS t1_r4, "player_registrations"."coach_request" AS t1_r5, "player_registrations"."buddy_request" AS t1_r6, "player_registrations"."created_at" AS t1_r7, "player_registrations"."updated_at" AS t1_r8, "player_registrations"."league_id" AS t1_r9, "player_registrations"."season_id" AS t1_r10, "player_registrations"."school_id" AS t1_r11, "player_registrations"."payment_id" AS t1_r12 FROM "players" LEFT OUTER JOIN "player_registrations" ON "player_registrations"."player_id" = "players"."id" WHERE "registrations"."payment_id" IS NULL
```
Could anyone show me a better way? Isn't there a way I can use the paid scope that I already have in PlayerRegistrations? | 2011/04/27 | [
"https://Stackoverflow.com/questions/5808650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303675/"
] | You need the real table name in the where() filter:
```
class Player < ActiveRecord::Base
def self.paid
includes(:registrations).where("player_registrations.payment_id IS NOT NULL")
end
end
``` | You could write:
```
class Player
scope :unpaid, includes(:registrations).where("player_registrations.payment_id is null")
scope :paid, includes(:registrations).where("player_registrations.payment_id is not null")
end
```
and now `Player.unpaid` will return all players with unpaid registrations.
If you write something like:
```
class Registration
scope :paid, where("payment_id IS NOT NULL")
scope :unpaid, where("payment_id is null")
end
```
then it is possible to write `player1.registrations.unpaid`, but that is not what you want.
If I understand correctly, you want to find *all players* with unpaid registrations, and that is only possible using the scope on the `Player` class.
Hope this helps. |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | I had the same problem, I fixed that by installing the php-mysql package:
$ sudo yum install php-mysql | Add same issue on Cpanel , moving a CI project from php 5.3 to 5.4
Blank page or 500 internal server error
This resolve the issue :
Enable the "mysqli" extension in PHP (v5) via EasyApache, using the Exhaustive Options List (Cpanel). |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Add same issue on Cpanel , moving a CI project from php 5.3 to 5.4
Blank page or 500 internal server error
This resolve the issue :
Enable the "mysqli" extension in PHP (v5) via EasyApache, using the Exhaustive Options List (Cpanel). | In my case it was fixed by doing this:
```
yum install php-mysqli
```
on Centos 8 |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | see the include\_path in php on your production server and/or make other frontend with development environment to see error | In my case it was fixed by doing this:
```
yum install php-mysqli
```
on Centos 8 |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Check this thread for similar issue: [CodeIgniter project loads blank webpage](https://stackoverflow.com/questions/7486872/codeigniter-project-loads-blank-webpage)
Also, in case you *don't* have mysql installed and/or a database set up for your site, TankAuth *does* need the database. Be sure to follow all the [installation instructions](http://konyukhov.com/soft/tank_auth/) and create the tables that the module needs (you'll see a .sql dump in the downloaded folder). | My solution was the same than the others, install mysql compatibility to php. In my case the platform is ubuntu on Amazon AWS (Using mysql on RDS, not local):
`$sudo apt-get install php5-mysql`
`$sudo apt-get install mysql-client`
`$sudo service apache2 restart`
And thats is all, Greetings! |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | I had the same problem, I fixed that by installing the php-mysql package:
$ sudo yum install php-mysql | My solution was the same than the others, install mysql compatibility to php. In my case the platform is ubuntu on Amazon AWS (Using mysql on RDS, not local):
`$sudo apt-get install php5-mysql`
`$sudo apt-get install mysql-client`
`$sudo service apache2 restart`
And thats is all, Greetings! |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Have you checked if error reporting is enabled? If not, try adding
```
ini_set('display_errors',1);
error_reporting(E_ALL);
```
to the beginning of index.php. | see the include\_path in php on your production server and/or make other frontend with development environment to see error |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Check this thread for similar issue: [CodeIgniter project loads blank webpage](https://stackoverflow.com/questions/7486872/codeigniter-project-loads-blank-webpage)
Also, in case you *don't* have mysql installed and/or a database set up for your site, TankAuth *does* need the database. Be sure to follow all the [installation instructions](http://konyukhov.com/soft/tank_auth/) and create the tables that the module needs (you'll see a .sql dump in the downloaded folder). | Add same issue on Cpanel , moving a CI project from php 5.3 to 5.4
Blank page or 500 internal server error
This resolve the issue :
Enable the "mysqli" extension in PHP (v5) via EasyApache, using the Exhaustive Options List (Cpanel). |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Have you checked if error reporting is enabled? If not, try adding
```
ini_set('display_errors',1);
error_reporting(E_ALL);
```
to the beginning of index.php. | i had the same problem, in my case i needed install de lib php-pgsql(because i use postgresql) on my server. After that, the problem was solved |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | Check this thread for similar issue: [CodeIgniter project loads blank webpage](https://stackoverflow.com/questions/7486872/codeigniter-project-loads-blank-webpage)
Also, in case you *don't* have mysql installed and/or a database set up for your site, TankAuth *does* need the database. Be sure to follow all the [installation instructions](http://konyukhov.com/soft/tank_auth/) and create the tables that the module needs (you'll see a .sql dump in the downloaded folder). | see the include\_path in php on your production server and/or make other frontend with development environment to see error |
9,084,682 | I'm trying to setup my site on a production server, and it's basically crashing at line 291 in /system/core/CodeIgniter.php:
```
//instantiate the requested controller
// Mark a start point so we can benchmark the controller
$BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start');
$CI = new $class();
```
The class is 'auth' (from the tank\_auth library), so it's crashing on '$CI = new auth();'
It doesn't produce an error (why??), just displays a blank page. This all works fine locally.
Has anyone had any similar issues? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9084682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366716/"
] | I had the same problem, I fixed that by installing the php-mysql package:
$ sudo yum install php-mysql | i had the same problem, in my case i needed install de lib php-pgsql(because i use postgresql) on my server. After that, the problem was solved |
39,149,747 | I am new to React. This is probably a noob question.
I want to change the "filteredFields" prop of my MeteorGriddle component when the user clicks a checkbox. My JSX:
```
const bookingsPage = () => {
let filteredFields = ['userName'];
const handleClick = (e) => {
if (e.target.checked) {
filteredFields = ['userEmail'];
// How to propagate this change to the MeteorGriddle?
}
}
return (
<div>
<label><input type="checkbox" defaultChecked="true" value="userEmail" onClick={handleClick}/>Email</label>
<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
};
``` | 2016/08/25 | [
"https://Stackoverflow.com/questions/39149747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372459/"
] | I see two ways of solving your problem.
**The first and easy way to do this:**
Turn your bookingsPage component into statefull component instead of functional,
then you'd be able to create state inside it, and then change the state on event alongside with passing it to MeteorGriddle component.
So the code would be:
```
class bookingsPage extends React.Component {
getInitialState = () => {
filteredFields: []
}
handleClick = (e) => {
if (e.target.checked) {
const newFilteredFields =
[ ...this.state.filteredFields ].push('userEmail');
this.setState({ filteredFields: newFilteredFields });
}
}
render() {
return (
<div>
<label>
<input
type="checkbox"
defaultChecked="true"
value="userEmail"
onClick={this.handleClick}
/>
Email
</label>
<MeteorGriddle
filteredFields={this.state.filteredFields}
/>
</div>
);
}
};
```
**Second and harder way to do this:**
Take a look on [Redux](http://redux.js.org/). It solves a problem of data flow in React.
The basic concept is that when you check you checkbox, you dispatch an action into reducer (aka your global data storage for react components), and then GriddleComponent recieves new state of your application with fresh data inside which tells him the checkbox is checked.
Say if you want me to write an example based on yours for you. | As @Maxx says, you should use a component with state. Then when you call the setState method, it will render again, updating the props of the children.
In your case this should work (also using ES6 notation):
```
import React from 'react';
import MeteorGriddle from '...whatever path...';
class bookingsPage extends React.Component {
state = {
filteredFields: ['userName']
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
if (e.target.checked) {
this.setState({
...this.state, //This is just a good practice to not overwrite other properties
filteredFields: ['userEmail']
});
}
}
render() {
const { filteredFields } = this.state;
return(
<div>
<label>
<input type="checkbox" defaultChecked="true" value="userEmail"
onChange={this.handleChange}/>Email
</label>
<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
}
}
``` |
39,149,747 | I am new to React. This is probably a noob question.
I want to change the "filteredFields" prop of my MeteorGriddle component when the user clicks a checkbox. My JSX:
```
const bookingsPage = () => {
let filteredFields = ['userName'];
const handleClick = (e) => {
if (e.target.checked) {
filteredFields = ['userEmail'];
// How to propagate this change to the MeteorGriddle?
}
}
return (
<div>
<label><input type="checkbox" defaultChecked="true" value="userEmail" onClick={handleClick}/>Email</label>
<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
};
``` | 2016/08/25 | [
"https://Stackoverflow.com/questions/39149747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372459/"
] | I see two ways of solving your problem.
**The first and easy way to do this:**
Turn your bookingsPage component into statefull component instead of functional,
then you'd be able to create state inside it, and then change the state on event alongside with passing it to MeteorGriddle component.
So the code would be:
```
class bookingsPage extends React.Component {
getInitialState = () => {
filteredFields: []
}
handleClick = (e) => {
if (e.target.checked) {
const newFilteredFields =
[ ...this.state.filteredFields ].push('userEmail');
this.setState({ filteredFields: newFilteredFields });
}
}
render() {
return (
<div>
<label>
<input
type="checkbox"
defaultChecked="true"
value="userEmail"
onClick={this.handleClick}
/>
Email
</label>
<MeteorGriddle
filteredFields={this.state.filteredFields}
/>
</div>
);
}
};
```
**Second and harder way to do this:**
Take a look on [Redux](http://redux.js.org/). It solves a problem of data flow in React.
The basic concept is that when you check you checkbox, you dispatch an action into reducer (aka your global data storage for react components), and then GriddleComponent recieves new state of your application with fresh data inside which tells him the checkbox is checked.
Say if you want me to write an example based on yours for you. | There are number of ways to achieve this, you can just try like the below code,
```
import React from 'react';
class bookingsPage extends React.Component {
state = {
filteredFields: ['userName']
};
constructor(props) {
super(props);
}
handleChange(e) {
if (e.target.checked) {
this.setState({
filteredFields: ['userEmail']
});
}
}
render() {
return(
<div>
<label>
<input type="checkbox" defaultChecked="true" value="userEmail"
onChange={this.handleChange.bind(this)}/>Email
</label>
<MeteorGriddle filteredFields={this.state.filteredFields}/>
</div>
);
}}
``` |
39,149,747 | I am new to React. This is probably a noob question.
I want to change the "filteredFields" prop of my MeteorGriddle component when the user clicks a checkbox. My JSX:
```
const bookingsPage = () => {
let filteredFields = ['userName'];
const handleClick = (e) => {
if (e.target.checked) {
filteredFields = ['userEmail'];
// How to propagate this change to the MeteorGriddle?
}
}
return (
<div>
<label><input type="checkbox" defaultChecked="true" value="userEmail" onClick={handleClick}/>Email</label>
<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
};
``` | 2016/08/25 | [
"https://Stackoverflow.com/questions/39149747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372459/"
] | As @Maxx says, you should use a component with state. Then when you call the setState method, it will render again, updating the props of the children.
In your case this should work (also using ES6 notation):
```
import React from 'react';
import MeteorGriddle from '...whatever path...';
class bookingsPage extends React.Component {
state = {
filteredFields: ['userName']
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
if (e.target.checked) {
this.setState({
...this.state, //This is just a good practice to not overwrite other properties
filteredFields: ['userEmail']
});
}
}
render() {
const { filteredFields } = this.state;
return(
<div>
<label>
<input type="checkbox" defaultChecked="true" value="userEmail"
onChange={this.handleChange}/>Email
</label>
<MeteorGriddle filteredFields={filteredFields}/>
</div>
);
}
}
``` | There are number of ways to achieve this, you can just try like the below code,
```
import React from 'react';
class bookingsPage extends React.Component {
state = {
filteredFields: ['userName']
};
constructor(props) {
super(props);
}
handleChange(e) {
if (e.target.checked) {
this.setState({
filteredFields: ['userEmail']
});
}
}
render() {
return(
<div>
<label>
<input type="checkbox" defaultChecked="true" value="userEmail"
onChange={this.handleChange.bind(this)}/>Email
</label>
<MeteorGriddle filteredFields={this.state.filteredFields}/>
</div>
);
}}
``` |
21,848,614 | I have an options page in my wordpress theme, it's to select a number of categories from a custom taxonomy.
```
$terms_obj = get_option('shop_features')
```
This returns an array with $key being the category-name and $value being either 1 or empty depending if the category was checked.
I need to grab a list of the checked categories to use in an array in another function:
```
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
Where I need to insert my category-names contained in a variable $terms to replace the `'terms' => array('knives')` with `'terms' => array ( $terms )`
Except it doesn't work by just doing that!
Here is how I've tried to accomplish that:
```
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$terms_obj = of_get_option( 'eco_shop_features', $default );
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms .= '\'' . $slug . '\', ';
}
$terms = rtrim( $terms, ', ' );
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( "$terms" ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
I'm stuck of how to insert just the list of category names in to the terms field so it works as an array. | 2014/02/18 | [
"https://Stackoverflow.com/questions/21848614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992558/"
] | The right way seems to be commented out by you, below should work
```
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms[] = $slug;
}
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms,
'operator' => 'NOT IN'
)));
``` | Just prepare an array in the loop
```
$terms[] = $slug
```
And assign to term
```
'terms' => $terms,
``` |
21,848,614 | I have an options page in my wordpress theme, it's to select a number of categories from a custom taxonomy.
```
$terms_obj = get_option('shop_features')
```
This returns an array with $key being the category-name and $value being either 1 or empty depending if the category was checked.
I need to grab a list of the checked categories to use in an array in another function:
```
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
Where I need to insert my category-names contained in a variable $terms to replace the `'terms' => array('knives')` with `'terms' => array ( $terms )`
Except it doesn't work by just doing that!
Here is how I've tried to accomplish that:
```
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$terms_obj = of_get_option( 'eco_shop_features', $default );
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms .= '\'' . $slug . '\', ';
}
$terms = rtrim( $terms, ', ' );
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( "$terms" ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
I'm stuck of how to insert just the list of category names in to the terms field so it works as an array. | 2014/02/18 | [
"https://Stackoverflow.com/questions/21848614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992558/"
] | The right way seems to be commented out by you, below should work
```
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms[] = $slug;
}
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms,
'operator' => 'NOT IN'
)));
``` | To get your array of category names you can do :
```
$terms_obj = get_option('shop_features');
$category_name_array = array_keys($terms_obj, 1);
```
The `array_keys($terms_obj, 1)` function will extract in an array all the keys of the $terms\_obj for witch the value match 1.
More info : <http://php.net/manual/en/function.array-keys.php> |
21,848,614 | I have an options page in my wordpress theme, it's to select a number of categories from a custom taxonomy.
```
$terms_obj = get_option('shop_features')
```
This returns an array with $key being the category-name and $value being either 1 or empty depending if the category was checked.
I need to grab a list of the checked categories to use in an array in another function:
```
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
Where I need to insert my category-names contained in a variable $terms to replace the `'terms' => array('knives')` with `'terms' => array ( $terms )`
Except it doesn't work by just doing that!
Here is how I've tried to accomplish that:
```
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$terms_obj = of_get_option( 'eco_shop_features', $default );
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms .= '\'' . $slug . '\', ';
}
$terms = rtrim( $terms, ', ' );
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( "$terms" ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
```
I'm stuck of how to insert just the list of category names in to the terms field so it works as an array. | 2014/02/18 | [
"https://Stackoverflow.com/questions/21848614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992558/"
] | To get your array of category names you can do :
```
$terms_obj = get_option('shop_features');
$category_name_array = array_keys($terms_obj, 1);
```
The `array_keys($terms_obj, 1)` function will extract in an array all the keys of the $terms\_obj for witch the value match 1.
More info : <http://php.net/manual/en/function.array-keys.php> | Just prepare an array in the loop
```
$terms[] = $slug
```
And assign to term
```
'terms' => $terms,
``` |
56,338,512 | I have a table where 1 of the rows is an integer that represents the rows time. Problem is the table isn't full, there are missing timestamps.
I would like to fill missing values such that every 10 seconds there is a row. I want the rest of the columns to be nuns (later I'll forward fill these nuns).
10 secs is basically 10,000.
If this was python the range would be:
```
range(
min(table[column]),
max(table[column]),
10000
)
``` | 2019/05/28 | [
"https://Stackoverflow.com/questions/56338512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11529177/"
] | If your values are strictly parted by 10 seconds, and there are just some multiples of 10 seconds intervals which are missing, you can go by this approach to fill your data holes:
```
WITH minsmax AS (
SELECT
MIN(time) AS minval,
MAX(time) AS maxval
FROM `dataset.table`
)
SELECT
IF (d.time <= i.time, d.time, i.time) as time,
MAX(IF(d.time <= i.time, d.value, NULL)) as value
FROM (
SELECT time FROM minsmax m, UNNEST(GENERATE_ARRAY(m.minval, m.maxval+100, 100)) AS time
) AS i
LEFT JOIN `dataset.table` d ON 1=1
WHERE ABS(d.time - i.time) >= 100
GROUP BY 1
ORDER BY 1
```
Hope this helps. | You can use arrays. For numbers, you can do:
```
select n
from unnest(generate_array(1, 1000, 1)) n;
```
There are similar functions for `generate_timestamp_array()` and `generate_date_array()` if you really need those types. |
56,338,512 | I have a table where 1 of the rows is an integer that represents the rows time. Problem is the table isn't full, there are missing timestamps.
I would like to fill missing values such that every 10 seconds there is a row. I want the rest of the columns to be nuns (later I'll forward fill these nuns).
10 secs is basically 10,000.
If this was python the range would be:
```
range(
min(table[column]),
max(table[column]),
10000
)
``` | 2019/05/28 | [
"https://Stackoverflow.com/questions/56338512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11529177/"
] | I ended up using the following query through python API:
```
"""
SELECT
i.time,
Sensor_Reading,
Sensor_Name
FROM (
SELECT time FROM UNNEST(GENERATE_ARRAY({min_time}, {max_time}+{sampling_period}+1, {sampling_period})) AS time
) AS i
LEFT JOIN
`{input_table}` AS input
ON
i.time =input.Time
ORDER BY i.time
""".format(sampling_period=sampling_period, min_time=min_time,
max_time=max_time,
input_table=input_table)
```
Thanks to both answers | You can use arrays. For numbers, you can do:
```
select n
from unnest(generate_array(1, 1000, 1)) n;
```
There are similar functions for `generate_timestamp_array()` and `generate_date_array()` if you really need those types. |
56,106,244 | The following code below print "34" instead of the expected ".34"
```
use strict;
use warnings;
use Regexp::Common;
my $regex = qr/\b($RE{num}{real})\s*/;
my $str = "This is .34 meters of cable";
if ($str =~ /$regex/) {
print $1;
}
```
Do I need to fix my regex? (The word boundary is need as not including it will cause it match something string like `xx34` which I don't want to)
Or is it is a bug in Regexp::Common? I always thought that a longest match should win. | 2019/05/13 | [
"https://Stackoverflow.com/questions/56106244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10704286/"
] | The word boundary is a context-dependent regex construct. When it is followed with a word char (letter, digit or `_`) this location should be preceded either with the start of a string or a non-word char. In this concrete case, the word boundary is followed with a non-word char and thus requires a word char to appear right before this character.
You may use a non-ambiguous word boundary expressed with a negative lookbehind:
```
my $regex = qr/(?<!\w)($RE{num}{real})/;
^^^^^^^
```
The `(?<!\w)` negative lookbehind always denotes one thing: fail the match if there
is no word character immediately to the left of the current location.
Or, use a whitespace boundary if you want your matches to only occur after whitespace or start of string:
```
my $regex = qr/(?<!\S)($RE{num}{real})/;
^^^^^^^
``` | Try this patern: `(?:^| )(\d*\.?\d+)`
Explanation:
`(?:...)` - non-capturing group
`^|` - match either `^` - beginning oof a string or - space
`\d*` - match zero or more digits
`\.?` - match dot literally - zero or one
`\d+` - match one or more digits
Matched number will be stored in first capturing group.
[Demo](https://regex101.com/r/KIIKkP/1) |
32,603,907 | I have a very simple PowerShell script that adds a sql server login to a db role. Since I use it for SQL 2008 I need to use the `sp_addrolemember` stored procedure.
If I use t-sql in management studio like this:
```
declare @dbrole varchar(100)
set @dbrole = 'db_owner'
declare @login varchar(100)
set @login = 'net1\vintida'
exec sp_addrolemember @rolename = @DBRole,
@membername = @login
```
then it works without problem
If I use a PowerShell script like this
```
$login = 'net1\vintida'
$DBrole = 'db_owner'
$Q3 = " exec sp_addrolemember @rolename = $DBRole,
@membername = $login "
Invoke-Sqlcmd -Query $Q3
```
then it throws the following error:
>
> Invoke-Sqlcmd : Incorrect syntax near 'vintida'. Incorrect syntax near
> '\'.
>
>
>
Howevever if I use the powershell script like this
```
$DBrole = 'db_owner'
$Q3 = "exec sp_addrolemember @rolename = $DBRole,
@membername = 'net1\vintida' "
Invoke-Sqlcmd -Query $Q3
```
It works perfectly
I cannot understand why when I pass the string 'net1\vintida' into the query text using the variable `$login` it does not like the \ but I hard code the same string into the query text it works | 2015/09/16 | [
"https://Stackoverflow.com/questions/32603907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3665373/"
] | Although I recommend using an image editor to remove the borders, there is a CSS hack for this:
**Negative margins:**
1. Wrap the image inside a container and set `overflow: hidden` after
defining the dimensions(width and height). Make sure the dimensions are slightly less than the image dimensions.
2. Set negative margins for the image inside. The margin value is relative to the size of the border.
```css
.borderless-img {
width: 118px;
height: 58px;
overflow: hidden;
}
.borderless-img img {
margin: -1px 0 0 -1px;
}
```
```html
<div class="borderless-img">
<img src="http://i.stack.imgur.com/dcnpS.jpg" />
</div>
```
**Scaling image:**
This method will increase the size of the image, might distort it to a very little extent. It works well for your solution since it would remove the small border.
*Cons: Not recommended to hide big part of images.*
```css
.borderless-img {
width: 118px;
height: 58px;
overflow: hidden;
}
.borderless-img img {
transform: scale(1.055);
}
```
```html
<div class="borderless-img">
<img src="http://i.stack.imgur.com/dcnpS.jpg" />
</div>
``` | you can use `clip-path` on [modern browsers](http://caniuse.com/#feat=css-clip-path) so you wouldn't need to add a wrapper and set the size of the image
Example: <http://codepen.io/anon/pen/Gpoamy>
```
img {
-webkit-clip-path: inset(1px 1px 1px 1px);
clip-path: inset(1px 1px 1px 1px)
}
```
On older browsers (and `IE`) you could just use `clip` (although this requires to specify the size of the rectangle and an `absolute` position)
---
Otherwise another approach, with a wider support across browsers, might uses an `outline` (with the same colour of the background) and a negative `outline-offset` — actually you're overlapping the black border with another one. (tested both on Chrome and Firefox).
Example: <http://codepen.io/anon/pen/PPZvKe>
```
img {
outline: 1px #fff solid;
outline-offset: -1px;
}
```
Of course these examples work when the border width included inside the image is exactly `1px`. If your image has a thicker border then change all the values according to the thickness |
28,197,253 | I'm pretty familiar with WordPress, and a fan of this CMS. So I'm used to the `get_header()` function that includes the `header.php` file. But now I'm developing a raw PHP project, and I want a similar ease here too. I designed a folder structure like below:
```
project/
css/
bootstrap.css
js/
jquery.js
project.js
inner-folder/
some-page.php
header.php
index.php
footer.php
style.css
```
I made a custom function `is_page()` just like WordPress to load page-specific items. Everything's working just fine where my `header.php` contains:
```
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
...
```
and my `footer.php` contains:
```
...
<script src="js/jquery.js"></script>
<script src="js/project.js"></script>
</body>
</html>
```
And my `index.php` contains:
```
<?php require_once( 'header.php' ); ?>
...
<?php require_once( 'footer.php' ); ?>
```
And everything's working just fine, until...
I started working on the `inner-folder/`. In `some-page.php` I used the same code like the `index.php` and you can guess, all the CSS and JS file links get broken.
How can I make a function or something so that regarding anywhere of my `project` folder (within any sub directory or sub-sub directory) I can load any of my resources without any hamper? And it should be performance-savvy too. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28197253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743124/"
] | If you have access to your `php.ini` file, and assuming you are running Apache 2 and have access to the Apache configuration file, you can edit these files to solve your problem.
**Step 1: Editing the Apache configuration**
You need to set the Directory and Document Root in your Apache configuration to be the path to your web project folder. I'm assuming this is already done, since you are successfully running PHP. If not, have a look at [this question](https://stackoverflow.com/questions/5891802/how-do-i-change-the-root-directory-of-an-apache-server).
**Step 2: Editing the PHP configuration**
There is a setting in the PHP configuration, `php.ini`, that allows you to set paths that the PHP engine will look for when including files.
```
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
;include_path = ".;c:\php\includes"
;
; PHP's default setting for include_path is ".;/path/to/php/pear"
; http://php.net/include-path
```
(Chart from [this question](https://stackoverflow.com/questions/11405864/how-can-i-change-include-path-in-php-ini-file))
If you don't have access to the PHP configuration or don't want to change it, you can always use the `[set_include_path][3]` function, which essentially does the same thing, just in the script.
Once you have completed both of these steps, you can include files as follows:
*Non-PHP resources such as CSS, JavaScript, etc:*
`/path/to/css`
*PHP resources:*
`path/to/php`
Note the leading slash for non-php resources, and no leading slash for PHP resources. | I had the same problem when using include menu so that i didn't had to change menu on each page.
So i hardcoded the url's:
```
<?php require_once('//domain.com/header.php'); ?>
``` |
28,197,253 | I'm pretty familiar with WordPress, and a fan of this CMS. So I'm used to the `get_header()` function that includes the `header.php` file. But now I'm developing a raw PHP project, and I want a similar ease here too. I designed a folder structure like below:
```
project/
css/
bootstrap.css
js/
jquery.js
project.js
inner-folder/
some-page.php
header.php
index.php
footer.php
style.css
```
I made a custom function `is_page()` just like WordPress to load page-specific items. Everything's working just fine where my `header.php` contains:
```
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
...
```
and my `footer.php` contains:
```
...
<script src="js/jquery.js"></script>
<script src="js/project.js"></script>
</body>
</html>
```
And my `index.php` contains:
```
<?php require_once( 'header.php' ); ?>
...
<?php require_once( 'footer.php' ); ?>
```
And everything's working just fine, until...
I started working on the `inner-folder/`. In `some-page.php` I used the same code like the `index.php` and you can guess, all the CSS and JS file links get broken.
How can I make a function or something so that regarding anywhere of my `project` folder (within any sub directory or sub-sub directory) I can load any of my resources without any hamper? And it should be performance-savvy too. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28197253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743124/"
] | Okay, I found a most solid solution: the HTML `<base>` tag –
```
<html>
<head>
<base href="http://example.com/">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
...
```
**Source:**
<http://www.w3schools.com/tags/tag_base.asp> | I had the same problem when using include menu so that i didn't had to change menu on each page.
So i hardcoded the url's:
```
<?php require_once('//domain.com/header.php'); ?>
``` |
28,197,253 | I'm pretty familiar with WordPress, and a fan of this CMS. So I'm used to the `get_header()` function that includes the `header.php` file. But now I'm developing a raw PHP project, and I want a similar ease here too. I designed a folder structure like below:
```
project/
css/
bootstrap.css
js/
jquery.js
project.js
inner-folder/
some-page.php
header.php
index.php
footer.php
style.css
```
I made a custom function `is_page()` just like WordPress to load page-specific items. Everything's working just fine where my `header.php` contains:
```
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
...
```
and my `footer.php` contains:
```
...
<script src="js/jquery.js"></script>
<script src="js/project.js"></script>
</body>
</html>
```
And my `index.php` contains:
```
<?php require_once( 'header.php' ); ?>
...
<?php require_once( 'footer.php' ); ?>
```
And everything's working just fine, until...
I started working on the `inner-folder/`. In `some-page.php` I used the same code like the `index.php` and you can guess, all the CSS and JS file links get broken.
How can I make a function or something so that regarding anywhere of my `project` folder (within any sub directory or sub-sub directory) I can load any of my resources without any hamper? And it should be performance-savvy too. | 2015/01/28 | [
"https://Stackoverflow.com/questions/28197253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743124/"
] | Okay, I found a most solid solution: the HTML `<base>` tag –
```
<html>
<head>
<base href="http://example.com/">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
...
```
**Source:**
<http://www.w3schools.com/tags/tag_base.asp> | If you have access to your `php.ini` file, and assuming you are running Apache 2 and have access to the Apache configuration file, you can edit these files to solve your problem.
**Step 1: Editing the Apache configuration**
You need to set the Directory and Document Root in your Apache configuration to be the path to your web project folder. I'm assuming this is already done, since you are successfully running PHP. If not, have a look at [this question](https://stackoverflow.com/questions/5891802/how-do-i-change-the-root-directory-of-an-apache-server).
**Step 2: Editing the PHP configuration**
There is a setting in the PHP configuration, `php.ini`, that allows you to set paths that the PHP engine will look for when including files.
```
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
;include_path = ".;c:\php\includes"
;
; PHP's default setting for include_path is ".;/path/to/php/pear"
; http://php.net/include-path
```
(Chart from [this question](https://stackoverflow.com/questions/11405864/how-can-i-change-include-path-in-php-ini-file))
If you don't have access to the PHP configuration or don't want to change it, you can always use the `[set_include_path][3]` function, which essentially does the same thing, just in the script.
Once you have completed both of these steps, you can include files as follows:
*Non-PHP resources such as CSS, JavaScript, etc:*
`/path/to/css`
*PHP resources:*
`path/to/php`
Note the leading slash for non-php resources, and no leading slash for PHP resources. |
27,077,967 | I have a immutable list and need a new copy of it with elements replaced at multiple index locations. The List.updated is an O(n) operation and can only replace one at a time. What is the efficient way of doing this? Thanks! | 2014/11/22 | [
"https://Stackoverflow.com/questions/27077967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2625798/"
] | `List` is not a good fit if you need random element access/update. From the [documentation](http://www.scala-lang.org/api/2.11.1/index.html#scala.collection.immutable.List):
>
> This class is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access pattern, for example, random access or FIFO, consider using a collection more suited to this than `List`.
>
>
>
More generally, what you need is an indexed sequence instead of a linear one (such as `List`). From the documentation of [`IndexedSeq`](http://www.scala-lang.org/api/2.11.1/index.html#scala.collection.immutable.IndexedSeq):
>
> Indexed sequences support constant-time or near constant-time element access and length computation. They are defined in terms of abstract methods apply for indexing and length.
>
>
> Indexed sequences do not add any new methods to `Seq`, but promise efficient implementations of random access patterns.
>
>
>
The default concrete implementation of `IndexedSeq` is [`Vector`](http://www.scala-lang.org/api/2.11.1/index.html#scala.collection.immutable.Vector), so you may consider using it.
Here's an extract from its documentation (emphasis added):
>
> Vector is a general-purpose, immutable data structure. **It provides random access and updates in effectively constant time**, as well as very fast append and prepend. Because vectors strike a good balance between fast random selections and fast random functional updates, they are currently the default implementation of immutable indexed sequences
>
>
> | ```
list
.iterator
.zipWithIndex
.map { case (index, element) => newElementFor(index) }
.toList
``` |
220,170 | I've skimmed through several sparse articles online about hysteresis in a MOSFET's I-V characteristics. What I found was sparse, but some articles attribute uneven-ness in the gate structure, causing some charge to move slower.
As for my limited knowledge of Physics, it's still reasonable to think that pulling or pushing out charge carriers would instantaneously collapse/build-up electric field. Not only that, the current must have something similar to a "momentum", even though electrons have extremely low mass.
I really don't have the time to read through all these articles and even if I did, my Physics is lacking. So can anybody just summarize this for me, or point to a shortened article?
Has there been any design of a MOSFET Gate Driver that deals with this issue?
EDIT:
Perhaps what I should've said is *"Hysteresis in MOSFET's response time"* (or maybe this is still incorrect?). I don't know what's wrong with me tonight. I'm shifting my sleeping schedule, so I already feel groggy. | 2016/03/01 | [
"https://electronics.stackexchange.com/questions/220170",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/58458/"
] | I have been studying/working with MOSFETs for 25 years and I've **never** heard/read about *"hysteresis in a MOSFET's I-V characteristics"*. So in my opinion: **it does not exist**.
Maybe it exists on a theoretical level but in practice I have yet to see it before I believe it exists.
The only hysteresis that you would encounter regarding a MOSFET is the hysteresis that you add with the surrounding circuit.
Please link to one or more of the articles where you see this phenomenon mentioned so I can have a look myself. | If you look at the curves from an IRF9510, they do not conform to the expected results. I found this out when I tried to use one for a linear application. P-CH MOSFETs from other manufacturers do not, in general, have the same behavior. In the image below, the gate voltage is offset by an external power supply to just below the threshold voltage.
What I do not know, is the effect that causes this behavior. If you have this info, please help me out.[](https://i.stack.imgur.com/wxEm0.jpg)
I have been told that IR developed these MOSFETs for switching applications only. The N-CH FETs do not behave this way. |
220,170 | I've skimmed through several sparse articles online about hysteresis in a MOSFET's I-V characteristics. What I found was sparse, but some articles attribute uneven-ness in the gate structure, causing some charge to move slower.
As for my limited knowledge of Physics, it's still reasonable to think that pulling or pushing out charge carriers would instantaneously collapse/build-up electric field. Not only that, the current must have something similar to a "momentum", even though electrons have extremely low mass.
I really don't have the time to read through all these articles and even if I did, my Physics is lacking. So can anybody just summarize this for me, or point to a shortened article?
Has there been any design of a MOSFET Gate Driver that deals with this issue?
EDIT:
Perhaps what I should've said is *"Hysteresis in MOSFET's response time"* (or maybe this is still incorrect?). I don't know what's wrong with me tonight. I'm shifting my sleeping schedule, so I already feel groggy. | 2016/03/01 | [
"https://electronics.stackexchange.com/questions/220170",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/58458/"
] | I have been studying/working with MOSFETs for 25 years and I've **never** heard/read about *"hysteresis in a MOSFET's I-V characteristics"*. So in my opinion: **it does not exist**.
Maybe it exists on a theoretical level but in practice I have yet to see it before I believe it exists.
The only hysteresis that you would encounter regarding a MOSFET is the hysteresis that you add with the surrounding circuit.
Please link to one or more of the articles where you see this phenomenon mentioned so I can have a look myself. | Vishay manufactured this FET. IR fabbed devices have similar performance.
A Fairchild FTP3P20 performs as expected. [](https://i.stack.imgur.com/SvWUq.jpg) |
220,170 | I've skimmed through several sparse articles online about hysteresis in a MOSFET's I-V characteristics. What I found was sparse, but some articles attribute uneven-ness in the gate structure, causing some charge to move slower.
As for my limited knowledge of Physics, it's still reasonable to think that pulling or pushing out charge carriers would instantaneously collapse/build-up electric field. Not only that, the current must have something similar to a "momentum", even though electrons have extremely low mass.
I really don't have the time to read through all these articles and even if I did, my Physics is lacking. So can anybody just summarize this for me, or point to a shortened article?
Has there been any design of a MOSFET Gate Driver that deals with this issue?
EDIT:
Perhaps what I should've said is *"Hysteresis in MOSFET's response time"* (or maybe this is still incorrect?). I don't know what's wrong with me tonight. I'm shifting my sleeping schedule, so I already feel groggy. | 2016/03/01 | [
"https://electronics.stackexchange.com/questions/220170",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/58458/"
] | Vishay manufactured this FET. IR fabbed devices have similar performance.
A Fairchild FTP3P20 performs as expected. [](https://i.stack.imgur.com/SvWUq.jpg) | If you look at the curves from an IRF9510, they do not conform to the expected results. I found this out when I tried to use one for a linear application. P-CH MOSFETs from other manufacturers do not, in general, have the same behavior. In the image below, the gate voltage is offset by an external power supply to just below the threshold voltage.
What I do not know, is the effect that causes this behavior. If you have this info, please help me out.[](https://i.stack.imgur.com/wxEm0.jpg)
I have been told that IR developed these MOSFETs for switching applications only. The N-CH FETs do not behave this way. |
52,539,941 | I have a macro where I am going through columns and identifying whether the "top" cell (row 7, because there are various irrelevant headers) matches certain specified values, and then performing various actions.
The problem is that some of the headers are merged cells. This means that the code correctly recognises only columns which align with the left-most column which the header cell straddles. Clearly, I need to change this to resolve this.
I don't know how to get this to record a value for, e.g., column D and Column E, where a merged cell in both column D and E says "manager" or "director".
For the moment, I've just included a made-up action ("y = 22") because I'm trying to get the basic principle right before progressing.
```
Sub LabourCalc()
Dim x As Variant
Dim y As Variant
Workbooks("XXX").Activate
Sheets("XXX").Activate
For x = 1 To 10
If InStr(Cells(7, x).Value, "MANAGER") _
Or InStr(Cells(7, x).Value, "manager") _
Or InStr(Cells(7, x).Value, "Manager") _
Or InStr(Cells(7, x).Value, "DIRECTOR") _
Or InStr(Cells(7, x).Value, "Director") _
Or InStr(Cells(7, x).Value, "director") Then
y = 22
End If
Next x
End Sub
``` | 2018/09/27 | [
"https://Stackoverflow.com/questions/52539941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6078710/"
] | Use the [`Range.MergeArea`](https://learn.microsoft.com/en-us/office/vba/api/excel.range.mergearea) property.
>
> Returns a Range object that represents the merged range containing the specified cell. If the specified cell isn't in a merged range, this property returns the specified cell.
>
>
>
So for example, if `D7:E7` is a merged cell:
* `Cells(7, 4).MergeArea.Cells(1, 1)` refers to `D7`
* `Cells(7, 5).MergeArea.Cells(1, 1)` *also* refers to `D7`. Cell `E7` is empty.
And if `F7` is *not* a merged cell:
* `Cells(7, 6).MergeArea.Cells(1, 1)` refers to `F7`.
As pointed out by @ValonMiller in the comments, you can simplify the multiple `InStr` instances by first converting the contents of `Cells(7, x)` to uppercase using `UCase`.
Your final loop then could look like:
```
With Workbooks("XXX").Sheets("XXX")
For x = 1 To 10
With .Cells(7, x).MergeArea.Cells(1, 1)
If InStr(UCase(.Value), "MANAGER") > 0 Or InStr(UCase(.Value), "DIRECTOR") > 0 Then
' Do your stuff here
End If
End With
Next x
End With
``` | All those comments and no one provided an actual working answer. Try this:
```
Sub LabourCalc()
Dim wb as Workbook
Set wb = Workbooks("XXX")
Dim ws as Worksheet
Set ws = wb.Worksheets("XXX")
For x = 1 To 10
Select Case UCase$(ws.Cells(7,x).MergeArea.Cells(1,1))
Case is = "MANAGER","DIRECTOR"
'do stuff here
End Select
Next
End Sub
```
If you need to check if the Manager or Director appear within the cell do this:
```
Dim checkValue as String
checkValue = UCase$(ws.Cells(7,x).MergeArea.Cells(1,1))
Select Case Instr(checkValue,"MANAGER") > 0 Or Instr(checkValue,"DIRECTOR") > 0
Case is = True
'do stuff
End Select
``` |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | After Android 4.3 on some devices, you can't get direct write access to FileSystem on SDcard.
You should use [storage access framework](https://developer.android.com/guide/topics/providers/document-provider.html) for that. | You can't copy or Delete files & Folder on external storage using third party app. like [file explorer].
It's data policy updated after **KITKAT** Version.
If only allow on system apps. So you can use an original file explorer (Come from ROM).
IF you need to use 3rd party app then **ROOT** your device. (Root permission is required) |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | As suggested by @CommonsWare here we have to use the new Storage Access Framework provided by android and will have to take permission from user to write SD card file as you said this is already written in the File Manager Application ES File Explorer.
Here is the code for Letting the user choose the "SD card" :
```
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);
```
which will look somewhat like this :
[](https://i.stack.imgur.com/8zjcC.png)
And get the Document path in `pickedDir`and pass further in your copyFile block
and use this path for writing the file :
```
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
}
}
public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
//out = new FileOutputStream(outputPath + inputFile);
DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
out = getContentResolver().openOutputStream(file.getUri());
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
``` | I have also got that problem but i solved by use the request the permission in run time and after forcefully give the permission.After the permission in App info of Android device. after declare the permission in manifest =>go to setting of your device => go to app info => go to permission =>
and finally allow the permission . just remember i just talking about after api level 22 means from marshmallow. |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | As suggested by @CommonsWare here we have to use the new Storage Access Framework provided by android and will have to take permission from user to write SD card file as you said this is already written in the File Manager Application ES File Explorer.
Here is the code for Letting the user choose the "SD card" :
```
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);
```
which will look somewhat like this :
[](https://i.stack.imgur.com/8zjcC.png)
And get the Document path in `pickedDir`and pass further in your copyFile block
and use this path for writing the file :
```
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
}
}
public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
//out = new FileOutputStream(outputPath + inputFile);
DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
out = getContentResolver().openOutputStream(file.getUri());
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
``` | Its seems the runtime permission are implemented correctly but the issues seems from the device
If you are using Redmi than you have to manually allow the permission of specific app in Redmi security settings
This [link](http://xiaomiadvices.com/miui7-enable-permission-manager-xiaomi-mi-redmi-phones/) shows how to enable permission in redmi security |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | As suggested by @CommonsWare here we have to use the new Storage Access Framework provided by android and will have to take permission from user to write SD card file as you said this is already written in the File Manager Application ES File Explorer.
Here is the code for Letting the user choose the "SD card" :
```
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);
```
which will look somewhat like this :
[](https://i.stack.imgur.com/8zjcC.png)
And get the Document path in `pickedDir`and pass further in your copyFile block
and use this path for writing the file :
```
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
}
}
public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
//out = new FileOutputStream(outputPath + inputFile);
DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
out = getContentResolver().openOutputStream(file.getUri());
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
``` | You need to add permission request run time in Android 6.0 (API Level 23) and up, here is the [official](https://developer.android.com/training/permissions/requesting.html) docs
This is the code for `WRITE_EXTERNAL_STORAGE`
```
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
```
Ask for permission else like this
```
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
``` |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | You need to add permission request run time in Android 6.0 (API Level 23) and up, here is the [official](https://developer.android.com/training/permissions/requesting.html) docs
This is the code for `WRITE_EXTERNAL_STORAGE`
```
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
```
Ask for permission else like this
```
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
``` | I have also got that problem but i solved by use the request the permission in run time and after forcefully give the permission.After the permission in App info of Android device. after declare the permission in manifest =>go to setting of your device => go to app info => go to permission =>
and finally allow the permission . just remember i just talking about after api level 22 means from marshmallow. |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | You need to add permission request run time in Android 6.0 (API Level 23) and up, here is the [official](https://developer.android.com/training/permissions/requesting.html) docs
This is the code for `WRITE_EXTERNAL_STORAGE`
```
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
```
Ask for permission else like this
```
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
``` | You can't copy or Delete files & Folder on external storage using third party app. like [file explorer].
It's data policy updated after **KITKAT** Version.
If only allow on system apps. So you can use an original file explorer (Come from ROM).
IF you need to use 3rd party app then **ROOT** your device. (Root permission is required) |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | I have also got that problem but i solved by use the request the permission in run time and after forcefully give the permission.After the permission in App info of Android device. after declare the permission in manifest =>go to setting of your device => go to app info => go to permission =>
and finally allow the permission . just remember i just talking about after api level 22 means from marshmallow. | I can see that you are copying the entire content of one file and trying to write the same to another file. I could suggest a better way to do this :
Assuming that you already checked for file existence
```
StringWriter temp=new StringWriter();
try{
FileInputStream fis=new FileInputStream(inputFile+inputPath);
int i;
while((i=fis.read())!=-1)
{
temp.write((char)i);
}
fis.close();
FileOutputStream fos = new FileOutputStream(outputPath, false); // true or false based on opening mode as appending or writing
fos.write(temp.toString(rs1).getBytes());
fos.close();
}
catch (Exception e){}
```
This code worked for my app...Let me know if this is working for you or not.. |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | I have also got that problem but i solved by use the request the permission in run time and after forcefully give the permission.After the permission in App info of Android device. after declare the permission in manifest =>go to setting of your device => go to app info => go to permission =>
and finally allow the permission . just remember i just talking about after api level 22 means from marshmallow. | After Android 4.3 on some devices, you can't get direct write access to FileSystem on SDcard.
You should use [storage access framework](https://developer.android.com/guide/topics/providers/document-provider.html) for that. |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | You need to add permission request run time in Android 6.0 (API Level 23) and up, here is the [official](https://developer.android.com/training/permissions/requesting.html) docs
This is the code for `WRITE_EXTERNAL_STORAGE`
```
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Permission is granted");
return true;
}
```
Ask for permission else like this
```
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
``` | Its seems the runtime permission are implemented correctly but the issues seems from the device
If you are using Redmi than you have to manually allow the permission of specific app in Redmi security settings
This [link](http://xiaomiadvices.com/miui7-enable-permission-manager-xiaomi-mi-redmi-phones/) shows how to enable permission in redmi security |
43,066,117 | I'm trying to copy file from within my application to the SD card, but I get the error **eacces (permission denied)**. The OS is Android M and I have allowed runtime Storage permissions (checked in app info). I have also set the uses-permission in AndroidManifest.xml
```
<application>...</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
Doesn't work if I copy to SD card
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)
```
Works if I copy to internal storage
```
Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/
```
Code to copy file from source to destination
```
/*
* Below are the parameters I have tried
*
* inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
* inputFile - /SomeFile.txt or SomeFile.txt
* outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
*/
public static void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
}
catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
```
ES File Explorer
----------------
I saw that ES File Explorer also cannot write anything on the SD Card on Redmi devices. [Here's a video with solution](https://youtu.be/q0w3kZm3XA4). Following the steps worked for ES Explorer on my device. Can this be done programmatically? | 2017/03/28 | [
"https://Stackoverflow.com/questions/43066117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/864850/"
] | As suggested by @CommonsWare here we have to use the new Storage Access Framework provided by android and will have to take permission from user to write SD card file as you said this is already written in the File Manager Application ES File Explorer.
Here is the code for Letting the user choose the "SD card" :
```
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);
```
which will look somewhat like this :
[](https://i.stack.imgur.com/8zjcC.png)
And get the Document path in `pickedDir`and pass further in your copyFile block
and use this path for writing the file :
```
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
else {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
}
}
public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
//out = new FileOutputStream(outputPath + inputFile);
DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
out = getContentResolver().openOutputStream(file.getUri());
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
// write the output file (You have now copied the file)
out.flush();
out.close();
} catch (FileNotFoundException fnfe1) {
/* I get the error here */
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
``` | You can't copy or Delete files & Folder on external storage using third party app. like [file explorer].
It's data policy updated after **KITKAT** Version.
If only allow on system apps. So you can use an original file explorer (Come from ROM).
IF you need to use 3rd party app then **ROOT** your device. (Root permission is required) |
41,688,966 | I am working with a dataset of hourly temperatures and I need to calculate "degree hours" above a heat threshold for each extreme event. I intend to run stats on the intensities (combined magnitude and duration) of each event to compare multiple sites over the same time period.
Example of data:
```
Temp
1 14.026
2 13.714
3 13.25
.....
21189 12.437
21190 12.558
21191 12.703
21192 12.896
```
Data after selecting only hours above the threshold of 18 degrees and then subtracting 18 to reveal degrees above 18:
```
Temp
5297 0.010
5468 0.010
5469 0.343
5470 0.081
5866 0.010
5868 0.319
5869 0.652
```
After this step I need help to sum consecutive hours during which the reading exceeded my specified threshold.
What I am hoping to produce out of above sample:
```
Temp
1 0.010
2 0.434
3 0.010
4 0.971
```
I've debated manipulating these data within a time series or by adding additional columns, but I do not want multiple rows for each warming event. I would immensely appreciate any advice. | 2017/01/17 | [
"https://Stackoverflow.com/questions/41688966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7428358/"
] | This is an alternative solution in base R.
You have some data that walks around, and you want to sum up the points above a cutoff. For example:
```
set.seed(99999)
x <- cumsum(rnorm(30))
plot(x, type='b')
abline(h=2, lty='dashed')
```
which looks like this:
[](https://i.stack.imgur.com/WrdmK.png)
First, we want to split the data in to groups based on when they cross the cutoff. We can use run length encoding on the indicator to get a compressed version:
```
x.rle <- rle(x > 2)
```
which has the value:
```
Run Length Encoding
lengths: int [1:8] 5 2 3 1 9 4 5 1
values : logi [1:8] FALSE TRUE FALSE TRUE FALSE TRUE ...
```
The first group is the first 5 points where x > 2 is FALSE; the second group is the two following points, and so on.
We can create a group id by replacing the values in the rle object, and then back transforming:
```
x.rle$values <- seq_along(x.rle$values)
group <- inverse.rle(x.rle)
```
Finally, we aggregate by group, keeping only the data above the cut off:
```
aggregate(x~group, subset = x > 2, FUN=sum)
```
Which produces:
```
group x
1 2 5.113291213
2 4 2.124118005
3 6 11.775435706
4 8 2.175868979
``` | I'd use `data.table` for this, although there are certainly other ways.
```
library( data.table )
setDT( df )
temp.threshold <- 18
```
First make a column showing the *previous* value from each one in your data. This will help to find the point at which the temperature rose above your threshold value.
```
df[ , lag := shift( Temp, fill = 0, type = "lag" ) ]
```
Now use that previous value column to compare with the `Temp` column. Mark every point at which the temperature rose above the threshold with a 1, and all other points as 0.
```
df[ , group := 0L
][ Temp > temp.threshold & lag <= temp.threshold, group := 1L ]
```
Now we can get `cumsum` of that new column, which will give each sequence after the temperature rose above the threshold its own `group` ID.
```
df[ , group := cumsum( group ) ]
```
Now we can get rid of every value not above the threshold.
```
df <- df[ Temp > temp.threshold, ]
```
And summarise what's left by finding the "degree hours" of each "group".
```
bygroup <- df[ , sum( Temp - temp.threshold ), by = group ]
```
I modified your input data a little to provide a couple of test events where the data rose above threshold:
```
structure(list(num = c(1L, 2L, 3L, 4L, 5L, 21189L, 21190L, 21191L,
21192L, 21193L, 21194L), Temp = c(14.026, 13.714, 13.25, 20,
19, 12.437, 12.558, 12.703, 12.896, 21, 21)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -11L), .Names = c("num",
"Temp"), spec = structure(list(cols = structure(list(num = structure(list(), class = c("collector_integer",
"collector")), Temp = structure(list(), class = c("collector_double",
"collector"))), .Names = c("num", "Temp")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
```
With that data, here's the output of the code above (note `$V1` is in "degree hours"):
```
> bygroup
group V1
1: 1 3
2: 2 6
``` |
23,160,844 | I just used `check out head` after making a commit. I figured that doing this checkout would not actually do anything, but I seem to have been wrong. It put me into a 'detached head' state. I ignored this note, and continued to make a few additional commits. The message change to 'Head detached from ...' Feeling a bit annoyed by this, I looked for a way to fix it. The answer I found was `git checkout master`. I did this and now my last few commits disappeared. What happened here? | 2014/04/18 | [
"https://Stackoverflow.com/questions/23160844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370337/"
] | ### TL;DR
Use `git reflog` to find the lost commits. Give them a name—e.g., a branch name—and then consider whether to copy them to new-and-improved commits, perhaps using `git cherry-pick` or `git rebase`.
### Long
It's not clear to me what you did to get into "detached HEAD" state. (Anything that checks out a commit by any identifier *other than* a branch-name will do that. For instance, if you give `git checkout` a tag name, or a remote-trackng name like `origin/master`, it will detach. Likewise, if you check out a specific commit by its hash-ID, you'll be in that mode. You can also deliberately do it even when checking out a commit by branch-name, using `--detach`, although I imagine that was not it.)
Note: `HEAD` is, at least currently, implemented as a plain-text file inside the `.git` directory. This file normally contains *the name of a branch*. When it does, Git says that you are "on" that branch: `git status` will say `on branch master` or `on branch branch`, for instance. In *detached HEAD* mode, the file *doesn't* have a name in it (see below for more). In this case `git status` will say `HEAD detached at ...` or `HEAD detached from ...` or similar (the exact phrasing varies depending on several items, including your particular Git version).
Here's how I like to draw commit graphs:
```
...--D--E--F <-- master
\
G <-- branch (HEAD)
```
This represents a `master` branch with a bunch of commits, and a branch named `branch` with one commit on it (commit `G`) that is not on `master`. Here `master` has two commits that are not on `branch` (commits `E` and `F`): The branch name `master` "points to" commit `F` (has commit `F`'s hash-ID in it), commit `F` points to commit `E` (by listing the raw hash ID for `E` as its parent), commit `E` points to `D`, and so on. The branch name `branch` points to commit `G`, and `G` points to `D`. The `(HEAD)` part says that HEAD is *attached*, to the name `branch`.
In this state, if you make a new commit, it's added as usual. If we label the new commit `H`, commit `H`'s parent-commit is commit `G`, and `branch` is updated to point to commit `H`, giving:
```
...--D--E--F <-- master
\
G--H <-- branch (HEAD)
```
When you are in this "detached HEAD" mode, on the other hand, `HEAD` does not contain the name of a branch. Instead, it contains a raw hash-ID, identifying the "current commit". Let's say you decide to take a look at commit `E` above:
```
$ git checkout master^ # some windows users may have to write ^^
```
`master^` identifies commit `E`, and is not a branch name because it has that `^` character in it, so this gets you on to commit `E` (and I have to use another row to raise `F` so that I can draw in the arrow for `HEAD`):
```
F <-- master
/
...--D--E <-- HEAD
\
G--H <-- branch
```
Now, if you are in this state and add new commits, they are added in the same way as always—but there is no branch to update, so Git writes each new commit's ID directly into `HEAD`. Let's say we now create commit `I`:
```
F <-- master
/
...--D--E--I <-- HEAD
\
G--H <-- branch
```
Commit `I` has commit `E` as its parent, and `HEAD` now points to commit `I`. However, if you decide you want to go look at `branch` again:
```
$ git checkout branch
```
how will you now locate commit `I`? The only *name* it had was `HEAD`, and after the above checkout, the picture now looks like this:
```
F <-- master
/
...--D--E--I
\
G--H <-- branch (HEAD)
```
(Note: if you made more than one commit while in "detached HEAD" state, they might be commits `I-J-K` for instance. This doesn't change any of what you need to do below, except to make it a bit more work to be sure you have the *last* commit, `K`. I'll just use the one commit `I` below.)
There's no label letting you find commit `I`. You can't find it from commit `E`: `E`'s parent is still only `D`, and `E` does *not* list its children. You cannot find it from commits `F`, `G`, or `H` either; none of them are even related. Commit `I` is "abandoned", and in about a month it will truly go away.
However, as [Nikhil Gupta noted](https://stackoverflow.com/a/23161062/1256452), there *is* still a way to find commit `I` (until it is collected in about a month): it's stored in what git calls the "reflog". (Or more precisely, "a" reflog: there's one reflog for each branch, plus one big one for `HEAD`.) In fact, it's the reflog itself that keeps commit `I` around for about-a-month. Abandoned repository objects are still name-able through reflog references, but those reflog entries expire. Once the reflog entry for commit `I` expires, if you have not attached a more-permanent link to it, git's garbage-collection process will truly delete it.
So, to get your commits back, use `git reflog` to view the `HEAD` reflog. This will show you things like `54ce513 HEAD@{3}: commit: foo the bar`. You can supply either `HEAD@{3}` or the abbreviated hash-ID, `54ce513`,1 to various git commands, including `git log` and `git show`.
Once you have a desired hash-ID (or name like `HEAD@{3}`), you can attach a name—a tag or branch name—to it:
```
$ git tag get-it-back 54ce513 # or git tag oops HEAD@{3}
```
or:
```
$ git branch experiment 54ce513
```
and now you can refer to commit `I` with the name `get-it-back` or `experiment`. If you make it a branch name, you have a regular ordinary branch now:
```
F <-- master
/
...--D--E--I <-- experiment
\
G--H <-- branch (HEAD)
```
Once it has a convenient name, you can do whatever you want with it. Or you can (for the ~30 days it sticks around) just refer to it by reflog-name or raw hash-ID. For instance, you could copy the changes in commit `I` onto a new commit on branch `branch` (where `HEAD` is still pointing):
```
$ git cherry-pick 54ce513
```
(`cherry-pick` basically means "find out what I did in that commit, and do it again on the current branch"). Assuming you did *not* attach a name to commit `I`, this would give you:
```
F <-- master
/
...--D--E--I
\
G--H--J <-- branch (HEAD)
```
where the difference in moving from commit `H` to commit `J` is the same2 as the diff from `E` to `I`.
---
1The string `HEAD@{3}` is a "relative reference": "where was `HEAD` 3 changes ago". A hash-ID like `54ce513` is "absolute": it never changes, and is (with the rest of the full ID—this one is abbreviated) the "true name" of the commit. Since `HEAD` changes every time you do a `commit` or `checkout`, if you do `git checkout HEAD@{3}`, it becomes `HEAD@{4}`—although of course `HEAD@{0}` now *also* contains `54ce513`. If you `git checkout 54ce513`, that always works—assuming, of course, that `54ce513` is the actual hash-ID (I made this particular one up).
2More specifically, `git diff` between those commits shows the same changes, with one exception: because cherry-pick uses Git's merge machinery, Git can sometimes tell that you already have some of the changes, and avoid duplicating them. | A detached head is perfectly normal and means that the copy you have point directly to the commit instead of a symbolic-ref in the branch. You can see more details on this [here](https://stackoverflow.com/a/5772882/2279816).
How do you come out of your situation? Well, use `git reflog` to see the stuff you did before `git checkout master` and then use `git merge <sha1>` for the commit that you want to bring back |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | Are you set on using an Array with Accounts?
Other data structures exist, such as the [Set](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) That already filter duplicate entries. Set checks the equals method of the objects being inserted against the elements in the Set. In this case that means you would have to implement an equals method in your Account class, that checks if the names of the account are equal. | If you dont want to use duplicate values then go with **Set** interface which is a part java.util and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element.
For more reference check the following link
[Set in java](https://www.geeksforgeeks.org/set-in-java/) |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | Are you set on using an Array with Accounts?
Other data structures exist, such as the [Set](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) That already filter duplicate entries. Set checks the equals method of the objects being inserted against the elements in the Set. In this case that means you would have to implement an equals method in your Account class, that checks if the names of the account are equal. | With java 8 you can do this
```
boolean nameExists = accounts.stream().anyMatch(account-> "name".equals(account.getName()));
```
or another approach would be storing name and balance as key value pairs in [HashMap](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html), it has a method [containsKey](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#containsKey(java.lang.Object)) to check for the key existence. |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | Are you set on using an Array with Accounts?
Other data structures exist, such as the [Set](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) That already filter duplicate entries. Set checks the equals method of the objects being inserted against the elements in the Set. In this case that means you would have to implement an equals method in your Account class, that checks if the names of the account are equal. | Thank you everyone for commenting! I should have mentioned I'm in my first semester of computer science so everything's still very new to me, but now I've got some more stuff to study up on haha. I decided to go with the for loop suggested by Carlos for simplicity sake.
```
for (Account acc : accounts) {
if (acc.getName().equals(name)) {
System.out.println("That name already exists, please enter a different one.");
continue;
}
``` |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | There are many ways of doing this. Here's a way that requires the least modification to your existing code that I can think of:
```
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
if (accounts.stream().anyMatch(x -> x.getName().equals(name))) {
System.out.println("This name already exists!");
continue;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
```
Alternatively, override `equals` and `hashCode` in `Account`, and store them in a `HashSet<Account>`. You can then check whether something is already in the set at a lower time complexity.
```
// in your Account class
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return name.equals(account.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
// in Bank class
HashSet<Account> accounts = new HashSet<>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
if (!accounts.add(new Account(name, balance))) {
System.out.println("This customer already exists!");
}
}
}
``` | If you dont want to use duplicate values then go with **Set** interface which is a part java.util and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element.
For more reference check the following link
[Set in java](https://www.geeksforgeeks.org/set-in-java/) |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | There are many ways of doing this. Here's a way that requires the least modification to your existing code that I can think of:
```
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
if (accounts.stream().anyMatch(x -> x.getName().equals(name))) {
System.out.println("This name already exists!");
continue;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
```
Alternatively, override `equals` and `hashCode` in `Account`, and store them in a `HashSet<Account>`. You can then check whether something is already in the set at a lower time complexity.
```
// in your Account class
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return name.equals(account.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
// in Bank class
HashSet<Account> accounts = new HashSet<>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
if (!accounts.add(new Account(name, balance))) {
System.out.println("This customer already exists!");
}
}
}
``` | With java 8 you can do this
```
boolean nameExists = accounts.stream().anyMatch(account-> "name".equals(account.getName()));
```
or another approach would be storing name and balance as key value pairs in [HashMap](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html), it has a method [containsKey](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#containsKey(java.lang.Object)) to check for the key existence. |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | There are many ways of doing this. Here's a way that requires the least modification to your existing code that I can think of:
```
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
if (accounts.stream().anyMatch(x -> x.getName().equals(name))) {
System.out.println("This name already exists!");
continue;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
```
Alternatively, override `equals` and `hashCode` in `Account`, and store them in a `HashSet<Account>`. You can then check whether something is already in the set at a lower time complexity.
```
// in your Account class
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return name.equals(account.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
// in Bank class
HashSet<Account> accounts = new HashSet<>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
if (!accounts.add(new Account(name, balance))) {
System.out.println("This customer already exists!");
}
}
}
``` | Thank you everyone for commenting! I should have mentioned I'm in my first semester of computer science so everything's still very new to me, but now I've got some more stuff to study up on haha. I decided to go with the for loop suggested by Carlos for simplicity sake.
```
for (Account acc : accounts) {
if (acc.getName().equals(name)) {
System.out.println("That name already exists, please enter a different one.");
continue;
}
``` |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | With java 8 you can do this
```
boolean nameExists = accounts.stream().anyMatch(account-> "name".equals(account.getName()));
```
or another approach would be storing name and balance as key value pairs in [HashMap](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html), it has a method [containsKey](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#containsKey(java.lang.Object)) to check for the key existence. | If you dont want to use duplicate values then go with **Set** interface which is a part java.util and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element.
For more reference check the following link
[Set in java](https://www.geeksforgeeks.org/set-in-java/) |
52,419,074 | I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.
```
class Bank {
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers() {
String name = "";
double balance;
System.out.println("Enter customer names or q to quit entering names");
while (true) {
name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
break;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));
}
}
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10218609/"
] | Thank you everyone for commenting! I should have mentioned I'm in my first semester of computer science so everything's still very new to me, but now I've got some more stuff to study up on haha. I decided to go with the for loop suggested by Carlos for simplicity sake.
```
for (Account acc : accounts) {
if (acc.getName().equals(name)) {
System.out.println("That name already exists, please enter a different one.");
continue;
}
``` | If you dont want to use duplicate values then go with **Set** interface which is a part java.util and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element.
For more reference check the following link
[Set in java](https://www.geeksforgeeks.org/set-in-java/) |
46,697 | I recently watched an Air Crash Investigation episode where Qantas flight 32 lost an engine shortly after takeoff. It was revealed that a *stud pipe* in a Rolls-Royce engine was made incorrectly, causing the pipe to snap and burst through the engine and the aircraft's wing, severing major hydraulic systems, and causing the ECAM to display pages and pages of errors.
On the final approach, the captain announced he wished to perform a ‘control check’. He said (and this is approximate):
>
> When the aircraft is damaged, you have to certify it is safe to land before you try to land.
>
>
>
I assume this is so that the captain can make the necessary preparations if he feels his aircraft is not safe to land. On flight 32 this was done by moving the stick left and right to simulate lining up with the runway.
---
Perhaps a better question is back to the post's title.
### What are the purposes of in-flight Control Checks?
In my example of Qantas Flight 32, the stick was moved left and right on final approach to simulate lining up with the runway. This was only small left and right control deflections. The flight deck had only minutes until landing. What was the captain expecting to see, or not to see? Can the captain after that brief manoeuvre be aware of his aircraft *enough* to make a decision?
Does this mean then that a Control Check only comes, or should only be done, if you are worried that the aircraft cannot **land**? Can it be done at any other time? In other words: is an in-flight control check **only** done for landing?
---
*SOURCES:*
Wikipedia
Flight 32:
<https://en.m.wikipedia.org/wiki/Qantas_Flight_32> | 2017/12/17 | [
"https://aviation.stackexchange.com/questions/46697",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/18800/"
] | Technically speaking, a control check is part of any pre-flight.
In the case of Qantas 32, one engine had exploded, punching holes in the wing and setting off a host of warnings, so there was a reasonable expectation that some of the controls might also have been damaged.
What the pilot did was put the plane through some basic maneuvers to see how the controls responded in their now potentially damaged form. And found that roll rate had been affected, something he factored in on the subsequent landing. He also found that pitch control had not been affected, which meant he could make a reasonably conventional approach to the runway.
Better to find out how much the controls had been affected when there is time and altitude to recover from an unexpected response, than to find out on final approach, where the margin for recovery is very slim to none at all.
During flight, this is not normal. It is prudent if an inflight incident may have damaged some of the controls, so that the pilot knows the level of controllability they have to work with. | Aircraft control their flight using movable portions of the wing and tail called control surfaces; a control check is a check performed to make sure that they're capable of moving through the range of motion that they're expected to be capable of moving through. In the case of small airplanes, they're connected to the control column directly through the use of small cables, but in large airplanes, they use electrical sensors in the avionics to create electrical signals that then control hydraulics in the wings and tail that move the control surfaces.
In the case of the Qantas plane, the damaged engine might have damaged the control surfaces or the fluid lines that power the hydraulics, so they carried out the check to figure out how much functionality they had so that they could get an idea of how damaged the plane was, and how it would control as they came in for an emergency landing. |
46,697 | I recently watched an Air Crash Investigation episode where Qantas flight 32 lost an engine shortly after takeoff. It was revealed that a *stud pipe* in a Rolls-Royce engine was made incorrectly, causing the pipe to snap and burst through the engine and the aircraft's wing, severing major hydraulic systems, and causing the ECAM to display pages and pages of errors.
On the final approach, the captain announced he wished to perform a ‘control check’. He said (and this is approximate):
>
> When the aircraft is damaged, you have to certify it is safe to land before you try to land.
>
>
>
I assume this is so that the captain can make the necessary preparations if he feels his aircraft is not safe to land. On flight 32 this was done by moving the stick left and right to simulate lining up with the runway.
---
Perhaps a better question is back to the post's title.
### What are the purposes of in-flight Control Checks?
In my example of Qantas Flight 32, the stick was moved left and right on final approach to simulate lining up with the runway. This was only small left and right control deflections. The flight deck had only minutes until landing. What was the captain expecting to see, or not to see? Can the captain after that brief manoeuvre be aware of his aircraft *enough* to make a decision?
Does this mean then that a Control Check only comes, or should only be done, if you are worried that the aircraft cannot **land**? Can it be done at any other time? In other words: is an in-flight control check **only** done for landing?
---
*SOURCES:*
Wikipedia
Flight 32:
<https://en.m.wikipedia.org/wiki/Qantas_Flight_32> | 2017/12/17 | [
"https://aviation.stackexchange.com/questions/46697",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/18800/"
] | Technically speaking, a control check is part of any pre-flight.
In the case of Qantas 32, one engine had exploded, punching holes in the wing and setting off a host of warnings, so there was a reasonable expectation that some of the controls might also have been damaged.
What the pilot did was put the plane through some basic maneuvers to see how the controls responded in their now potentially damaged form. And found that roll rate had been affected, something he factored in on the subsequent landing. He also found that pitch control had not been affected, which meant he could make a reasonably conventional approach to the runway.
Better to find out how much the controls had been affected when there is time and altitude to recover from an unexpected response, than to find out on final approach, where the margin for recovery is very slim to none at all.
During flight, this is not normal. It is prudent if an inflight incident may have damaged some of the controls, so that the pilot knows the level of controllability they have to work with. | Why controllability checks matter
---------------------------------
The procedure you're referring to from the QF32 mishap is called a "controllability check". While a standard control check is done as part of a ground preflight to make sure that the flight controls work well enough to fly, a *controllability* check is an in-flight operation, performed either as part of a functional check flight or, more importantly, *after the aircraft has sustained damage*.
The controllability check is different from an ordinary control check in that while a control check is looking only for flight control motion, range of motion, binding, or free-play, a *controllability* check evaluates the airframe's response to control inputs in-flight at various speeds, typically from a stable clean speed at 10,000' down to a normal landing Vref if all is functional. Flap and gear extension will also be tested if possible as part of this exercise due to their impact on aerodynamics. Of course, if the controls start getting too close to full deflection during what basically is a mock landing approach, the pilots will knock it off and accelerate back to a safer speed, cleaning up the airplane if possible.
As a result of this, the pilots could determine what impact the damage had on airplane handling. For instance, damage to a wing or wing control surfaces could have an impact in roll, while damaged or missing engines can be problematic at low speeds in roll and/or yaw. Tail damage will often manifest itself as pitch control issues, but sometimes can be a yaw problem instead. A load shift or other C.G. issue will also show up as pitch control trouble at low speeds.
A good example of a flight where one *should* have been performed was El Al 1862. Had they performed a controllability check, they'd have noticed that the departure of engines #3 and #4 from the aircraft, as well as the loss of the right outboard aileron and right leading edge devices, had effectively jacked their Vmca up sky-high. With this knowledge in hand, the crew could have recalibrated their expectations, shooting a partial flap approach at a much higher Vref speed to a choice of runway that gave them more favorable winds as they could still maintain flight at this higher speed and would need the headwind to help slow down after landing. |
46,697 | I recently watched an Air Crash Investigation episode where Qantas flight 32 lost an engine shortly after takeoff. It was revealed that a *stud pipe* in a Rolls-Royce engine was made incorrectly, causing the pipe to snap and burst through the engine and the aircraft's wing, severing major hydraulic systems, and causing the ECAM to display pages and pages of errors.
On the final approach, the captain announced he wished to perform a ‘control check’. He said (and this is approximate):
>
> When the aircraft is damaged, you have to certify it is safe to land before you try to land.
>
>
>
I assume this is so that the captain can make the necessary preparations if he feels his aircraft is not safe to land. On flight 32 this was done by moving the stick left and right to simulate lining up with the runway.
---
Perhaps a better question is back to the post's title.
### What are the purposes of in-flight Control Checks?
In my example of Qantas Flight 32, the stick was moved left and right on final approach to simulate lining up with the runway. This was only small left and right control deflections. The flight deck had only minutes until landing. What was the captain expecting to see, or not to see? Can the captain after that brief manoeuvre be aware of his aircraft *enough* to make a decision?
Does this mean then that a Control Check only comes, or should only be done, if you are worried that the aircraft cannot **land**? Can it be done at any other time? In other words: is an in-flight control check **only** done for landing?
---
*SOURCES:*
Wikipedia
Flight 32:
<https://en.m.wikipedia.org/wiki/Qantas_Flight_32> | 2017/12/17 | [
"https://aviation.stackexchange.com/questions/46697",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/18800/"
] | Why controllability checks matter
---------------------------------
The procedure you're referring to from the QF32 mishap is called a "controllability check". While a standard control check is done as part of a ground preflight to make sure that the flight controls work well enough to fly, a *controllability* check is an in-flight operation, performed either as part of a functional check flight or, more importantly, *after the aircraft has sustained damage*.
The controllability check is different from an ordinary control check in that while a control check is looking only for flight control motion, range of motion, binding, or free-play, a *controllability* check evaluates the airframe's response to control inputs in-flight at various speeds, typically from a stable clean speed at 10,000' down to a normal landing Vref if all is functional. Flap and gear extension will also be tested if possible as part of this exercise due to their impact on aerodynamics. Of course, if the controls start getting too close to full deflection during what basically is a mock landing approach, the pilots will knock it off and accelerate back to a safer speed, cleaning up the airplane if possible.
As a result of this, the pilots could determine what impact the damage had on airplane handling. For instance, damage to a wing or wing control surfaces could have an impact in roll, while damaged or missing engines can be problematic at low speeds in roll and/or yaw. Tail damage will often manifest itself as pitch control issues, but sometimes can be a yaw problem instead. A load shift or other C.G. issue will also show up as pitch control trouble at low speeds.
A good example of a flight where one *should* have been performed was El Al 1862. Had they performed a controllability check, they'd have noticed that the departure of engines #3 and #4 from the aircraft, as well as the loss of the right outboard aileron and right leading edge devices, had effectively jacked their Vmca up sky-high. With this knowledge in hand, the crew could have recalibrated their expectations, shooting a partial flap approach at a much higher Vref speed to a choice of runway that gave them more favorable winds as they could still maintain flight at this higher speed and would need the headwind to help slow down after landing. | Aircraft control their flight using movable portions of the wing and tail called control surfaces; a control check is a check performed to make sure that they're capable of moving through the range of motion that they're expected to be capable of moving through. In the case of small airplanes, they're connected to the control column directly through the use of small cables, but in large airplanes, they use electrical sensors in the avionics to create electrical signals that then control hydraulics in the wings and tail that move the control surfaces.
In the case of the Qantas plane, the damaged engine might have damaged the control surfaces or the fluid lines that power the hydraulics, so they carried out the check to figure out how much functionality they had so that they could get an idea of how damaged the plane was, and how it would control as they came in for an emergency landing. |
32,256,171 | So I have a containing element whose width gets smaller as the screen get smaller `#Aa`, this element has a `<nav>` element that contains a `<ul>` element and some `<li>` elements as menu items.
When `#Aa` can no longer contain all the `<li>` elements the page layout is broken.
What I would like to happen is what is suppose to happen when
`overflow:hidden` is used. I applied this rule to `#Aa`.
I thought this was the purpose of `overflow:hidden`. I entered it manually through the web inspector.
Here is **some** of the relevant CSS
```
nav {
white-space: nowrap;
float: right;
}
nav ul li a {
display: inline-block;
padding: 0 20px;
line-height: 60px;
color: #2e2c60;
font-size: 14px;
text-transform: uppercase;
letter-spacing: .1em;
}
nav ul li {
display: inline-block;
float: left;
border-left: 1px solid #ffffff;
position: relative;
list-style: none;
background: rgba(255, 255, 255, .25);
}
nav ul li:hover{
background: rgba(255, 255, 255, 0.5);
}
nav ul li:last-child{
border-right: 1px solid #ffffff;
}
``` | 2015/08/27 | [
"https://Stackoverflow.com/questions/32256171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021893/"
] | This is solved simply by below two lines of code.
```
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 3)
{
foreach (DataRow row in dt1.Rows)
comboBox2.Items.Add(row["course_name"]);
}
}
``` | You could project the data into a collection that has named fields to prevent the default ToString()ing of the datarow objects:
```
if (comboBox1.SelectedIndex == 3)
{
comboBox2.ValueMember = "course_name_value";
comboBox2.DisplayMember = "course_name";
comboBox2.DataSource = dt1.AsEnumerable().Select
(n => new { course_name = n["course_name"], course_name_value = n["course_name"]}).ToList();
}
```
EDIT
I think you should put these lines in the Load event. You don't need to set them more than once, and it could be the reason for the combobox display getting the object's ToString() result instead of individual properties.
```
comboBox2.ValueMember = "course_name";
comboBox2.DisplayMember = "course_name";
``` |
32,256,171 | So I have a containing element whose width gets smaller as the screen get smaller `#Aa`, this element has a `<nav>` element that contains a `<ul>` element and some `<li>` elements as menu items.
When `#Aa` can no longer contain all the `<li>` elements the page layout is broken.
What I would like to happen is what is suppose to happen when
`overflow:hidden` is used. I applied this rule to `#Aa`.
I thought this was the purpose of `overflow:hidden`. I entered it manually through the web inspector.
Here is **some** of the relevant CSS
```
nav {
white-space: nowrap;
float: right;
}
nav ul li a {
display: inline-block;
padding: 0 20px;
line-height: 60px;
color: #2e2c60;
font-size: 14px;
text-transform: uppercase;
letter-spacing: .1em;
}
nav ul li {
display: inline-block;
float: left;
border-left: 1px solid #ffffff;
position: relative;
list-style: none;
background: rgba(255, 255, 255, .25);
}
nav ul li:hover{
background: rgba(255, 255, 255, 0.5);
}
nav ul li:last-child{
border-right: 1px solid #ffffff;
}
``` | 2015/08/27 | [
"https://Stackoverflow.com/questions/32256171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021893/"
] | This is solved simply by below two lines of code.
```
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 3)
{
foreach (DataRow row in dt1.Rows)
comboBox2.Items.Add(row["course_name"]);
}
}
``` | I ran a mock test, and I think it's disposing of your dataset(when it finished the OnLoad event) before you can get to the selectedIndex changed event. Try having your SelectedIndexChanged event raise a function to populate the second box. PS, don't mind I used an SQLite database to test.
```
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If (ComboBox1.SelectedIndex = 3) Then
Select3()
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim range() As String = {"0", "1", "2", "3 - Fire Combo2", "4", "5", "6"}
ComboBox1.Items.AddRange(range)
End Sub
Private Sub Select3()
Dim connectionString As String = MyStandAloneDB.DBConnStr
Dim conn As New System.Data.SQLite.SQLiteConnection(connectionString)
conn.Open()
Dim cmd1 As New System.Data.SQLite.SQLiteCommand
cmd1.Connection = conn
cmd1.CommandType = CommandType.Text
cmd1.CommandText = "SELECT * FROM Foo"
Dim dt1 As New DataTable()
Dim adp1 As New System.Data.SQLite.SQLiteDataAdapter(cmd1)
adp1.Fill(dt1)
ComboBox2.DataSource = dt1
ComboBox2.ValueMember = dt1.Columns(1).ToString
ComboBox2.DisplayMember = dt1.Columns(0).ToString
End Sub
``` |
74,572,453 | I launch my app in eclipse and works fine and I got the initialization of de entityManagerFactory by default as I wish:
```
2022-11-28 13:32:58.558 INFO 12176 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
```
but when I deploy my app by a runnable jar file it is not launching, I'm sharing this question after much research, here is my pom (I'm extracting the libraries into generated jar):
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
</parent>
<groupId>ZpectrumApp</groupId>
<artifactId>ZpectrumApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ZpectrumApp</name>
<description>End-Degree project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec</artifactId>
<version>0.2.3</version>
</dependency>
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec-javase</artifactId>
<version>0.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>ZpectrumApplication.Application</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
I thinks it is possible a incompatibility from one spring-boot version to another dependency, but I'm not certain. Also attach the console trace.
```
ZpectrumApplication: Cannot create inner bean '(inner bean)#71a9b4c7' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#71a9b4c7': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
``` | 2022/11/25 | [
"https://Stackoverflow.com/questions/74572453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18495770/"
] | You have to build and package the jar with dependencies, add the below to your plugins in the pom.xml, change the main mainClass to yours.
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.byteworks.epms.DeviceServiceListener</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
``` | I solve it by deploying the project by command prompt in the next three steps:
* downloading Apache-Maven <https://maven.apache.org/download.cgi>
* following this tutorial: <https://www.youtube.com/watch?v=-ARoNTL90hY>
* modifying the pom.xml with manual configuration -> <https://www.baeldung.com/executable-jar-with-maven> |
37,684,788 | I have a TableviewController : TableViewController.m , this has dynamic cells .
I have subclassed one cell(just one ) to : RegisterTableViewCell.m/.h , have a UIButton in this cell in storyboard and have created an outlet for the same in TableViewcell.m .
I have decalared a custom protocol in TableViewcell to get the click event on button in TableViewController.m . I want to do a segue on click of this button .
RegisterTableViewCell.h
```
@protocol CellDelegate <NSObject>
-(void)didClickOnCellAtIndex:(NSInteger)cellIndex withData:(id)data;
@end
@property (weak,nonatomic) id<CellDelegate>delegate;
@property (assign,nonatomic) NSInteger cellIndex;
@property (weak, nonatomic) IBOutlet UIButton *PopoverAnchorButton;
```
RegisterTableViewCell.m
```
@synthesize PopoverAnchorButton = _PopoverAnchorButton;
- (void)awakeFromNib {
// Initialization code
[self.PopoverAnchorButton addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
//[self.PopoverAnchorButton
}
- (void)didTapButton:(id)sender{
NSLog(@"Anchor Button Pressed");
NSLog(@"self.delegate %d ", [self.delegate isEqual:nil]);
NSLog(@"responds to selector %d ", [self.delegate respondsToSelector:@selector(didClickOnCellAtIndex:withData:)]);
if(self.delegate && [self.delegate respondsToSelector:@selector(didClickOnCellAtIndex:withData:)]){
[self.delegate didClickOnCellAtIndex:_cellIndex withData:@"abc"];
}
}
```
TableViewController.h
```
@interface SideBarTableViewController : UITableViewController <UIPopoverPresentationControllerDelegate ,CellDelegate>
```
TableViewController.m
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
RegisterTableViewCell *cellreg = [[RegisterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"register"];
cellreg.delegate = self;
cellreg.cellIndex = indexPath.row;
return cell;
}
-(void)didClickOnCellAtIndex:(NSInteger)cellIndex withData:(id)data
{
NSLog(@"cell at index %ld clicked",(long)cellIndex);
}
```
Problem:
My didClickOnCellAtIndex func in not called in TableViewController.m .
Even didTapButton func in RegisterTableViewCell.m , the 'if' condition is not executed, - "responds to selector = 0".
Also , i have just subclassed one of cells, whose instance i am getting in cellForRowAtIndexPath, but cellForRowAtIndexPath is called only once the table view is shown .
Won't the ref RegisterTableViewCell \*cellreg and its property cellreg.delegate cleared by the time button on this cell is selected ?
My whole objective is to put a uibutton in some selected cells(for now say just 1) to the right end and when user clicks the cell or this button(preferably cell ), i want to do a popover presentation segue to a vc with popover arrow pointing towards the button .
For this question, my obj is to get the click event on the button in RegisterTableViewCell in TableViewController so that i can call prepareforsegue with the sender from here.
I am stuck at this . Please help. | 2016/06/07 | [
"https://Stackoverflow.com/questions/37684788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3540903/"
] | Yo can try this method: `QGraphicsView::setAlignment(Qt::Alignment alignment)`
([see here](http://doc.qt.io/qt-4.8/qgraphicsview.html))
You would have to use something like:
```
scene->setAlignment(Qt::AlignTop|Qt::AlignLeft);
``` | @rsp1984
Here is an example of a header code for a class based on a QWIdget. I'm copying and pasting only the parts of the code relvant to the question, from work, so please excuse me if it does not compile because I left something out:
The Header:
```
#include <QWidget>
#include <QGraphicsView>
#include <QDesktopWidget>
#include <QVBoxLayout>
#include <QApplication>
#include <QGraphicsScene>
class MonitorScreen : public QWidget
{
Q_OBJECT
public:
explicit MonitorScreen(QWidget *parent = nullptr, const QRect &screen = QRect(), qreal SCREEN_W = 1, qreal SCREEN_H = 1);
private:
QGraphicsView *gview;
};
```
The CPP:
```
#include "monitorscreen.h"
MonitorScreen::MonitorScreen(QWidget *parent, const QRect &screen, qreal SCREEN_W, qreal SCREEN_H) : QWidget(parent)
{
// Making this window frameless and making sure it stays on top.
this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint|Qt::X11BypassWindowManagerHint|Qt::Window);
this->setGeometry(screen);
// Creating a graphics widget and adding it to the layout
gview = new QGraphicsView(this);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0,0,0,0);
layout->addWidget(gview);
gview->setScene(new QGraphicsScene(0,0,screen.width(),screen.height(),this));
gview->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
gview->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// White background
gview->scene()->setBackgroundBrush(QBrush(Qt::gray));
}
```
The idea here is that the scene is the same size as the rect of the QGraphcisView widget. That way something positioned at 100,100 will be a coordinate 100, 100 of in relation to the top left corner of the QGraphicsView. I do this because my scene will NEVER be larger than widget showing it. As a matter of fact they NEED to be the same size due to my particular problem.
Keep in mind that you CAN have a larger (or smaller) scene. If your scene is larger objects that are not withing the visible view will not be drawn, but will still exist in memory.
However I've always found that doing this, greatly facilitates how you start positioning and sizing your items in any given project, as you now know 100% sure where something at any given position should appear. You can then start coding more complex behaviour.
I hope this helps! |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | I think the warning message is quite straightforward. You need to:
```
from hashlib import md5
```
or you can use python < 2.5, <http://docs.python.org/library/md5.html> | i think the warning is ok,still you can use the md5 module,or else hashlib module contains md5 class
```
import hashlib
a=hashlib.md5("foo")
print a.hexdigest()
```
this would print the md5 checksum of the string "foo" |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | That's not an error, that's a warning.
If you still insist on getting rid of it then modify the code so that it uses [`hashlib`](http://docs.python.org/library/hashlib.html) instead. | What about something like this?
```
try:
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
import md5
except ImportError as imp_err:
raise type(imp_err), type(imp_err)("{0}{1}".format(
imp_err.message,"Custom import message"))
``` |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | I think the warning message is quite straightforward. You need to:
```
from hashlib import md5
```
or you can use python < 2.5, <http://docs.python.org/library/md5.html> | please see the docs [here](http://docs.python.org/library/warnings.html) , 28.5.3 gives you a way to suppress deprecate warnings. Or on the command line when you run your script, issue `-W ignore::DeprecationWarning` |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | I think the warning message is quite straightforward. You need to:
```
from hashlib import md5
```
or you can use python < 2.5, <http://docs.python.org/library/md5.html> | As mentioned, the warning can be silenced. And hashlib.md5(my\_string) should do the same as md5.md5(my\_string).
```
>>> import md5
__main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
>>> import hashlib
>>> s = 'abc'
>>> m = md5.new(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> m = hashlib.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> md5(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> md5.md5(s)
<md5 HASH object @ 0x100493260>
>>> m = md5.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
```
As @Dyno Fu says: you may need to track down what your code actually calls from md5. |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | I think the warning message is quite straightforward. You need to:
```
from hashlib import md5
```
or you can use python < 2.5, <http://docs.python.org/library/md5.html> | What about something like this?
```
try:
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
import md5
except ImportError as imp_err:
raise type(imp_err), type(imp_err)("{0}{1}".format(
imp_err.message,"Custom import message"))
``` |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | That's not an error, that's a warning.
If you still insist on getting rid of it then modify the code so that it uses [`hashlib`](http://docs.python.org/library/hashlib.html) instead. | please see the docs [here](http://docs.python.org/library/warnings.html) , 28.5.3 gives you a way to suppress deprecate warnings. Or on the command line when you run your script, issue `-W ignore::DeprecationWarning` |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | As mentioned, the warning can be silenced. And hashlib.md5(my\_string) should do the same as md5.md5(my\_string).
```
>>> import md5
__main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
>>> import hashlib
>>> s = 'abc'
>>> m = md5.new(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> m = hashlib.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> md5(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> md5.md5(s)
<md5 HASH object @ 0x100493260>
>>> m = md5.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
```
As @Dyno Fu says: you may need to track down what your code actually calls from md5. | i think the warning is ok,still you can use the md5 module,or else hashlib module contains md5 class
```
import hashlib
a=hashlib.md5("foo")
print a.hexdigest()
```
this would print the md5 checksum of the string "foo" |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | I think the warning message is quite straightforward. You need to:
```
from hashlib import md5
```
or you can use python < 2.5, <http://docs.python.org/library/md5.html> | That's not an error, that's a warning.
If you still insist on getting rid of it then modify the code so that it uses [`hashlib`](http://docs.python.org/library/hashlib.html) instead. |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | As mentioned, the warning can be silenced. And hashlib.md5(my\_string) should do the same as md5.md5(my\_string).
```
>>> import md5
__main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
>>> import hashlib
>>> s = 'abc'
>>> m = md5.new(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> m = hashlib.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> md5(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> md5.md5(s)
<md5 HASH object @ 0x100493260>
>>> m = md5.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
```
As @Dyno Fu says: you may need to track down what your code actually calls from md5. | please see the docs [here](http://docs.python.org/library/warnings.html) , 28.5.3 gives you a way to suppress deprecate warnings. Or on the command line when you run your script, issue `-W ignore::DeprecationWarning` |
2,084,407 | I'm using an older version of PLY that uses the md5 module (among others):
```
import re, types, sys, cStringIO, md5, os.path
```
... although the script runs but not without this error:
```
DeprecationWarning: the md5 module is deprecated; use hashlib instead
```
How do I fix it so the error goes away?
Thanks | 2010/01/18 | [
"https://Stackoverflow.com/questions/2084407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | That's not an error, that's a warning.
If you still insist on getting rid of it then modify the code so that it uses [`hashlib`](http://docs.python.org/library/hashlib.html) instead. | i think the warning is ok,still you can use the md5 module,or else hashlib module contains md5 class
```
import hashlib
a=hashlib.md5("foo")
print a.hexdigest()
```
this would print the md5 checksum of the string "foo" |
35,780,647 | The project I'm working on uses C# WebAPI 2, and used to use Windows Active Directory authentication for everything. We're attempting to transition to Basic auth using a `AuthorizationFilterAttribute`, but IIS Express is making that quite difficult. Originally any request with Basic auth with get a `401.2` response because Basic auth wasn't enabled. To fix this I added:
```
<basicAuthentication enabled="false" />
```
to **applicationhost.config**. Now all requests with a Basic auth header get a `401.1` error, as if IIS Express tries to authenticate the request itself, without going through the attribute.
I created a blank project and attempted the same set up, and it worked fine! I compared **applicationhost.config**, **web.config**, and **Global.asax.cs** of the two projects, and everything appears to be the same. So I can't figure out why IIS Express isn't cooperating for the initial project.
What other files / config settings should I look at to get this resolved? | 2016/03/03 | [
"https://Stackoverflow.com/questions/35780647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029096/"
] | You may need to look in App\_Start/Startup.Auth.cs . If it's using OWIN, you'll need to add the basic auth module to the pipeline. | Did you check the authentication mode to make sure it's not set to 'Windows'?
```
<authentication mode="Forms">
``` |
62,712,771 | Think I have 2 collection:
1. Man: the documents are-
```
[
{ _id: 1,
name: 'Jack',
children: ['Joy','Joe','James']
},
{ _id: 2,
name: 'Molly',
children: ['Milly','Mou']
}
]
```
2. Age
```
[{_id:1, name: "Joy", age:10},
{_id:2, name: "Joe", age:12},
{_id:3, name: "James", age:14},
{_id:4, name: "Milly", age:9},
{_id:5, name: "Mou", age: 6}
]
```
I am wanting to create a single aggregate,
where in 1st phase I will find Jack's all children (`children` array) and in 2nd phase I will find the age of all children in collection `age` using the `children` array.
Expected output:
```
[
{ name: "Joy", age:10},
{name: "Joe", age:12},
{name: "James", age:14},
]
```
How can I do this,without $lookup? | 2020/07/03 | [
"https://Stackoverflow.com/questions/62712771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585327/"
] | Set #myInput and bind the focus event
`<input #myInput (focus)="onFocus()">`
```
@ViewChild('myInput') myInput: ElementRef<HTMLInputElement>;
```
and
```
onFocus() {
setTimeout(() => {
this.myInput.nativeElement.setSelectionRange(0,0);
}, 0)
}
```
The timeout is required because when you select an input with the tab key, the text is automatically selected right after the focus event. | For setting the elements as unselectable, you can use `tabindex = -1` attribute in the input element like following-
`<input tabindex='-1'>`
>
> A negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with Javascript or visually by clicking with the mouse.
>
>
>
You can check more about this here- [tabindex MDN guide](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex)
Hope this will help you. |
62,712,771 | Think I have 2 collection:
1. Man: the documents are-
```
[
{ _id: 1,
name: 'Jack',
children: ['Joy','Joe','James']
},
{ _id: 2,
name: 'Molly',
children: ['Milly','Mou']
}
]
```
2. Age
```
[{_id:1, name: "Joy", age:10},
{_id:2, name: "Joe", age:12},
{_id:3, name: "James", age:14},
{_id:4, name: "Milly", age:9},
{_id:5, name: "Mou", age: 6}
]
```
I am wanting to create a single aggregate,
where in 1st phase I will find Jack's all children (`children` array) and in 2nd phase I will find the age of all children in collection `age` using the `children` array.
Expected output:
```
[
{ name: "Joy", age:10},
{name: "Joe", age:12},
{name: "James", age:14},
]
```
How can I do this,without $lookup? | 2020/07/03 | [
"https://Stackoverflow.com/questions/62712771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585327/"
] | Just set `target.selectionEnd` to 0 on focus event
```html
<input (focus)="unselectOnFocus($event)">
```
```js
unselectOnFocus(event: Event): void {
event.target.selectionEnd = 0;
}
``` | For setting the elements as unselectable, you can use `tabindex = -1` attribute in the input element like following-
`<input tabindex='-1'>`
>
> A negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with Javascript or visually by clicking with the mouse.
>
>
>
You can check more about this here- [tabindex MDN guide](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex)
Hope this will help you. |
62,712,771 | Think I have 2 collection:
1. Man: the documents are-
```
[
{ _id: 1,
name: 'Jack',
children: ['Joy','Joe','James']
},
{ _id: 2,
name: 'Molly',
children: ['Milly','Mou']
}
]
```
2. Age
```
[{_id:1, name: "Joy", age:10},
{_id:2, name: "Joe", age:12},
{_id:3, name: "James", age:14},
{_id:4, name: "Milly", age:9},
{_id:5, name: "Mou", age: 6}
]
```
I am wanting to create a single aggregate,
where in 1st phase I will find Jack's all children (`children` array) and in 2nd phase I will find the age of all children in collection `age` using the `children` array.
Expected output:
```
[
{ name: "Joy", age:10},
{name: "Joe", age:12},
{name: "James", age:14},
]
```
How can I do this,without $lookup? | 2020/07/03 | [
"https://Stackoverflow.com/questions/62712771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585327/"
] | Just set `target.selectionEnd` to 0 on focus event
```html
<input (focus)="unselectOnFocus($event)">
```
```js
unselectOnFocus(event: Event): void {
event.target.selectionEnd = 0;
}
``` | Set #myInput and bind the focus event
`<input #myInput (focus)="onFocus()">`
```
@ViewChild('myInput') myInput: ElementRef<HTMLInputElement>;
```
and
```
onFocus() {
setTimeout(() => {
this.myInput.nativeElement.setSelectionRange(0,0);
}, 0)
}
```
The timeout is required because when you select an input with the tab key, the text is automatically selected right after the focus event. |
13,888,663 | i've looked through many posts on here and couldn't quite see the solution I need...
I'm getting the error:
```
the method initTimer(untitled.Object, String, int int) in the type untitled.TimerClass is not applicable for the arguments (untitled.Toon, String, int, int)
```
and it's driving me crazy.
```
timers.initTimer(character, "regenAdd", 0,3);
```
The above line is the one throwing the error and the following is the function:
```
public void initTimer(final Object obj, final String method, int delay, int period) {
delay*=1000;
period*=1000;
final Class<?> unknown = obj.getClass();
new Timer().schedule(new TimerTask() {
public void run() {
try {
//get the method from the class
Method whatToDo = unknown.getMethod(method, null);
try {
//invoke() the object method
whatToDo.invoke(obj);
} catch(Exception e) {
println("Exception encountered: " + e);
}
} catch(NoSuchMethodException e) {
println("Exception encountered: " + e);
}
runState = getTimerState();
if (!runState) {
println("timer dead");
this.cancel();
}
}
}
, delay, period);
}
```
Thanks in advance to anybody who can help with this :)
Additional info:
>
> runState is a boolean just incase you couldn't guess and
> character is an instance of the Toon class; the above method is within
> the TimerClass class and 'timers' is an instance of that class.
>
>
> | 2012/12/15 | [
"https://Stackoverflow.com/questions/13888663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1446063/"
] | The error message
>
> the method `initTimer(untitled.Object, String, int int)` in the type `untitled.TimerClass` is not
> applicable for the arguments `(untitled.Toon, String, int, int)`
>
>
>
is due to the fact that `untitled.Toon` does not extend `untitled.Object`. It extends `java.lang.Object` of course, which is why the reason is not immediately obvious from the source code. | Also, another error is initTimer(untitled.Object, String, int) is being called as (untitled.Toon, String, int, int) - notice the difference in number of arguments - 1 int in method declaration and 2 int in calling the method.
Please remember to correct that also. |
898,443 | I'm reading from the standard input using the read() system call but there's a tiny thing that bothers me. I can't use the arrow keys... What I really wanted to do was to use arrow keys to go back and forth within the typed text but I think that's not that easy... So, what I at least want to do, is to ignore them.
Right now, pressing any of the arrow keys produces strange output and I want to prevent anything from being written to the standard output (consequently read from the standard input in my read() system call).
Is this easily possible to achieve or it's not that easy? | 2009/05/22 | [
"https://Stackoverflow.com/questions/898443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40480/"
] | In order to interpret the arrow keys the way you would ideally like to (i.e. to move back and forth and edit the input), you generally need to use a library. For Linux, the standard is [GNU Readline](http://tiswww.case.edu/php/chet/readline/rltop.html). Hopefully someone else can say what you would normally use for a Windows CLI app. | The answer ultimately depends on where the keys come from. I ran this program under Cygwin:
```
int main(void)
{
int c=0;
while( c != 'X' ) {
c = getchar();
printf("\nc=%d", c);
}
}
```
Every time a cursor key comes along, I see escape (27), a bracket, plus another character.
So, if you get results like that, you can skip 3 keys every time you see a 27. You could also look at them and make use of them!
As mentioned, YMMV, especially for the O.S., and the actual key-getting function you call. |
11,334,913 | What is the proper way of inserting a copyright symbol `©` and a pound sterling symbol `£` into a bash script.
I am using `nano` as my editor and am running Debian Squeeze.
If I copy and paste the symbol from windows, it works but it seems to paste hidden characters that `nano` cannot display and it makes it hard to edit code in the shell script then.
So for example I want to be able to do this:-
```
text="£15.00"
text2="© John Doe"
``` | 2012/07/04 | [
"https://Stackoverflow.com/questions/11334913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317603/"
] | It seems you are using a locale that doesn't support these symbols (in the olden days it could have also been a bad font). Since you are using UTF-8 characters (default on windows), you also need to be in a UTF-8 aware environment on linux. You can check that with the `locale` command:
```
$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
```
So my system is fine, but yours had the default, ASCII C locale set. These are simple `bash` variables, so you could `export` them individually or override them all (by setting `LC_ALL`). However, that would only affect the current shell, so you need to make it part of shell initialisation to work everytime automatically.
This is usually done through profile scripts in `/etc` globally, but `.bash_profile` or `.bashrc` would work just as well. In your version of Debian the locale is stored in `/etc/default/locale` and you can get the list of available choices with `locale -a`, eg.:
```
$ locale -a
C
en_US
en_US.iso88591
en_US.utf8
POSIX
sl_SI.utf8
```
Pick one with an utf8 suffix. If you need other locales (for example japanese), they can be generated with localedef/locale-gen (comes with `glibc` or as a separate package). | Better just use (C) for copyright, you want it to be always readable in other locales and not a defense for violation.
The display looks like
```
text="1.00"
text2=" ohn Doe"
```
in my test terminal. |
11,334,913 | What is the proper way of inserting a copyright symbol `©` and a pound sterling symbol `£` into a bash script.
I am using `nano` as my editor and am running Debian Squeeze.
If I copy and paste the symbol from windows, it works but it seems to paste hidden characters that `nano` cannot display and it makes it hard to edit code in the shell script then.
So for example I want to be able to do this:-
```
text="£15.00"
text2="© John Doe"
``` | 2012/07/04 | [
"https://Stackoverflow.com/questions/11334913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317603/"
] | It seems you are using a locale that doesn't support these symbols (in the olden days it could have also been a bad font). Since you are using UTF-8 characters (default on windows), you also need to be in a UTF-8 aware environment on linux. You can check that with the `locale` command:
```
$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
```
So my system is fine, but yours had the default, ASCII C locale set. These are simple `bash` variables, so you could `export` them individually or override them all (by setting `LC_ALL`). However, that would only affect the current shell, so you need to make it part of shell initialisation to work everytime automatically.
This is usually done through profile scripts in `/etc` globally, but `.bash_profile` or `.bashrc` would work just as well. In your version of Debian the locale is stored in `/etc/default/locale` and you can get the list of available choices with `locale -a`, eg.:
```
$ locale -a
C
en_US
en_US.iso88591
en_US.utf8
POSIX
sl_SI.utf8
```
Pick one with an utf8 suffix. If you need other locales (for example japanese), they can be generated with localedef/locale-gen (comes with `glibc` or as a separate package). | If you're having problems with entering the symbols in nano, use escape syntax.
You can use `iconv` to convert it to the output encoding corresponding to the current locale:
```
text=$'\xa315.00'
text2=$'\xa9 John Doe'
iconv -f latin1 <<< $text
iconv -f latin1 <<< $text2
```
or the same in utf8:
```
text=$'\xc2\xa315.00'
text2=$'\xc2\xa9 John Doe'
iconv -f utf-8 <<< $text
iconv -f utf-8 <<< $text2
``` |
37,402,110 | HI i want to install the polyglot on python version 3.5. it requires to have numpy installed which i already have and also libicu-dev. My OS is windows X86. I went through cmd, pip and wrote "pip install libicu-dev" but it gives me an error that could not find a version to satisfy the requirements.
how can i install libicu-dev? | 2016/05/23 | [
"https://Stackoverflow.com/questions/37402110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6195038/"
] | For install polyglot, get all dependency libraries (.whl) from <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
* NumPy
* PyICU
* PyCLD2
Install by `pip install <name_of_the_binary>.whl`
Related to issue 11 in poliglot github repository
[source\_issue](https://github.com/aboSamoor/polyglot/issues/11#issuecomment-126675914) | From here:
```
sudo apt-get install python-numpy libicu-dev
```
for more information:
<http://polyglot.readthedocs.io/en/latest/Installation.html> |
37,402,110 | HI i want to install the polyglot on python version 3.5. it requires to have numpy installed which i already have and also libicu-dev. My OS is windows X86. I went through cmd, pip and wrote "pip install libicu-dev" but it gives me an error that could not find a version to satisfy the requirements.
how can i install libicu-dev? | 2016/05/23 | [
"https://Stackoverflow.com/questions/37402110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6195038/"
] | For install polyglot, get all dependency libraries (.whl) from <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
* NumPy
* PyICU
* PyCLD2
Install by `pip install <name_of_the_binary>.whl`
Related to issue 11 in poliglot github repository
[source\_issue](https://github.com/aboSamoor/polyglot/issues/11#issuecomment-126675914) | Firstly try:
```
git clone https://github.com/aboSamoor/polyglot.git
python setup.py install
```
Then pip install:
```
pip install pycld2-0.31-cp36-cp36m-win_amd64.whl
pip install PyICU-1.9.8-cp36-cp36m-win_amd64.whl
``` |
37,402,110 | HI i want to install the polyglot on python version 3.5. it requires to have numpy installed which i already have and also libicu-dev. My OS is windows X86. I went through cmd, pip and wrote "pip install libicu-dev" but it gives me an error that could not find a version to satisfy the requirements.
how can i install libicu-dev? | 2016/05/23 | [
"https://Stackoverflow.com/questions/37402110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6195038/"
] | For install polyglot, get all dependency libraries (.whl) from <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
* NumPy
* PyICU
* PyCLD2
Install by `pip install <name_of_the_binary>.whl`
Related to issue 11 in poliglot github repository
[source\_issue](https://github.com/aboSamoor/polyglot/issues/11#issuecomment-126675914) | This will work by typing it on Anaconda Prompt:
pip install polyglot==14.11 |
15,312,004 | I'm developing a website and intend to support IE8 and above, so I'm not so concerned about older IE versions.
When users open the website in IE, it always jumps either to Compatibility mode or Quirks mode. Can I turn that feature off using this?
```
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
```
W3 Validation is not so much a concern, the only goal we want is to force IE not to open in compatibility mode OR quirks mode, does that meta do the fix for that?
This is the DOCTYPE I am using:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
``` | 2013/03/09 | [
"https://Stackoverflow.com/questions/15312004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870940/"
] | Just have a look at [this SO post](https://stackoverflow.com/questions/14637943/what-is-x-ua-compatible-when-it-references-ie-edge-chrome-1).
Basically it should do what you need, I've used this in the past and it works. It'll open in standards mode in IE.
Just be aware, that if you open the developer tools in IE and select compatability mode, that is what IE will open in (compat mode) and the tag will not have an effect (because you are using developer tools to override the tag behavior). It does work, but you have to test it without the developer tool settings. | You can explicitly tell IE browsers to use its latest available rendering engine using a meta tag. This also prevents IE to open Quirks mode while rending page.
<http://technowide.net/2013/06/21/forcing-ie-browsers-to-behave-properly/> |
31,049 | In an answer to [this question](https://space.stackexchange.com/questions/29633/vector-rs-lp-1-and-2-engines-use-liquid-propylene-as-fuel-with-lox-advantages), the brilliant diagram below was given:
[](https://i.stack.imgur.com/ihsi8.png)
The chart makes chilled ethylene look like a very appealing choice, yet I don't believe it is ever used. Why not?
Edit: I just checked the wonderful ["Ignition" by John D Clark](https://archive.org/details/ignition_201612/page/n3) and while ethylene oxide and many other compounds are mentioned ethylene gets only one mention:
>
> Alcohol, ammonia, and JP-4 or RP-I were the fuels usually burned with LOX, but practically every other inflammable liquid available has been tried experimentally at one time or another. RMI tried, for instance, cyclopropane, ethylene, methyl acetylene, and methyl amine. None of these was any particular improvement on the usual fuels.
>
>
>
(this was around 1950 and their concern was mainly missile boosters, not upper stages). | 2018/10/01 | [
"https://space.stackexchange.com/questions/31049",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/23003/"
] | For one, you get basically the same $I\_{sp}$ to density ratio as RP-1, except with two penalties: lower density, which means bigger tanks and a heavier rocket, and the need to chill the ethylene. Compared to RP-1, you also lose the synergy of being able to use the fuel as a lubricant and hydraulic fluid. | Late answer, but I just stumbled on this. There is a class that is not considered here that is up and to the right of most of the other propellants on the graph. Blends of light hydrocarbons exhibit depressed freezing points, which means things like 50/50 propane/propylene can be chilled down to or even below LOx temperature (90K), which greatly improves both their density and their lubricity. At these temps they give significantly better density impulse that anything on the chart. |
31,049 | In an answer to [this question](https://space.stackexchange.com/questions/29633/vector-rs-lp-1-and-2-engines-use-liquid-propylene-as-fuel-with-lox-advantages), the brilliant diagram below was given:
[](https://i.stack.imgur.com/ihsi8.png)
The chart makes chilled ethylene look like a very appealing choice, yet I don't believe it is ever used. Why not?
Edit: I just checked the wonderful ["Ignition" by John D Clark](https://archive.org/details/ignition_201612/page/n3) and while ethylene oxide and many other compounds are mentioned ethylene gets only one mention:
>
> Alcohol, ammonia, and JP-4 or RP-I were the fuels usually burned with LOX, but practically every other inflammable liquid available has been tried experimentally at one time or another. RMI tried, for instance, cyclopropane, ethylene, methyl acetylene, and methyl amine. None of these was any particular improvement on the usual fuels.
>
>
>
(this was around 1950 and their concern was mainly missile boosters, not upper stages). | 2018/10/01 | [
"https://space.stackexchange.com/questions/31049",
"https://space.stackexchange.com",
"https://space.stackexchange.com/users/23003/"
] | It sure is, by some small portion of the industry. I don't think we'll be seeing any big EthyLox (if you'll excuse the neologism) boosters taking off as first stages, though: it's a complicated thing to deal with, Ethylene. it being a room temperature gas means it entails all the hassle methane or hydrogen brings (i.e. you need to chill it down in order to put it in a tank, build pretty good insulation around your tanks, deal with boiloff, etcetera) and since methane has one fewer carbon I'd expect it to get better ISP. What Ethylene is being considered for, however, is as half of a storable bipropellant system: Ethylene self-pressurizes at normal temperatures, so for pressure-fed engines and RCS it's pretty good, and it's supposed to burn nicely when combined with various oxides of nitrogen, which are also self-pressurizing: The combination doesn't get amazing performance, but if proven to work it would be much easier -and cheaper- to handle than the various nasties currently used for reaction control, stationkeeping, auxiliary power units, orbital maneouvering systems and the like: all in all the mixture seems to have the advantage of being a safe (well, about as safe as rocket fuel gets, anyway), storable, and highly energetic bipropellant: *and* you can use the oxidizer as a monoprop as well. I think it has a decent chance of competing with stuff like hydrazine.
there's a NASA paper on this <https://tfaws.nasa.gov/TFAWS06/Proceedings/Aerothermal-Propulsion/Papers/TFAWS06-1026_Paper_Herdy.pdf>
I suppose the system has the added benefit that you could use a bit of your fuel for ripening bananas? | Late answer, but I just stumbled on this. There is a class that is not considered here that is up and to the right of most of the other propellants on the graph. Blends of light hydrocarbons exhibit depressed freezing points, which means things like 50/50 propane/propylene can be chilled down to or even below LOx temperature (90K), which greatly improves both their density and their lubricity. At these temps they give significantly better density impulse that anything on the chart. |
14,572,331 | I am new to Entity Framework so please bear with me.
I have a program that I want to select multiple records from a table and store it in a queue:
```
private Queue<RecordsToProcess> getRecordsToProcess()
{
Queue<RecordsToProcess> results = new Queue<RecordsToProcess>();
using (MyEntity context = new MyEntity())
{
var query = from v in context.RecordsToProcess
where v.Processed == false
select v;
foreach (RecordsToProcess record in query)
{
results.Enqueue(record);
}
}
}
```
Then I spin up multiple worker threads. Each worker thread takes one of the items in queue, processes it, and then saves it to the database.
```
private void processWorkerThread(object stateInfo)
{
while (workQueue.Count > 0)
{
RecordToProcess record = new RecordToProcess;
lock(workQueue)
{
if (workQueue.Count > 0)
RecordToProcess = workQueue.Dequeue();
else
break;
}
//Do the record processing here
//How do I save that record here???
}
}
```
My understanding is that to save changes back to the database you just call context.SaveChanges() but I can't do that in this situation can I?
Any help is appreciated.
Thanks! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775706/"
] | Since you are disposing your `MyEntity` context in the first method (by wrapping it in a `using` statement), the entities that are enqueued will be in a "detached" state. That means, among other things, that changes done to the entity will not be tracked and you will not be able to lazy load navigation properties.
It is perfectly fine to dequeue these entities, "attaching" them to a different context, update them, and then call `SaveChanges` to persist the changes.
You can read about [Attaching and Detaching Objects](https://msdn.microsoft.com/en-us/library/bb896271(v=vs.110).aspx) and [Add/Attach and Entity States](http://msdn.microsoft.com/en-us/data/jj592676.aspx) | It might be safer if you save off the primary key in the queue instead and retrieve the entities again. This way you are more likely avoid any data concurrency issues. |
53,305,405 | I have a weird issue with CORS. **The API and web APP are running on different servers**.
I enabled CORS on the API using [laravel-cors](https://github.com/barryvdh/laravel-cors) package, and am trying to consume the API from a different server.
I can consume the API using **Postman** as well as **Guzzle** Http Clients, but it fails when using **Ajax**.
[](https://i.stack.imgur.com/PXl9i.png)
When I check the API response; I have the `Access-Control-Allow-Origin: *` header.
[](https://i.stack.imgur.com/aj07p.png)
How can I fix this? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53305405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732184/"
] | In a single awk you can do:
```
awk '{print > ("file" (NR%4))}' inputfile
```
This will send the output to files `file0`, `file1`, `file2` and `file3` | You may use these `awk` commands:
```
awk -v n=1 'NR%4 == n%4' file
20
14
awk -v n=2 'NR%4 == n%4' file
18
30
awk -v n=3 'NR%4 == n%4' file
21
40
awk -v n=4 'NR%4 == n%4' file
16
24
``` |
53,305,405 | I have a weird issue with CORS. **The API and web APP are running on different servers**.
I enabled CORS on the API using [laravel-cors](https://github.com/barryvdh/laravel-cors) package, and am trying to consume the API from a different server.
I can consume the API using **Postman** as well as **Guzzle** Http Clients, but it fails when using **Ajax**.
[](https://i.stack.imgur.com/PXl9i.png)
When I check the API response; I have the `Access-Control-Allow-Origin: *` header.
[](https://i.stack.imgur.com/aj07p.png)
How can I fix this? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53305405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732184/"
] | You may use these `awk` commands:
```
awk -v n=1 'NR%4 == n%4' file
20
14
awk -v n=2 'NR%4 == n%4' file
18
30
awk -v n=3 'NR%4 == n%4' file
21
40
awk -v n=4 'NR%4 == n%4' file
16
24
``` | IMHO `awk` is the best solution. You can use `sed`:
Inputfile generated with `seq 12`:
```
for ((i=1;i<5; i++)); do
sed -n $i~4w$i.out <(seq 12)
done
```
Here `w$i.out` writes to file $i.out. |
53,305,405 | I have a weird issue with CORS. **The API and web APP are running on different servers**.
I enabled CORS on the API using [laravel-cors](https://github.com/barryvdh/laravel-cors) package, and am trying to consume the API from a different server.
I can consume the API using **Postman** as well as **Guzzle** Http Clients, but it fails when using **Ajax**.
[](https://i.stack.imgur.com/PXl9i.png)
When I check the API response; I have the `Access-Control-Allow-Origin: *` header.
[](https://i.stack.imgur.com/aj07p.png)
How can I fix this? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53305405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732184/"
] | You may use these `awk` commands:
```
awk -v n=1 'NR%4 == n%4' file
20
14
awk -v n=2 'NR%4 == n%4' file
18
30
awk -v n=3 'NR%4 == n%4' file
21
40
awk -v n=4 'NR%4 == n%4' file
16
24
``` | This might work for you (GNU sed):
```
sed -ne '1~4w file1' -e '2~4w file2' -e '3~4w file3' -e '4~4w file4' file
``` |
53,305,405 | I have a weird issue with CORS. **The API and web APP are running on different servers**.
I enabled CORS on the API using [laravel-cors](https://github.com/barryvdh/laravel-cors) package, and am trying to consume the API from a different server.
I can consume the API using **Postman** as well as **Guzzle** Http Clients, but it fails when using **Ajax**.
[](https://i.stack.imgur.com/PXl9i.png)
When I check the API response; I have the `Access-Control-Allow-Origin: *` header.
[](https://i.stack.imgur.com/aj07p.png)
How can I fix this? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53305405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732184/"
] | In a single awk you can do:
```
awk '{print > ("file" (NR%4))}' inputfile
```
This will send the output to files `file0`, `file1`, `file2` and `file3` | IMHO `awk` is the best solution. You can use `sed`:
Inputfile generated with `seq 12`:
```
for ((i=1;i<5; i++)); do
sed -n $i~4w$i.out <(seq 12)
done
```
Here `w$i.out` writes to file $i.out. |
53,305,405 | I have a weird issue with CORS. **The API and web APP are running on different servers**.
I enabled CORS on the API using [laravel-cors](https://github.com/barryvdh/laravel-cors) package, and am trying to consume the API from a different server.
I can consume the API using **Postman** as well as **Guzzle** Http Clients, but it fails when using **Ajax**.
[](https://i.stack.imgur.com/PXl9i.png)
When I check the API response; I have the `Access-Control-Allow-Origin: *` header.
[](https://i.stack.imgur.com/aj07p.png)
How can I fix this? | 2018/11/14 | [
"https://Stackoverflow.com/questions/53305405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2732184/"
] | In a single awk you can do:
```
awk '{print > ("file" (NR%4))}' inputfile
```
This will send the output to files `file0`, `file1`, `file2` and `file3` | This might work for you (GNU sed):
```
sed -ne '1~4w file1' -e '2~4w file2' -e '3~4w file3' -e '4~4w file4' file
``` |
24,474,416 | I am trying to create a function that will toggle optional inputs if chosen, here is what I have done so far:
HTML:
```
<div>
<input>
<a class="input-toggle" href="#"><span>Toggle Option</span><span>Close</span></a>
<div class="input-toggle-content">
<input name="">
</div>
</div>
```
JavaScript:
```
$('.input-toggle').each(function() {
$(this).next("div").hide().end();
$("span:last-of-type").hide();
$(this).on('click', function() {
$(this).next("div").slideToggle();
$("span:first-of-type").hide();
$("span:last-of-type").show();
});
});
```
So, the way it should work is when clicked on .input-toggle the div that is just next to it will be toggled and if clicked again the div will go away... I got this bit working, however, I want to also toggle `<span>Toggle Option</span>` with `<span>Close</span>` and I can't get it working... I don't know if the way I structured my function is correct? | 2014/06/29 | [
"https://Stackoverflow.com/questions/24474416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3388091/"
] | Try,
```
$('.input-toggle + div.input-toggle-content').hide();
$(".input-toggle span:last-of-type").hide();
$('.input-toggle').click(function () {
$(this).next('div.input-toggle-content').toggle();
var spans = $('span', this);
spans.not(spans.filter(':visible').hide()).show();
});
```
[DEMO](http://jsfiddle.net/DbnW3/)
---------------------------------- | here you go: <http://jsfiddle.net/jPe3A/>
```
$('.input-toggle').each(function() {
$(this).next("div").hide().end();
$("span:last-of-type").hide();
$(this).on('click', function() {
$(this).next("div").slideToggle();
if($("span:first").is(':hidden')){
$("span:first").show();
$("span:last").hide();
}
else{
$("span:first").hide();
$("span:last").show();
}
});
});
``` |
71,574,752 | I need to use a reporting tool with genexus for web development. Genexus proposes to use the generation of reports through Procedure-type objects, but these do not have the possibility of generating them through queries similar to what can be done with Crystal Report.
As far as I know it has no possibility to integrate with Crystal Report.
Do you know any reporting tool that can be easily integrated with Genexus? | 2022/03/22 | [
"https://Stackoverflow.com/questions/71574752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18441548/"
] | In GeneXus, you have the possibility to create queries to extract information from your database and then present with different types of charts, pivot table, tables, maps, and cards.
Also, you have a dashboard object to integrate many queries in a same dashboard. [Here](https://wiki.genexus.com/commwiki/servlet/wiki?33991,Query%20Object%20Usage%20Example) you can learn how to build this and [here](https://reporting.samples.genexus.com/dashboardcases.aspx) you can see a showcase running with different examples
This Knowledge Base is open source, so [here](https://wiki.genexus.com/commwiki/servlet/wiki?49086,KB%3AReporting+Showcase) you can see how to get it. | speaking of Crystal Report I think you are using .net as a generator. If you had used Java you could have adopted Jasper Report. For .net, on the other hand, at the moment I don't think there is anything "standard". We use different approaches based on the type of report. For some reports we continue to make them with the procedure, others with the query object but for documents, such as contracts that need to be managed dynamically with the possibility of inserting or removing sections but which must also dynamically manage the page change, we have integrated an external DLL (integrated as an external object) and we generate the report in html. |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | The strategy here is to split the data frame by columns into variable groups, and for each row identifying if there are non-NA values. We then check with `rowsums` to make sure there are at least two variables with non-NA values for a row, and if so, add the mean of those values with `cbind`.
This will generalize to any number of columns so long as they are named in the AA\_varXXX format, and so long as the only column not in that format is `myid`. Easy enough to fix if this isn't strictly the case, but these are the limitations on the code as written now.
```
df.dat <- df[!names(df) == "myid"]
diverse.rows <- rowSums(
sapply(
split.default(df.dat, gsub("^([A-Z]{2})_var.*", "\\1", names(df.dat))),
function(x) apply(x, 1, function(y) any(!is.na(y)))
) ) > 1
cbind(df, div.mean=ifelse(diverse.rows, rowMeans(df.dat, na.rm=T), NA))
```
Produces:
```
AA_var1 AA_var2 myid BB_var3 BB_var4 div.mean
1 NA NA 123456 10 12 NA
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NA
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NA
6 12 13 132203 14 NA 13
``` | This solution seems a little convoluted to me, so there's probably a better way, but it should work for you.
```
# Here's your data:
df <- data.frame(AA_var1 = c(NA,NA,12,12,NA,12),
AA_var2 = c(NA,10,10,NA,NA,13),
BB_var3 = c(10,12,NA,NA,NA,14),
BB_var4 = c(12,NA,NA,12,NA,NA))
# calculate rowMeans for each subset of variables
a <- rowMeans(df[,grepl('AA',names(df))], na.rm=TRUE)
b <- rowMeans(df[,grepl('BB',names(df))], na.rm=TRUE)
# count non-missing values for each subset of variables
a2 <- rowSums(!is.na(df[,grepl('AA',names(df))]), na.rm=TRUE)
b2 <- rowSums(!is.na(df[,grepl('BB',names(df))]), na.rm=TRUE)
# calculate means:
rowSums(cbind(a*a2,b*b2)) /
rowSums(!is.na(df[,grepl('[AA]|[BB]',names(df))]), na.rm=TRUE)
```
Result:
```
> df$rowMeanIfDiverseData <- rowSums(cbind(a*a2,b*b2)) /
+ rowSums(!is.na(df[,grepl('[AA]|[BB]',names(df))]), na.rm=TRUE)
> df
AA_var1 AA_var2 BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 10 12 NaN
2 NA 10 12 NA 11
3 12 10 NA NA NaN
4 12 NA NA 12 12
5 NA NA NA NA NaN
6 12 13 14 NA 13
```
And a little cleanup to exactly match your intended output:
```
> df$rowMeanIfDiverseData[is.nan(df$rowMeanIfDiverseData)] <- NA
> df
AA_var1 AA_var2 BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 10 12 NA
2 NA 10 12 NA 11
3 12 10 NA NA NA
4 12 NA NA 12 12
5 NA NA NA NA NA
6 12 13 14 NA 13
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | This solution seems a little convoluted to me, so there's probably a better way, but it should work for you.
```
# Here's your data:
df <- data.frame(AA_var1 = c(NA,NA,12,12,NA,12),
AA_var2 = c(NA,10,10,NA,NA,13),
BB_var3 = c(10,12,NA,NA,NA,14),
BB_var4 = c(12,NA,NA,12,NA,NA))
# calculate rowMeans for each subset of variables
a <- rowMeans(df[,grepl('AA',names(df))], na.rm=TRUE)
b <- rowMeans(df[,grepl('BB',names(df))], na.rm=TRUE)
# count non-missing values for each subset of variables
a2 <- rowSums(!is.na(df[,grepl('AA',names(df))]), na.rm=TRUE)
b2 <- rowSums(!is.na(df[,grepl('BB',names(df))]), na.rm=TRUE)
# calculate means:
rowSums(cbind(a*a2,b*b2)) /
rowSums(!is.na(df[,grepl('[AA]|[BB]',names(df))]), na.rm=TRUE)
```
Result:
```
> df$rowMeanIfDiverseData <- rowSums(cbind(a*a2,b*b2)) /
+ rowSums(!is.na(df[,grepl('[AA]|[BB]',names(df))]), na.rm=TRUE)
> df
AA_var1 AA_var2 BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 10 12 NaN
2 NA 10 12 NA 11
3 12 10 NA NA NaN
4 12 NA NA 12 12
5 NA NA NA NA NaN
6 12 13 14 NA 13
```
And a little cleanup to exactly match your intended output:
```
> df$rowMeanIfDiverseData[is.nan(df$rowMeanIfDiverseData)] <- NA
> df
AA_var1 AA_var2 BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 10 12 NA
2 NA 10 12 NA 11
3 12 10 NA NA NA
4 12 NA NA 12 12
5 NA NA NA NA NA
6 12 13 14 NA 13
``` | ```
fun <- function(x) {
MEAN <- mean(c(x[1], x[2], x[4], x[5]), na.rm=TRUE)
CHECK <- sum(!is.na(c(x[1], x[2]))) > 0 & sum(!is.na(c(x[4], x[5])) > 0)
MEAN * ifelse(CHECK, 1, NaN)
}
df$rowMeanIfDiverseData <- apply(df, 1, fun)
df
AA_var1 AA_var2 myid BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 123456 10 12 NaN
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NaN
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NaN
6 12 13 132203 14 NA 13
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | The strategy here is to split the data frame by columns into variable groups, and for each row identifying if there are non-NA values. We then check with `rowsums` to make sure there are at least two variables with non-NA values for a row, and if so, add the mean of those values with `cbind`.
This will generalize to any number of columns so long as they are named in the AA\_varXXX format, and so long as the only column not in that format is `myid`. Easy enough to fix if this isn't strictly the case, but these are the limitations on the code as written now.
```
df.dat <- df[!names(df) == "myid"]
diverse.rows <- rowSums(
sapply(
split.default(df.dat, gsub("^([A-Z]{2})_var.*", "\\1", names(df.dat))),
function(x) apply(x, 1, function(y) any(!is.na(y)))
) ) > 1
cbind(df, div.mean=ifelse(diverse.rows, rowMeans(df.dat, na.rm=T), NA))
```
Produces:
```
AA_var1 AA_var2 myid BB_var3 BB_var4 div.mean
1 NA NA 123456 10 12 NA
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NA
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NA
6 12 13 132203 14 NA 13
``` | My attempt, somewhat longwinded.....
```
dat<-data.frame(AA_var1=c(NA,NA,12,12,NA,12),
AA_var2=c(NA,10,10,NA,NA,13),
myid=1:6,
BB_var3=c(10,12,NA,NA,NA,14),
BB_var4=c(12,NA,NA,12,NA,NA))
#what columns are associated with variables used in our mean
varcols<-grep("*var[1-9]",names(dat),value=T)
#which rows have the requisite diversification of non-nulls
#i assume these columns will start with capitals and folloowed by underscore
meanrow<-apply(!is.na(dat[,varcols]),1,function(x){n<-varcols[x]
1<length(unique(regmatches(n,regexpr("[A-Z]+_",n))))
})
#do the row mean for all
dat$meanval<-rowMeans(dat[,varcols],na.rm=T)
#null out for those without diversification (i.e. !meanrow)
dat[!meanrow,"meanval"]<-NA
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | The strategy here is to split the data frame by columns into variable groups, and for each row identifying if there are non-NA values. We then check with `rowsums` to make sure there are at least two variables with non-NA values for a row, and if so, add the mean of those values with `cbind`.
This will generalize to any number of columns so long as they are named in the AA\_varXXX format, and so long as the only column not in that format is `myid`. Easy enough to fix if this isn't strictly the case, but these are the limitations on the code as written now.
```
df.dat <- df[!names(df) == "myid"]
diverse.rows <- rowSums(
sapply(
split.default(df.dat, gsub("^([A-Z]{2})_var.*", "\\1", names(df.dat))),
function(x) apply(x, 1, function(y) any(!is.na(y)))
) ) > 1
cbind(df, div.mean=ifelse(diverse.rows, rowMeans(df.dat, na.rm=T), NA))
```
Produces:
```
AA_var1 AA_var2 myid BB_var3 BB_var4 div.mean
1 NA NA 123456 10 12 NA
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NA
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NA
6 12 13 132203 14 NA 13
``` | ```
fun <- function(x) {
MEAN <- mean(c(x[1], x[2], x[4], x[5]), na.rm=TRUE)
CHECK <- sum(!is.na(c(x[1], x[2]))) > 0 & sum(!is.na(c(x[4], x[5])) > 0)
MEAN * ifelse(CHECK, 1, NaN)
}
df$rowMeanIfDiverseData <- apply(df, 1, fun)
df
AA_var1 AA_var2 myid BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 123456 10 12 NaN
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NaN
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NaN
6 12 13 132203 14 NA 13
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | The strategy here is to split the data frame by columns into variable groups, and for each row identifying if there are non-NA values. We then check with `rowsums` to make sure there are at least two variables with non-NA values for a row, and if so, add the mean of those values with `cbind`.
This will generalize to any number of columns so long as they are named in the AA\_varXXX format, and so long as the only column not in that format is `myid`. Easy enough to fix if this isn't strictly the case, but these are the limitations on the code as written now.
```
df.dat <- df[!names(df) == "myid"]
diverse.rows <- rowSums(
sapply(
split.default(df.dat, gsub("^([A-Z]{2})_var.*", "\\1", names(df.dat))),
function(x) apply(x, 1, function(y) any(!is.na(y)))
) ) > 1
cbind(df, div.mean=ifelse(diverse.rows, rowMeans(df.dat, na.rm=T), NA))
```
Produces:
```
AA_var1 AA_var2 myid BB_var3 BB_var4 div.mean
1 NA NA 123456 10 12 NA
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NA
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NA
6 12 13 132203 14 NA 13
``` | I think some of the answers are making this seem more complicated than it is. This will do it:
```
df$means = ifelse(rowSums(!is.na(df[, grep('AA_var', names(df))])) &
rowSums(!is.na(df[, grep('BB_var', names(df))])),
rowMeans(df[, grep('_var', names(df))], na.rm = T), NA)
# AA_var1 AA_var2 myid BB_var3 BB_var4 means
#1 NA NA 123456 10 12 NA
#2 NA 10 194200 12 NA 11
#3 12 10 132200 NA NA NA
#4 12 NA 132201 NA 12 12
#5 NA NA 132202 NA NA NA
#6 12 13 132203 14 NA 13
```
Here's a generalization of the above, given the comment, assuming unique id's (if they're not, create a unique index instead):
```
library(data.table)
library(reshape2)
dt = data.table(df)
setkey(dt, myid) # not strictly necessary, but makes life easier
# find the conditional
cond = melt(dt, id.var = 'myid')[,
sum(!is.na(value)), by = list(myid, sub('_var.*', '', variable))][,
all(V1 != 0), keyby = myid]$V1
# fill in the means (could also do a join, but will rely on ordering instead)
dt[cond, means := rowMeans(.SD, na.rm = T), .SDcols = grep('_var', names(dt))]
dt
# AA_var1 AA_var2 myid BB_var3 BB_var4 means
#1: NA NA 123456 10 12 NA
#2: 12 10 132200 NA NA NA
#3: 12 NA 132201 NA 12 12
#4: NA NA 132202 NA NA NA
#5: 12 13 132203 14 NA 13
#6: NA 10 194200 12 NA 11
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | My attempt, somewhat longwinded.....
```
dat<-data.frame(AA_var1=c(NA,NA,12,12,NA,12),
AA_var2=c(NA,10,10,NA,NA,13),
myid=1:6,
BB_var3=c(10,12,NA,NA,NA,14),
BB_var4=c(12,NA,NA,12,NA,NA))
#what columns are associated with variables used in our mean
varcols<-grep("*var[1-9]",names(dat),value=T)
#which rows have the requisite diversification of non-nulls
#i assume these columns will start with capitals and folloowed by underscore
meanrow<-apply(!is.na(dat[,varcols]),1,function(x){n<-varcols[x]
1<length(unique(regmatches(n,regexpr("[A-Z]+_",n))))
})
#do the row mean for all
dat$meanval<-rowMeans(dat[,varcols],na.rm=T)
#null out for those without diversification (i.e. !meanrow)
dat[!meanrow,"meanval"]<-NA
``` | ```
fun <- function(x) {
MEAN <- mean(c(x[1], x[2], x[4], x[5]), na.rm=TRUE)
CHECK <- sum(!is.na(c(x[1], x[2]))) > 0 & sum(!is.na(c(x[4], x[5])) > 0)
MEAN * ifelse(CHECK, 1, NaN)
}
df$rowMeanIfDiverseData <- apply(df, 1, fun)
df
AA_var1 AA_var2 myid BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 123456 10 12 NaN
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NaN
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NaN
6 12 13 132203 14 NA 13
``` |
22,180,935 | I'm working on a data set where the source name is specified by a 2-letter abbreviation in front of the variable. So all variables from source AA start with `AA_var1`, and source bb has `bb_variable_name_2`. There are actually a lot of sources, and a lot of variable names, but I leave only 2 as a minimal example.
I want to create a mean variable for any row where the number of sources, that is, where the number of unique prefixes for which the data on that row is not NA, is greater than 1. If there's only one source, I want that total variable to be NA.
So, for example, my data looks like this:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1
1 NA NA 123456 10 12
2 NA 10 194200 12 NA
3 12 10 132200 NA NA
4 12 NA 132201 NA 12
5 NA NA 132202 NA NA
6 12 13 132203 14 NA
```
And I want the following:
```
> head(df)
AA_var1 AA_var2 myid bb_meow bb_A_v1 rowMeanIfDiverseData
1 NA NA 123456 10 12 NA #has only bb
2 NA 10 194200 12 NA 11 #has AA and bb
3 12 10 132200 NA NA NA #has only AA
4 12 NA 132201 NA 12 12 #has AA and bb
5 NA NA 132202 NA NA NA #has neither
6 12 13 132203 14 NA 13 #has AA and bb
```
Normally, I just use `rowMeans()` for this kind of thing. But the additional subsetting of selecting only rows whose variable names follow a convention /at the row level/ has caught me confused between the item-level and the general apply-level statements I'm used to.
I can get the prefixes at the dataframe level:
```
mynames <- names(df[!names(df) %in% c("myid")])
tmp <- str_extract(mynames, perl("[A-Za-z]{2}(?=_)"))
uniq <- unique(tmp[!is.na(tmp)])
```
So,
```
> uniq
[1] "AA" "bb"
```
So, I can make this a function I can apply to df like so:
```
multiSource <- function(x){
nm = names(x[!names(x) %in% badnames]) # exclude c("myid")
tmp <- str_extract(nm, perl("[A-Za-z]{2}(?=_)")) # get prefixes
uniq <- unique(tmp[!is.na(tmp)]) # ensure unique and not NA
if (length(uniq) > 1){
return(T)
} else {
return(F)
}
}
```
But this is clearly confused, and still getting data-set level, ie:
```
> lapply(df,multiSource)
$AA_var1
[1] FALSE
$AA_var2
[1] FALSE
$bb_meow
[1] FALSE
$bb_A_v1
[1] FALSE
```
And...
```
> apply(df,MARGIN=1,FUN=multiSource)
```
Gives TRUE for all.
I'd otherwise like to be saying...
```
df$rowMean <- rowMeans(df, na.rm=T)
# so, in this case
rowMeansIfTest <- function(X,test) {
# is this row muliSource True?
# if yes, return(rowMeans(X))
# else return(NA)
}
df$rowMeanIfDiverseData <- rowMeansIfTest(df, test=multiSource)
```
But it is unclear to me how to do this without some kind of for loop. | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1052117/"
] | I think some of the answers are making this seem more complicated than it is. This will do it:
```
df$means = ifelse(rowSums(!is.na(df[, grep('AA_var', names(df))])) &
rowSums(!is.na(df[, grep('BB_var', names(df))])),
rowMeans(df[, grep('_var', names(df))], na.rm = T), NA)
# AA_var1 AA_var2 myid BB_var3 BB_var4 means
#1 NA NA 123456 10 12 NA
#2 NA 10 194200 12 NA 11
#3 12 10 132200 NA NA NA
#4 12 NA 132201 NA 12 12
#5 NA NA 132202 NA NA NA
#6 12 13 132203 14 NA 13
```
Here's a generalization of the above, given the comment, assuming unique id's (if they're not, create a unique index instead):
```
library(data.table)
library(reshape2)
dt = data.table(df)
setkey(dt, myid) # not strictly necessary, but makes life easier
# find the conditional
cond = melt(dt, id.var = 'myid')[,
sum(!is.na(value)), by = list(myid, sub('_var.*', '', variable))][,
all(V1 != 0), keyby = myid]$V1
# fill in the means (could also do a join, but will rely on ordering instead)
dt[cond, means := rowMeans(.SD, na.rm = T), .SDcols = grep('_var', names(dt))]
dt
# AA_var1 AA_var2 myid BB_var3 BB_var4 means
#1: NA NA 123456 10 12 NA
#2: 12 10 132200 NA NA NA
#3: 12 NA 132201 NA 12 12
#4: NA NA 132202 NA NA NA
#5: 12 13 132203 14 NA 13
#6: NA 10 194200 12 NA 11
``` | ```
fun <- function(x) {
MEAN <- mean(c(x[1], x[2], x[4], x[5]), na.rm=TRUE)
CHECK <- sum(!is.na(c(x[1], x[2]))) > 0 & sum(!is.na(c(x[4], x[5])) > 0)
MEAN * ifelse(CHECK, 1, NaN)
}
df$rowMeanIfDiverseData <- apply(df, 1, fun)
df
AA_var1 AA_var2 myid BB_var3 BB_var4 rowMeanIfDiverseData
1 NA NA 123456 10 12 NaN
2 NA 10 194200 12 NA 11
3 12 10 132200 NA NA NaN
4 12 NA 132201 NA 12 12
5 NA NA 132202 NA NA NaN
6 12 13 132203 14 NA 13
``` |
283,371 | In letters written in the early 20th century, for the German word “bei”, the
author commonly uses the abbreviation “ᵇ/”. Currently I typeset as follows:
```
26.4.17 \textsuperscript{b}/La Selve
```
The result, however, is an unpleasant space between the superscript “b” and the
slash. Of course I could manually adjust space, but I wonder:
*Is there a recommended way of typesetting abbreviations like that? Any
dedicated package?* | 2015/12/16 | [
"https://tex.stackexchange.com/questions/283371",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/37500/"
] | Never seen such an abbreviation, but it's easy to obtain it:
```
\documentclass{article}
\newcommand{\bei}{\textsuperscript{b}\kern-.3em}
\begin{document}
Abcdef \bei/La Selve
\end{document}
```
You could also add the `/` in the definition of `\bei`, if you prefer, but it has the disadvantage that a space after `\bei` would need `{}`.
Alternatively, in order to be sure you do have a slash after `\bei` is
```
\newcommand{\bei}{}% just for safety
\def\bei/{\textsuperscript{b}\kern-.3em/}
```
and the usage is as before.
[](https://i.stack.imgur.com/kDbjh.png) | I'm not familiar with this specific abbreviation. For what I understand from your question, I'd suggest the microtype package (needs LuaLaTex).
```
\documentclass{article}
\usepackage{microtype}
\usepackage{xspace}
\newcommand*{\mybei}{\textls[-190]{\emph{\textsuperscript{b}}/}\xspace}
\newcommand*{\mybeis}{\textls[-300]{\textsuperscript{b}/}\xspace}
\newcommand*{\mybeit}{\textls[-190]{\textsuperscript{b}/}\xspace}
\begin{document}
There is a \mybei here. Can I use the abbreviation \mybeit to say \mybeis uns in Deutschland?
\end{document}
```
The kerning between "b" and "/" can be adapted by \textls. |
25,932,257 | I would like to show a different **div** depending on what class my 3 **span** elems contain.
If all **span** hasClass *up* or *up1* the code would show a **div** with class *allUp* . If it hasClass *up* *up1* and *down* then it would show a **div** with class *twoUp*.
I wrote the following, but of course it doesn't work.
```
var $line1 = $(".line1")
var $line2 = $(".line2")
var $line3 = $(".line3")
if($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("up") || $line3.hasClass("up1")) {
$(".allUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".twoUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("down") || $line2.hasClass("down1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".oneUp").show();
}
else {
$(".down").show();
}
```
***think I've fixed the syntax errors*** | 2014/09/19 | [
"https://Stackoverflow.com/questions/25932257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246460/"
] | Using Mockito, you can do that by using `@Mock` and `@InjectMocks` and the `MockitoJUnitRunner`.
This question describes this: [Using @Mock and @InjectMocks](https://stackoverflow.com/questions/9076302/using-mock-and-injectmocks) | I think your tests are telling you that database records are hard to implement as unmodifiable objects.
How about adding
```
Person updateName(String name);
```
to Person class? |
25,932,257 | I would like to show a different **div** depending on what class my 3 **span** elems contain.
If all **span** hasClass *up* or *up1* the code would show a **div** with class *allUp* . If it hasClass *up* *up1* and *down* then it would show a **div** with class *twoUp*.
I wrote the following, but of course it doesn't work.
```
var $line1 = $(".line1")
var $line2 = $(".line2")
var $line3 = $(".line3")
if($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("up") || $line3.hasClass("up1")) {
$(".allUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".twoUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("down") || $line2.hasClass("down1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".oneUp").show();
}
else {
$(".down").show();
}
```
***think I've fixed the syntax errors*** | 2014/09/19 | [
"https://Stackoverflow.com/questions/25932257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246460/"
] | Through my substantial searches on Mockito I found there are two types of mocking:
1. Proxy Mocking (Usual stubbing)
2. Class remapping(Only Jmockit supports)
You can read about "How Mock Objects Work" [here](http://java.dzone.com/articles/the-concept-mocking).
For my question, Class Remapping was the solution
Another solution is through the use of `InjectMocks` and `ReflectionTestUtils`
```
/* We can place this code in the JUnit test Class */
@Mock
PersonDAO personDAO;
@InjectMocks
PersonService personService;
@Before
public void setUP() {
MockitoAnnotations.init(this);
}
@Test
public void shouldUpdatePersonName(){
ReflectionTestutils.setField(personService,"personDao",personDAO);
............Remaining Code..........
}
```
What `ReflectionTestUtils` does is it will replace the `personDao`(created using "new" operator) present in the `personService` object with the locally created(using `@Mock`) mock `personDAO`.
```
ReflectionTestutils.setField(target,"name",actual);
```
There is a wealth of information beyond what I can give here about `ReflectionTestUtils` on the net. | Using Mockito, you can do that by using `@Mock` and `@InjectMocks` and the `MockitoJUnitRunner`.
This question describes this: [Using @Mock and @InjectMocks](https://stackoverflow.com/questions/9076302/using-mock-and-injectmocks) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.