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 |
|---|---|---|---|---|---|
48,476,431 | I have these fields:
```
field1
field2
field3
field4
this.form = this.formbuilder.group({
'field1' = ['', [<control-specific-validations>]],
'field2' = ['', [<control-specific-validations>]]
}, { validator: isField1GreaterThanField2Validator}
});
```
More validations I need:
```
- field3.value must be greater than field4.value
- field3.value must be greater than field2.value + 1
- field4.value must be less than field1.value
```
How do you integrate these new validation requirements into the constructed form?
What I do **NOT** want to do is to setup a
```
formControl.valueChanges.subscribe(value => { });
```
for each field and then have many if/else there.
Then I could remove the whole reactive forms module, use 2way-databinding and render a error string in the ui when the validation expression is true. | 2018/01/27 | [
"https://Stackoverflow.com/questions/48476431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401643/"
] | You can use a custom validator to do this. <https://angular.io/guide/form-validation#custom-validators>
Here is a working example of what you want: <https://stackblitz.com/edit/isgreaterthanotherfield-custom-validator>
The validator function itself looks like this:
```
greaterThan(field: string): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const group = control.parent;
const fieldToCompare = group.get(field);
const isLessThan = Number(fieldToCompare.value) > Number(control.value);
return isLessThan ? {'lessThan': {value: control.value}} : null;
}
}
```
I am using the `parent` property on the control to access the other field.
Note that you cannot set that validator in the form initialization, since the field you are basing it on is not yet defined.
```
this.myForm = this.fb.group({
field1: 0,
field2: 0
});
this.myForm.get('field2').setValidators(this.greaterThan('field1'));
```
---
Update: I took it a step further and implemented a custom validator which accepts a predicate function so you can use the same validator for all your comparisons.
See it in action here: <https://stackblitz.com/edit/comparison-custom-validator>
It uses the same approach as above, but is a bit more flexible since you can pass in any comparison. There are some edge cases the example doesn't consider, like passing a form field name that doesn't exist, if the form field you pass does not actually use numbers / the types don't match up, etc, but I believe that is outside the scope of the question.
This was an interesting question and I enjoyed working on it.
For quick reference, here is what the entire component looks like with the flexible custom validator:
```
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
myForm: FormGroup;
field2HasError: boolean;
field3HasError: boolean;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
field1: 0,
field2: 0,
field3: 0,
field4: 0
});
const field1MustBeGreaterThanField2 =
this.comparison('field1', (field2Val, field1Val) => {
return Number(field2Val) < Number(field1Val);
});
const field3MustBeGreaterThanField2Plus1 =
this.comparison('field2', (field3Val, field2Val) => {
return Number(field3Val) > (Number(field2Val) + 1);
});
this.myForm.get('field2').setValidators(field1MustBeGreaterThanField2);
this.myForm.get('field3').setValidators(field3MustBeGreaterThanField2Plus1);
this.myForm.get('field2').valueChanges.subscribe(() => {
this.field2HasError = this.myForm.get('field2').hasError('comparison');
});
this.myForm.get('field3').valueChanges.subscribe(() => {
this.field3HasError = this.myForm.get('field3').hasError('comparison');
});
}
comparison(field: string, predicate: (fieldVal, fieldToCompareVal) => boolean): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const group = control.parent;
const fieldToCompare = group.get(field);
console.log('fieldToCompare.value', fieldToCompare.value);
console.log('field.value', control.value);
const valid = predicate(control.value, fieldToCompare.value);
return valid ? null : {'comparison': {value: control.value}};
}
}
}
``` | //your .ts
```
ngOnInit() {
this.myForm = this.fb.group({
field1: 0,
field2: 0,
field3: 0,
}, { validator: this.customValidator }); //a unique validator
}
customValidator(formGroup: FormGroup) {
let errors:any={};
let i:number=0;
let valueBefore:any=null;
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (valueBefore)
{
if (parseInt(control.value)<valueBefore)
{
let newError:any={['errorLess'+i]:true} //create an object like,e.g. {errorLess1:true}
errors={...errors,...newError}; //Concat errors
}
}
valueBefore=parseInt(control.value);
i++;
});
if (errors)
return errors;
}
}
```
The .html like
```
<form [formGroup]="myForm">
field1:
<input formControlName="field1">
<br> field2:
<input formControlName="field2">
<div *ngIf="myForm.hasError('errorLess1')">Field 2 less that field 1</div>
<br> field3:
<input formControlName="field3">
<div *ngIf="myForm.hasError('errorLess2')">Field 3 less that field 2</div>
</form>
``` |
1,936,460 | Suppose $f(x)$ is differentiable on $U=(-\infty, 0]$ and $g(x)$ is not differentiable at $V=[0,\infty)$ but is differentiable on $(0,\infty)$. Is the following piecewise function $h(x)$ differentiable?
$$
h(x)=
\begin{cases}
f(x) \text{ for } x\in U\\
g(x) \text{ for } x\in V\\
\end{cases}
$$ Note $U\cap V=\{0\}$ and $f$ is differentiable at $0$ but $g$ is not. Disclaimer, I'm not sure why you would want to consider a piecewise function with "overlapping pieces" but I was asked to. | 2016/09/22 | [
"https://math.stackexchange.com/questions/1936460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/199120/"
] | $\frac{dy}{dx}$ gives you the slope of the tangent line at any point. Substituting in a value for $x$ into $\frac{dy}{dx}$ gives you the slope at that particular value. Now you have the slope of the line, how do you get the equation of the line? | From high school algebra, you know that to get the equation of a line you need two things: A point on the line and the slope. You're given the $x$-coordinate of a point on the line (and the curve.) So find the $y$-coordinate. Now you need the slope at that point. |
1,936,460 | Suppose $f(x)$ is differentiable on $U=(-\infty, 0]$ and $g(x)$ is not differentiable at $V=[0,\infty)$ but is differentiable on $(0,\infty)$. Is the following piecewise function $h(x)$ differentiable?
$$
h(x)=
\begin{cases}
f(x) \text{ for } x\in U\\
g(x) \text{ for } x\in V\\
\end{cases}
$$ Note $U\cap V=\{0\}$ and $f$ is differentiable at $0$ but $g$ is not. Disclaimer, I'm not sure why you would want to consider a piecewise function with "overlapping pieces" but I was asked to. | 2016/09/22 | [
"https://math.stackexchange.com/questions/1936460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/199120/"
] | $\frac{dy}{dx}$ gives you the slope of the tangent line at any point. Substituting in a value for $x$ into $\frac{dy}{dx}$ gives you the slope at that particular value. Now you have the slope of the line, how do you get the equation of the line? | Here's how to solve such a problem:
1. Differentiate your function $f(x)$ (as you have done) and insert the value of $x=x\_t$ which represents the point you want to find the tangent line at, i.e., $f'(x\_t)$.
2. You want to find an equation of the form $g(x)=ax+b$, where you already know $a$. To find $b$, simply insert the point you know $g(x)$ must satisfy, i.e., $g(x\_t)=f(x\_t)$. |
1,936,460 | Suppose $f(x)$ is differentiable on $U=(-\infty, 0]$ and $g(x)$ is not differentiable at $V=[0,\infty)$ but is differentiable on $(0,\infty)$. Is the following piecewise function $h(x)$ differentiable?
$$
h(x)=
\begin{cases}
f(x) \text{ for } x\in U\\
g(x) \text{ for } x\in V\\
\end{cases}
$$ Note $U\cap V=\{0\}$ and $f$ is differentiable at $0$ but $g$ is not. Disclaimer, I'm not sure why you would want to consider a piecewise function with "overlapping pieces" but I was asked to. | 2016/09/22 | [
"https://math.stackexchange.com/questions/1936460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/199120/"
] | $\frac{dy}{dx}$ gives you the slope of the tangent line at any point. Substituting in a value for $x$ into $\frac{dy}{dx}$ gives you the slope at that particular value. Now you have the slope of the line, how do you get the equation of the line? | The slope of the tangent line is
$$
y'(4/\pi)=2(4/\pi)\sec(\pi/4)-\sec(\pi/4)\tan(\pi/4)=\frac{16}{\sqrt{2}\pi}-\frac{2}{\sqrt{2}}
$$
And the line must go through the point $(\frac{4}{\pi},\frac{16}{\pi^2}\*\frac{2}{\sqrt{2}})$
Can you finish from here? |
49,766,993 | I'm trying to separate the declaration of components. I've created a new file called "Components.ts" and I wrote the declaration codes there and I'm exporting It.
```
import { NgModule } from '@angular/core';
import { Component1} from '../components/Component1.component';
import { Component2} from '../components/Component2.component';
import { Component3} from
'../components/Component3.component';
@NgModule({
declarations: [
Component1,
Component2,
Component3
]
})
export class Components { }
```
And I'm defining into my "App.module.ts" file
```
import { NgModule } from '@angular/core';
import { Components } from './Misc/Components';//Custom Module
@NgModule({
declarations: [AppComponent], //This is my main component
imports: [
Components // This is the custom module containg declarations of
// other components
],
```
Here is the error:
[](https://i.stack.imgur.com/vAUDe.png)
**UPDATE**
I've already Imported ReactiveForm Module.
My project is running fine if i define all the components in the "App.module.ts" file like this:
```
declarations: [
AppComponent,
Component1,
Component2,
Component3
];
```
Problem occurs when i'm trying to seperate the declarations of all other components. | 2018/04/11 | [
"https://Stackoverflow.com/questions/49766993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5478249/"
] | You are having this issue because you didn't add `float:left` property to the video thumnail div. Try this code.
```
.vp-video-img-w {
position: relative;
overflow: hidden;
float: left;
margin-right: 10px;
width: 30%;
}
``` | Change
```
.vp-video-img-w {
position: relative;
width: 100%;
overflow: hidden;
}
```
to
```
.vp-video-img-w {
position: relative;
width: 100%;
overflow: hidden;
float: left;
}
``` |
49,766,993 | I'm trying to separate the declaration of components. I've created a new file called "Components.ts" and I wrote the declaration codes there and I'm exporting It.
```
import { NgModule } from '@angular/core';
import { Component1} from '../components/Component1.component';
import { Component2} from '../components/Component2.component';
import { Component3} from
'../components/Component3.component';
@NgModule({
declarations: [
Component1,
Component2,
Component3
]
})
export class Components { }
```
And I'm defining into my "App.module.ts" file
```
import { NgModule } from '@angular/core';
import { Components } from './Misc/Components';//Custom Module
@NgModule({
declarations: [AppComponent], //This is my main component
imports: [
Components // This is the custom module containg declarations of
// other components
],
```
Here is the error:
[](https://i.stack.imgur.com/vAUDe.png)
**UPDATE**
I've already Imported ReactiveForm Module.
My project is running fine if i define all the components in the "App.module.ts" file like this:
```
declarations: [
AppComponent,
Component1,
Component2,
Component3
];
```
Problem occurs when i'm trying to seperate the declarations of all other components. | 2018/04/11 | [
"https://Stackoverflow.com/questions/49766993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5478249/"
] | Try below code:
```css
.header {
padding-top: 20px;
padding-bottom: 20px;
}
.video-embed-container {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
margin-bottom: 0px;
}
.active-iframe-wrapper {
float: left;
width: 100%;
background-color: #f5f5f5;
}
.video-embed-container iframe, .embed-container object, .embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.video-item-w{
background-color:#ccc;
}
.vp-hqdefault-w {
max-height: 80px;
max-width: 120px;
overflow: hidden;
position: relative;
width:30%;
}
.vp-video-img-w {
position: relative;
width: 30%;
overflow: hidden;
float: left;
}
.vp-video-details{
width:70%;
float:left;
}
.vp-video-img-w img {
max-width: 100%;
}
.video-thumbnail:after {
content: '';
display: block;
clear:both;
}
.footer {
border-top: 1px solid #444;
padding-top: 20px;
margin-top: 20px;
color: #999
}
.p {
text-align: center;
padding-top: 120px;
}
.p a {
text-decoration: underline;
color: blue;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row content">
<div class="col-md-7 col-sm-6">
<div class="active-iframe-wrapper video-embed-container">
<iframe id='activeIFrame' class='active-iframe' width='100%' height='324' src="http://www.youtube.com/embed/SCRUg5s389Q?showinfo=0&modestbranding=1" ></iframe>
</div>
<p>Title of the video</p>
</div>
<div class="col-md-5 col-sm-6">
<a class="video-thumbnail" href="http://www.youtube.com/embed/SCRUg5s389Q?showinfo=0&modestbranding=1">
<div class="vp-video-img-w vp-hqdefault-w">
<img src="http://img.youtube.com/vi/SCRUg5s389Q/hqdefault.jpg" title="">
</div>
<div class="vp-video-details">
<h3 class="video-title">Mr. Bean is back on the road One</h3>
</div>
</a>
<a class="video-thumbnail" href="http://www.youtube.com/embed/QThP5kDUJJ0?showinfo=0&modestbranding=1">
<div class="vp-video-img-w vp-hqdefault-w">
<img src="http://img.youtube.com/vi/QThP5kDUJJ0/hqdefault.jpg" title="">
</div>
<div class="vp-video-details">
<h3 class="video-title">Mr. Bean is back on the road Two</h3>
</div>
</a>
<a class="video-thumbnail" href="http://www.youtube.com/embed/xIOP1PLjUTs?showinfo=0&modestbranding=1">
<div class="vp-video-img-w vp-hqdefault-w">
<img src="http://img.youtube.com/vi/xIOP1PLjUTs/hqdefault.jpg" title="">
</div>
<div class="vp-video-details">
<h3 class="video-title">Mr. Bean is back on the road Three</h3>
</div>
</a>
</div>
</div>
``` | Change
```
.vp-video-img-w {
position: relative;
width: 100%;
overflow: hidden;
}
```
to
```
.vp-video-img-w {
position: relative;
width: 100%;
overflow: hidden;
float: left;
}
``` |
51,223,484 | I am trying add a custom back button so that I can perform some tasks before popping the controller. But no matter how hard I tried this function bind with back button doesn't work. I am adding some code to understand
```
-(void)customizeNavigationBar
{
self.navigationController.navigationBarHidden = NO;
self.navigationItem.title = @"Video Call";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@" " style:UIBarButtonItemStylePlain
target:self action:@selector(didBackBtnTap)];
[self.navigationItem setBackBarButtonItem:backButton];
}
```
and this is the function, which is not calling at all,
```
-(void)didBackBtnTap
{
[self popToProfileScreen];
}
```
Please suggest any solution, Thanks in advance. | 2018/07/07 | [
"https://Stackoverflow.com/questions/51223484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540925/"
] | Use `leftbarbutton` item instead of `setBackBarButtonItem`
```
self.navigationItem.leftBarButtonItem = backButton;
``` | Another option is to write your custom code in viewWillDisappear. |
51,223,484 | I am trying add a custom back button so that I can perform some tasks before popping the controller. But no matter how hard I tried this function bind with back button doesn't work. I am adding some code to understand
```
-(void)customizeNavigationBar
{
self.navigationController.navigationBarHidden = NO;
self.navigationItem.title = @"Video Call";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@" " style:UIBarButtonItemStylePlain
target:self action:@selector(didBackBtnTap)];
[self.navigationItem setBackBarButtonItem:backButton];
}
```
and this is the function, which is not calling at all,
```
-(void)didBackBtnTap
{
[self popToProfileScreen];
}
```
Please suggest any solution, Thanks in advance. | 2018/07/07 | [
"https://Stackoverflow.com/questions/51223484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540925/"
] | Use `leftbarbutton` item instead of `setBackBarButtonItem`
```
self.navigationItem.leftBarButtonItem = backButton;
``` | Use this code
```
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 15, 15);
[backButton setImage:[UIImage imageNamed:@"backButtonImage"] forState:UIControlStateNormal];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
[backButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
```
Add an image(15\*15, @1x @2x @3x) like back button of NavigationBar in xcasstes *backButtonImage*
```
- (void)backButtonPressed {}
``` |
51,223,484 | I am trying add a custom back button so that I can perform some tasks before popping the controller. But no matter how hard I tried this function bind with back button doesn't work. I am adding some code to understand
```
-(void)customizeNavigationBar
{
self.navigationController.navigationBarHidden = NO;
self.navigationItem.title = @"Video Call";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@" " style:UIBarButtonItemStylePlain
target:self action:@selector(didBackBtnTap)];
[self.navigationItem setBackBarButtonItem:backButton];
}
```
and this is the function, which is not calling at all,
```
-(void)didBackBtnTap
{
[self popToProfileScreen];
}
```
Please suggest any solution, Thanks in advance. | 2018/07/07 | [
"https://Stackoverflow.com/questions/51223484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540925/"
] | When you use the `setLeftBarButtonItem` or `setBackBarButtonItem`, it will take effect on the viewController you’re pushing to but not the current one. That’s why you need to directly set the current `leftBarButtonItem` | Another option is to write your custom code in viewWillDisappear. |
51,223,484 | I am trying add a custom back button so that I can perform some tasks before popping the controller. But no matter how hard I tried this function bind with back button doesn't work. I am adding some code to understand
```
-(void)customizeNavigationBar
{
self.navigationController.navigationBarHidden = NO;
self.navigationItem.title = @"Video Call";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@" " style:UIBarButtonItemStylePlain
target:self action:@selector(didBackBtnTap)];
[self.navigationItem setBackBarButtonItem:backButton];
}
```
and this is the function, which is not calling at all,
```
-(void)didBackBtnTap
{
[self popToProfileScreen];
}
```
Please suggest any solution, Thanks in advance. | 2018/07/07 | [
"https://Stackoverflow.com/questions/51223484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540925/"
] | When you use the `setLeftBarButtonItem` or `setBackBarButtonItem`, it will take effect on the viewController you’re pushing to but not the current one. That’s why you need to directly set the current `leftBarButtonItem` | Use this code
```
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 15, 15);
[backButton setImage:[UIImage imageNamed:@"backButtonImage"] forState:UIControlStateNormal];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
[backButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
```
Add an image(15\*15, @1x @2x @3x) like back button of NavigationBar in xcasstes *backButtonImage*
```
- (void)backButtonPressed {}
``` |
1,573,901 | I am wondering about the parameters for constructing a `ConcurrentHashMap`:
* `initialCapacity` is 16 by default (understood).
* `loadFactor` is 0.75 by default.
* `concurrencyLevel` is 16 by default.
My questions are:
* What criteria should be used to adjust `loadFactor` up or down?
* How do we establish the number of concurrently updating threads?
* What criteria should be used to adjust `concurrencyLevel` up or down?
Additionally:
* What are the hallmarks of a **good** hashcode implementation? (If an SO question addresses this, just link to it.)
Thank you! | 2009/10/15 | [
"https://Stackoverflow.com/questions/1573901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117783/"
] | Load Factor is primarily related to the quality of the hash function. The closer to zero the load factor the less likely there are to be collisions even if the hash function isn't so great. The trade off is that the memory footprint is larger. In other words, the HashMap isn't distributing the entries in seperate buckets for each seperate hashcode, it is grouping them by a proximity, so the more buckets it has, the more spread out the distribution, the less likely that there are collisions.
So the bottom line is you fiddle with load factor to improve lookup time or reduce memory, according to your needs and the objects you are storing in the Map.
ConcurrencyLevel really depends on your application. If you only have two or three threads running in the application, there you go. If you are an application server with an arbitrary number of threads, then you need to understand what your load capacity is and what point you want to optimize for.
A good quality hashcode implementation provides as wide a distribution across potential values of the object as possible with the least number of collisions, while honoring the contract. In other words, it allows the HashMap (or Set as the case may be) to distribute the objects into separate buckets making lookups faster. | loadFactor: controls when the implementation decides to resize the hashtable. Too high a value will waste space; too low a value will result in expensive resize operations.
concurrencyLevel: tells the implementation to try to optimize for the given number of writing threads. According to the API docs, being off by up to a factor of 10 shouldn't have much effect on performance.
>
> The allowed concurrency among update
> operations is guided by the optional
> concurrencyLevel constructor argument
> (default 16), which is used as a hint
> for internal sizing. The table is
> internally partitioned to try to
> permit the indicated number of
> concurrent updates without contention.
> Because placement in hash tables is
> essentially random, the actual
> concurrency will vary. Ideally, you
> should choose a value to accommodate
> as many threads as will ever
> concurrently modify the table. Using a
> significantly higher value than you
> need can waste space and time, and a
> significantly lower value can lead to
> thread contention. But overestimates
> and underestimates within an order of
> magnitude do not usually have much
> noticeable impact.
>
>
>
A good hashcode implementation will distribute the hash values uniformly over any interval. If the set of keys is known in advance it is possible to define a "perfect" hash function that creates a unique hash value for each key. |
1,573,901 | I am wondering about the parameters for constructing a `ConcurrentHashMap`:
* `initialCapacity` is 16 by default (understood).
* `loadFactor` is 0.75 by default.
* `concurrencyLevel` is 16 by default.
My questions are:
* What criteria should be used to adjust `loadFactor` up or down?
* How do we establish the number of concurrently updating threads?
* What criteria should be used to adjust `concurrencyLevel` up or down?
Additionally:
* What are the hallmarks of a **good** hashcode implementation? (If an SO question addresses this, just link to it.)
Thank you! | 2009/10/15 | [
"https://Stackoverflow.com/questions/1573901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117783/"
] | The short answer: set "initial capacity" to roughly how many mappings you expect to put in the map, and leave the other parameters at their default.
Long answer:
* load factor is the ratio between the
number of "buckets" in the map and
the number of expected elements;
* 0.75 is usually a reasonable compromise-- as I recall, it means that with a
good hash function, on average we
expect about 1.6 redirects to find an
element in the map (or around that figure);
+ changing the load
factor changes the compromise between
more redirects to find an element but
less wasted space-- put 0.75 is
really usually a good value;
+ in principle, set ConcurrencyLevel to
the number of concurrent threads you
expect to have modifying the map,
although overestimating this doesn't
appear to have a bad effect other
than wasting memory (I wrote a little
on [ConcurrentHashMap performance](http://www.javamex.com/tutorials/synchronization_concurrency_8_hashmap.shtml)
a while ago in case you're
interested)
Informally, your hash function should essentially aim to have as much "randomness" in the bits as possible. Or more strictly, the hash code for a given element should give each bit a roughly 50% chance of being set. It's actually easier to illustrate this with an example: again, you may be interested in some stuff I wrote about [how the String hash function works](http://www.javamex.com/tutorials/collections/hash_function_technical.shtml) and associated [hash function guidelines](http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml). Feedback is obvioulsy welcome on any of this stuff.
One thing I also mention at some point is that you don't have to be too paranoid in practice: if your hash function produces a "reasonable" amount of randomness in *some* of the bits, then it will often be OK. In the worst case, sticking representative pieces of data into a string and taking the hash code of the string actually doesn't work so badly. | loadFactor: controls when the implementation decides to resize the hashtable. Too high a value will waste space; too low a value will result in expensive resize operations.
concurrencyLevel: tells the implementation to try to optimize for the given number of writing threads. According to the API docs, being off by up to a factor of 10 shouldn't have much effect on performance.
>
> The allowed concurrency among update
> operations is guided by the optional
> concurrencyLevel constructor argument
> (default 16), which is used as a hint
> for internal sizing. The table is
> internally partitioned to try to
> permit the indicated number of
> concurrent updates without contention.
> Because placement in hash tables is
> essentially random, the actual
> concurrency will vary. Ideally, you
> should choose a value to accommodate
> as many threads as will ever
> concurrently modify the table. Using a
> significantly higher value than you
> need can waste space and time, and a
> significantly lower value can lead to
> thread contention. But overestimates
> and underestimates within an order of
> magnitude do not usually have much
> noticeable impact.
>
>
>
A good hashcode implementation will distribute the hash values uniformly over any interval. If the set of keys is known in advance it is possible to define a "perfect" hash function that creates a unique hash value for each key. |
1,573,901 | I am wondering about the parameters for constructing a `ConcurrentHashMap`:
* `initialCapacity` is 16 by default (understood).
* `loadFactor` is 0.75 by default.
* `concurrencyLevel` is 16 by default.
My questions are:
* What criteria should be used to adjust `loadFactor` up or down?
* How do we establish the number of concurrently updating threads?
* What criteria should be used to adjust `concurrencyLevel` up or down?
Additionally:
* What are the hallmarks of a **good** hashcode implementation? (If an SO question addresses this, just link to it.)
Thank you! | 2009/10/15 | [
"https://Stackoverflow.com/questions/1573901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117783/"
] | Load Factor is primarily related to the quality of the hash function. The closer to zero the load factor the less likely there are to be collisions even if the hash function isn't so great. The trade off is that the memory footprint is larger. In other words, the HashMap isn't distributing the entries in seperate buckets for each seperate hashcode, it is grouping them by a proximity, so the more buckets it has, the more spread out the distribution, the less likely that there are collisions.
So the bottom line is you fiddle with load factor to improve lookup time or reduce memory, according to your needs and the objects you are storing in the Map.
ConcurrencyLevel really depends on your application. If you only have two or three threads running in the application, there you go. If you are an application server with an arbitrary number of threads, then you need to understand what your load capacity is and what point you want to optimize for.
A good quality hashcode implementation provides as wide a distribution across potential values of the object as possible with the least number of collisions, while honoring the contract. In other words, it allows the HashMap (or Set as the case may be) to distribute the objects into separate buckets making lookups faster. | >
> loadFactor is set to 0.75 by default,
> what criteria should be used to adjust
> this up or down?
>
>
>
You need some background in how hash maps work before you can understand how this works. The map is essentially a series of buckets. Each value in the map gets put in to a bucket depending on what its hash code is. The loadFactor means, if the buckets are more than 75% full, the Map should be resized
>
> concurrencyLevel is set to 16 by
> default, how do we establish the
> number of concurrently updating
> threads? What criteria should be used
> to adjust this up or down?
>
>
>
This is asking how many threads to you expect to modify the Map concurrently (simultaneously)
For hash codes, see Joshua Bloch's [Effective Java](http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA45&lpg=PA45&dq=effective+java+hash+code&source=bl&ots=yXHkOgv_S-&sig=EVALdDYgWGQfSE5Lg_Vmdeo2yVQ&hl=en&ei=hF3XSov1FIak8AbErK3UCA&sa=X&oi=book_result&ct=result&resnum=6&ved=0CCMQ6AEwBQ#v=onepage&q=&f=false) |
1,573,901 | I am wondering about the parameters for constructing a `ConcurrentHashMap`:
* `initialCapacity` is 16 by default (understood).
* `loadFactor` is 0.75 by default.
* `concurrencyLevel` is 16 by default.
My questions are:
* What criteria should be used to adjust `loadFactor` up or down?
* How do we establish the number of concurrently updating threads?
* What criteria should be used to adjust `concurrencyLevel` up or down?
Additionally:
* What are the hallmarks of a **good** hashcode implementation? (If an SO question addresses this, just link to it.)
Thank you! | 2009/10/15 | [
"https://Stackoverflow.com/questions/1573901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117783/"
] | The short answer: set "initial capacity" to roughly how many mappings you expect to put in the map, and leave the other parameters at their default.
Long answer:
* load factor is the ratio between the
number of "buckets" in the map and
the number of expected elements;
* 0.75 is usually a reasonable compromise-- as I recall, it means that with a
good hash function, on average we
expect about 1.6 redirects to find an
element in the map (or around that figure);
+ changing the load
factor changes the compromise between
more redirects to find an element but
less wasted space-- put 0.75 is
really usually a good value;
+ in principle, set ConcurrencyLevel to
the number of concurrent threads you
expect to have modifying the map,
although overestimating this doesn't
appear to have a bad effect other
than wasting memory (I wrote a little
on [ConcurrentHashMap performance](http://www.javamex.com/tutorials/synchronization_concurrency_8_hashmap.shtml)
a while ago in case you're
interested)
Informally, your hash function should essentially aim to have as much "randomness" in the bits as possible. Or more strictly, the hash code for a given element should give each bit a roughly 50% chance of being set. It's actually easier to illustrate this with an example: again, you may be interested in some stuff I wrote about [how the String hash function works](http://www.javamex.com/tutorials/collections/hash_function_technical.shtml) and associated [hash function guidelines](http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml). Feedback is obvioulsy welcome on any of this stuff.
One thing I also mention at some point is that you don't have to be too paranoid in practice: if your hash function produces a "reasonable" amount of randomness in *some* of the bits, then it will often be OK. In the worst case, sticking representative pieces of data into a string and taking the hash code of the string actually doesn't work so badly. | >
> loadFactor is set to 0.75 by default,
> what criteria should be used to adjust
> this up or down?
>
>
>
You need some background in how hash maps work before you can understand how this works. The map is essentially a series of buckets. Each value in the map gets put in to a bucket depending on what its hash code is. The loadFactor means, if the buckets are more than 75% full, the Map should be resized
>
> concurrencyLevel is set to 16 by
> default, how do we establish the
> number of concurrently updating
> threads? What criteria should be used
> to adjust this up or down?
>
>
>
This is asking how many threads to you expect to modify the Map concurrently (simultaneously)
For hash codes, see Joshua Bloch's [Effective Java](http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA45&lpg=PA45&dq=effective+java+hash+code&source=bl&ots=yXHkOgv_S-&sig=EVALdDYgWGQfSE5Lg_Vmdeo2yVQ&hl=en&ei=hF3XSov1FIak8AbErK3UCA&sa=X&oi=book_result&ct=result&resnum=6&ved=0CCMQ6AEwBQ#v=onepage&q=&f=false) |
1,573,901 | I am wondering about the parameters for constructing a `ConcurrentHashMap`:
* `initialCapacity` is 16 by default (understood).
* `loadFactor` is 0.75 by default.
* `concurrencyLevel` is 16 by default.
My questions are:
* What criteria should be used to adjust `loadFactor` up or down?
* How do we establish the number of concurrently updating threads?
* What criteria should be used to adjust `concurrencyLevel` up or down?
Additionally:
* What are the hallmarks of a **good** hashcode implementation? (If an SO question addresses this, just link to it.)
Thank you! | 2009/10/15 | [
"https://Stackoverflow.com/questions/1573901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117783/"
] | The short answer: set "initial capacity" to roughly how many mappings you expect to put in the map, and leave the other parameters at their default.
Long answer:
* load factor is the ratio between the
number of "buckets" in the map and
the number of expected elements;
* 0.75 is usually a reasonable compromise-- as I recall, it means that with a
good hash function, on average we
expect about 1.6 redirects to find an
element in the map (or around that figure);
+ changing the load
factor changes the compromise between
more redirects to find an element but
less wasted space-- put 0.75 is
really usually a good value;
+ in principle, set ConcurrencyLevel to
the number of concurrent threads you
expect to have modifying the map,
although overestimating this doesn't
appear to have a bad effect other
than wasting memory (I wrote a little
on [ConcurrentHashMap performance](http://www.javamex.com/tutorials/synchronization_concurrency_8_hashmap.shtml)
a while ago in case you're
interested)
Informally, your hash function should essentially aim to have as much "randomness" in the bits as possible. Or more strictly, the hash code for a given element should give each bit a roughly 50% chance of being set. It's actually easier to illustrate this with an example: again, you may be interested in some stuff I wrote about [how the String hash function works](http://www.javamex.com/tutorials/collections/hash_function_technical.shtml) and associated [hash function guidelines](http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml). Feedback is obvioulsy welcome on any of this stuff.
One thing I also mention at some point is that you don't have to be too paranoid in practice: if your hash function produces a "reasonable" amount of randomness in *some* of the bits, then it will often be OK. In the worst case, sticking representative pieces of data into a string and taking the hash code of the string actually doesn't work so badly. | Load Factor is primarily related to the quality of the hash function. The closer to zero the load factor the less likely there are to be collisions even if the hash function isn't so great. The trade off is that the memory footprint is larger. In other words, the HashMap isn't distributing the entries in seperate buckets for each seperate hashcode, it is grouping them by a proximity, so the more buckets it has, the more spread out the distribution, the less likely that there are collisions.
So the bottom line is you fiddle with load factor to improve lookup time or reduce memory, according to your needs and the objects you are storing in the Map.
ConcurrencyLevel really depends on your application. If you only have two or three threads running in the application, there you go. If you are an application server with an arbitrary number of threads, then you need to understand what your load capacity is and what point you want to optimize for.
A good quality hashcode implementation provides as wide a distribution across potential values of the object as possible with the least number of collisions, while honoring the contract. In other words, it allows the HashMap (or Set as the case may be) to distribute the objects into separate buckets making lookups faster. |
1,878,301 | I have some images inside links that I want to essentially look like this:
```
<a href="/path/to/img.png"><img src="/path/to/img.png" /></a>
```
Clicking on the link should load the image it contains. I'm trying to use CakePHP's HTML helper to do this, as follows:
```
<?php
echo $html->link(
$html->image('img.png'),
'img.png',
array('escape' => false)
);
?>
```
When I do this, however, I get the following code:
```
<a href="/pages/img.png"><img src="/path/to/img.png" /></a>
```
**Without using absolute URLs**, can I make the link's `href` attribute point to the image's correct location?
Thanks! | 2009/12/10 | [
"https://Stackoverflow.com/questions/1878301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197560/"
] | This should do the trick:
```
echo $html->image('image.png', array('url' => '/' . IMAGES_URL . 'image.png'));
``` | you can also do this in 1.2
```
echo $html->link(
$html->image('img.png'),
'img.png',
array(),
null,
false
);
```
or in 1.3
```
echo $html->link(
$html->image('img.png'),
'img.png',
array(),
array( 'escape' => false ),
);
``` |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | Here's one way to do it:
```
int is_bang_num(const char *s) {
if (*s != '!') {
return 0;
}
size_t n = strspn(s + 1, "0123456789");
return n > 0 && s[1 + n] == '\0';
}
```
This verifies that the first character is `!`, that it is followed by more characters, and that all of those following characters are digits. | If you want to test that a string matches a format of an exclamation point and then some series of numbers, this regex: "!\d+" will match that. That won't catch if the first number is a zero, which is invalid. This will: "![1,2,3,4,5,6,7,8,9]\d\*". |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | Here's one way to do it:
```
int is_bang_num(const char *s) {
if (*s != '!') {
return 0;
}
size_t n = strspn(s + 1, "0123456789");
return n > 0 && s[1 + n] == '\0';
}
```
This verifies that the first character is `!`, that it is followed by more characters, and that all of those following characters are digits. | You see, `scanf()` family of functions return a value indicating how many parameters where converted.
Even books usually ignore this value and it leads programmers to ignore that it does return a value. One of the consequences of this is *Undefined Behavior* when the `scanf()` function failed and the value was not initialized, not before calling `scanf()` and since it has failed not by `scanf()` either.
You can use this value returned by `sscanf()` to check for success, like this
```
#include <stdio.h>
int
main(void)
{
const char *string;
int value;
int result;
string = "!12345";
result = sscanf(string, "!%d", &value);
if (result == 1)
fprintf(stderr, "the value was: %d\n", value);
else
fprintf(stderr, "the string did not match the pattern\n");
return 0;
}
```
As you can see, if one parameter was successfuly scanned it means that the string matched pattern, otherwise it didn't.
With this approach you also extract the integral value, but you should be careful because `scanf()`'s are not meant for regular expressions, this would work in very simple situations. |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | Here's one way to do it:
```
int is_bang_num(const char *s) {
if (*s != '!') {
return 0;
}
size_t n = strspn(s + 1, "0123456789");
return n > 0 && s[1 + n] == '\0';
}
```
This verifies that the first character is `!`, that it is followed by more characters, and that all of those following characters are digits. | Since the stirng must begin with a ! and follow with an integer, use a qualified `strtol()` which allows a leading sign character. As OP did not specify the range of the integer, let us allow any range.
```
int is_sc_num(const char *str) {
if (*str != '!') return 0;
str++;
// Insure no spaces- something strtol() allows.
if (isspace((unsigned char) *str) return 0;
char *endptr;
// errno = 0;
// By using base 0, input like "0xABC" allowed
strtol(str, &endptr, 0);
// no check for errno as code allows any range
// if (errno == ERANGE) return 0
if (str == endptr) return 0; // no digits
if (*endptr) return 0; // Extra character at the end
return 1;
}
``` |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | You see, `scanf()` family of functions return a value indicating how many parameters where converted.
Even books usually ignore this value and it leads programmers to ignore that it does return a value. One of the consequences of this is *Undefined Behavior* when the `scanf()` function failed and the value was not initialized, not before calling `scanf()` and since it has failed not by `scanf()` either.
You can use this value returned by `sscanf()` to check for success, like this
```
#include <stdio.h>
int
main(void)
{
const char *string;
int value;
int result;
string = "!12345";
result = sscanf(string, "!%d", &value);
if (result == 1)
fprintf(stderr, "the value was: %d\n", value);
else
fprintf(stderr, "the string did not match the pattern\n");
return 0;
}
```
As you can see, if one parameter was successfuly scanned it means that the string matched pattern, otherwise it didn't.
With this approach you also extract the integral value, but you should be careful because `scanf()`'s are not meant for regular expressions, this would work in very simple situations. | If you want to test that a string matches a format of an exclamation point and then some series of numbers, this regex: "!\d+" will match that. That won't catch if the first number is a zero, which is invalid. This will: "![1,2,3,4,5,6,7,8,9]\d\*". |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | Since the stirng must begin with a ! and follow with an integer, use a qualified `strtol()` which allows a leading sign character. As OP did not specify the range of the integer, let us allow any range.
```
int is_sc_num(const char *str) {
if (*str != '!') return 0;
str++;
// Insure no spaces- something strtol() allows.
if (isspace((unsigned char) *str) return 0;
char *endptr;
// errno = 0;
// By using base 0, input like "0xABC" allowed
strtol(str, &endptr, 0);
// no check for errno as code allows any range
// if (errno == ERANGE) return 0
if (str == endptr) return 0; // no digits
if (*endptr) return 0; // Extra character at the end
return 1;
}
``` | If you want to test that a string matches a format of an exclamation point and then some series of numbers, this regex: "!\d+" will match that. That won't catch if the first number is a zero, which is invalid. This will: "![1,2,3,4,5,6,7,8,9]\d\*". |
32,673,507 | I'm trying to compare an input of characters with a string that can be of the format "!x" where x is any integer.
What's the easiest way to do this? I tried
```
int result = strcmp(input,"!%d");
```
which did not work. | 2015/09/19 | [
"https://Stackoverflow.com/questions/32673507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2548040/"
] | You see, `scanf()` family of functions return a value indicating how many parameters where converted.
Even books usually ignore this value and it leads programmers to ignore that it does return a value. One of the consequences of this is *Undefined Behavior* when the `scanf()` function failed and the value was not initialized, not before calling `scanf()` and since it has failed not by `scanf()` either.
You can use this value returned by `sscanf()` to check for success, like this
```
#include <stdio.h>
int
main(void)
{
const char *string;
int value;
int result;
string = "!12345";
result = sscanf(string, "!%d", &value);
if (result == 1)
fprintf(stderr, "the value was: %d\n", value);
else
fprintf(stderr, "the string did not match the pattern\n");
return 0;
}
```
As you can see, if one parameter was successfuly scanned it means that the string matched pattern, otherwise it didn't.
With this approach you also extract the integral value, but you should be careful because `scanf()`'s are not meant for regular expressions, this would work in very simple situations. | Since the stirng must begin with a ! and follow with an integer, use a qualified `strtol()` which allows a leading sign character. As OP did not specify the range of the integer, let us allow any range.
```
int is_sc_num(const char *str) {
if (*str != '!') return 0;
str++;
// Insure no spaces- something strtol() allows.
if (isspace((unsigned char) *str) return 0;
char *endptr;
// errno = 0;
// By using base 0, input like "0xABC" allowed
strtol(str, &endptr, 0);
// no check for errno as code allows any range
// if (errno == ERANGE) return 0
if (str == endptr) return 0; // no digits
if (*endptr) return 0; // Extra character at the end
return 1;
}
``` |
6,393,464 | I have gone through tons of the form\_for nested resource questions and can't get any of the solutions to work for me. I figured its time to ask a personalized question.
I have two models, jobs and questions, jobs has\_many questions and questions belong\_to jobs.
I used scaffolding to create the controllers and models then nested the resources in the routes.rb.
```
root :to => "pages#home"
resources :jobs do
resources :questions
end
get "pages/home"
get "pages/about"
get "pages/contact"
class Job < ActiveRecord::Base
has_many :questions
end
class Question < ActiveRecord::Base
belongs_to :job
end
```
Right now I am trying to access '/jobs/1/questions/new' and keep getting the
NoMethodError in Questions#new
I started with the error **No route matches {:controller=>"questions"}** when the code was
```
<%= form_for(@question) do |f| %>
```
I know this is wrong, so I started to try other combos and none of them worked.
I've tried
```
<%= form_for([@job.questions.build ]) do |f| %>
```
that
```
<%= form_for([@job, @job.questions.build ]) do |f| %>
```
that
```
<%= form_for(@job, @question) do |f| %>
```
Among a bunch of other combinations and that are not working.
Here is a link to my rake routes : git clone <https://gist.github.com/1032734>
Any help is appreciated and let me know if you need more info, thanks. | 2011/06/18 | [
"https://Stackoverflow.com/questions/6393464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583964/"
] | I just pass the URL as an extra option:
```
<%= form_for(@question, :url => job_questions_path(@job)) do %>
```
**EDIT:**
Also try:
```
form_for([@job, @question])
``` | This is how I solved mine :)
In your `questions/_form.html.erb`
```
<%= form_for [@job, @question] do %>
```
For this to work, you need the job's id. You'll pass it as follows:
In the `questions_controller.rb`
```
def new
@job = Job.find(params[job_id])
@question = @job.questions.build
end
```
Build(`.build`) is similar to using new(`.new`) in the code above, with differences only in older versions of rails; rails 2 down.
Now for the create action (still in `questions_controller.rb`)
```
def create
@job = Job.find(params[:job_id])
@question = @job.questions.build(question_params)
end
```
If you only use these, the job\_id and user\_id field in the question model will be empty. To add the ids, do this:
In your `questions_controller.rb` add job\_id to job\_params like so:
```
def question_params
params.require(:question).permit(:ahaa, :ohoo, :job_id)
end
```
Then to pass the user's id (if you are using Devise), do:
```
def create
@job = Job.find(params[:job_id])
@question = @job.questions.build(question_params)
@question.user_id = current_user.id
end
``` |
16,526,921 | Below I have included some code from my model and my view. It tells me that the $date variable does not exist. I dont understand why it wouldnt. I am changing over from it being objects so thats why some of the old code still has $data-> and why its being changed to $data['']. Regardless its now telling me that $data does not exist.
This is the code from my view.
```
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'type'=>'condensed',
'dataProvider'=>$gridDataProvider,
'template'=>"{items}",
'columns'=>array(
array('name'=>'id', 'header'=>'Name'),
array('name'=>'emax', 'header'=>'Employees' 'value'=>$date['id']),
/*array('name'=>'location', 'value'=>'$data->city . ", " . $data->state->name', 'header'=>'Location'),
array('name'=>'phone', 'header'=>'Phone'),
array('name'=>'website', 'header'=>'Website'),
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
'htmlOptions'=>array('style'=>'width: 50px'),
'template'=>"{view}",
'buttons'=>array(
'view'=>array(
'url'=>'Yii::app()->createUrl("account/rinkdetail", array("id"=>$data->id))',
),
),
),*/
),
));
?>
```
This is the code from my model
```
$sql="SELECT buyer.id, emax.max as emax, emin.min as emin, rmin.min as rmin, rmin.max as rmax, firm.name as firm, region.name as region, project.name as project
FROM buyer
LEFT JOIN buyer_target target on buyer.id=target.buyer_id
LEFT JOIN employee emax on emax.id=target.max_employee_id
LEFT JOIN employee emin on emin.id=target.min_employee_id
LEFT JOIN revenue rmax on rmax.id=target.max_revenue_id
LEFT JOIN revenue rmin on rmin.id=target.min_revenue_id
LEFT JOIN buyer_target_firm tfirm on buyer.id=tfirm.buyer_id
LEFT JOIN firm on firm.id=tfirm.firm_id
LEFT JOIN buyer_target_project tproject on buyer.id=tproject.buyer_id
LEFT JOIN project on project.id=tproject.project_id
LEFT JOIN buyer_target_region tregion on buyer.id=tregion.buyer_Id
LEFT JOIN region on region.id=tregion.region_id";
$gridDataProvider = new CSqlDataProvider($sql);
return $gridDataProvider;
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16526921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892484/"
] | I was able to figure it out. In my example used above it was saying
```
'value'=>$date['id']
```
Even though I had DATE in my example, I was using DATA in my actual test.
What the actual problem was it that it needs to be...
```
'value'=>'$data["id"]'
``` | Replace:
```
array('name'=>'emax', 'header'=>'Employees' 'value'=>$date['id']),
```
With:
```
array('name'=>'emax', 'header'=>'Employees', 'value'=>$date['id']),
``` |
68,440 | Can anyone please help me on this..
I have a column in my table that stores the duration in an `nvarchar` field formatted as '00:00:00'.
How do I calculate the average duration? I read some other blogs and also used cast techniques like the one below but couldn't solve my problem...
```
cast(cast(avg(cast(CAST(Duration as datetime) as float)) as datetime) as time) AvgTime
```
Please help... | 2014/06/17 | [
"https://dba.stackexchange.com/questions/68440",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/38142/"
] | I assume you must have invalid data stored in your `nvarchar` field. I created a simple test to obtain average duration, which works:
```
DECLARE @T TABLE
(
duration NVARCHAR(8)
);
INSERT INTO @T VALUES ('00:00:05');
INSERT INTO @T VALUES ('00:01:04');
INSERT INTO @T VALUES ('00:02:03');
INSERT INTO @T VALUES ('03:00:02');
INSERT INTO @T VALUES ('04:00:01');
SELECT CAST(AVG(CAST(CAST(duration AS DATETIME) AS DECIMAL(10,5))) AS DATETIME)
FROM @T;
```
This returns:

If you want the result in time format, you could do the following, although I would recommend not doing this part in T-SQL - you should do presentation layer stuff in the presentation layer.
```
SELECT CONVERT(VARCHAR(255), CAST(AVG(CAST(CAST(duration AS DATETIME) AS DECIMAL(10,5))) AS DATETIME), 108)
FROM @T;
```

I've been convinced by this question, and Aaron's excellent answer, that duration should be stored either using start and end fields using some type of date data-type, or as a simple integer expressing the duration in the smallest necessary increment. For instance, if you are only interested in how many weeks something took, simply store the number of weeks as an `INT`. To see the chat transcript that convinced me, see <http://chat.stackexchange.com/transcript/message/16134865#16134865> | If you can't afford to refactor this field as an integer right now but you need better performance or simplicity for aggregate calculations, you may want to consider a **computed field**:
```
ALTER TABLE timetable ADD DurationSeconds AS DATEDIFF(SECOND, '00:00:00', Duration);
```
You can then index this field if needed.
Based on a comment below, here's an alternative that seems to avoid conversion of the `00:00:00` argument (which I would've thought would be part of the compilation of the statement but I guess not!):
```
ALTER TABLE timetable ADD DurationSeconds AS DATEDIFF(SECOND, 0, Duration);
```
And here's a version that avoids DATEDIFF() entirely:
```
CAST(CAST('00:30:00' AS datetime) AS float) * 86400
```
My original answer used SUBSTRING() to directly convert the hours, minutes, and seconds to a total number of seconds. My testing found that DATEDIFF() was slower, but YMMV. Here's the alternate method:
```
ALTER TABLE timetable ADD DurationSeconds AS
3600 * CAST(LEFT(Duration, 2) AS int)
+ 60 * CAST(SUBSTRING(Duration, 4, 2) AS int)
+ CAST(RIGHT(Duration, 2) AS int);
```
Regardless which method you choose, you get a dynamically-calculated value that you can pass to AVERAGE(), SUM(), etc. as needed. |
68,440 | Can anyone please help me on this..
I have a column in my table that stores the duration in an `nvarchar` field formatted as '00:00:00'.
How do I calculate the average duration? I read some other blogs and also used cast techniques like the one below but couldn't solve my problem...
```
cast(cast(avg(cast(CAST(Duration as datetime) as float)) as datetime) as time) AvgTime
```
Please help... | 2014/06/17 | [
"https://dba.stackexchange.com/questions/68440",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/38142/"
] | Store duration in seconds as an integer; then average is quite easy. Right now you're trying to take an average of a string converted to a float converted to a datetime converted to a time. If that doesn't sound wrong to you, read it again. Then consider that `time` represents a point time. What is the average of 3:12 AM and 4:57 PM? Meet in the middle?
Don't be tempted to change this from `nvarchar` to `time`. Again, `time` is a point in time, not an interval. You should be storing start and end values as datetime; you can always calculate duration from that (typically I see duration as an additional nonsense column that doesn't need to be stored in the first place).
The formatting as `hh:mm:ss` should not happen at storage time, only at presentation time. And no idea why you would ever use `nvarchar` for this in the first place - what Unicode characters do you expect to support in `hh:mm:ss`?
In the meantime:
```
SELECT CONVERT(TIME(0), DATEADD(SECOND, AVG(DATEDIFF(SECOND, 0, CONVERT(DATETIME,
CASE WHEN ISDATE(Duration) = 1 THEN Duration END))),0)) -- in case of garbage data
FROM dbo.your_table_name;
```
See how messy that is? Wouldn't it be much easier as:
```
SELECT AVG(Duration) FROM dbo.your_table_name;
```
Or:
```
SELECT AVG(DATEDIFF(SECOND, [start], [end])) FROM dbo.your_table_name;
```
And then format as hh:mm:ss in the client language? Yes, I think so. | If you can't afford to refactor this field as an integer right now but you need better performance or simplicity for aggregate calculations, you may want to consider a **computed field**:
```
ALTER TABLE timetable ADD DurationSeconds AS DATEDIFF(SECOND, '00:00:00', Duration);
```
You can then index this field if needed.
Based on a comment below, here's an alternative that seems to avoid conversion of the `00:00:00` argument (which I would've thought would be part of the compilation of the statement but I guess not!):
```
ALTER TABLE timetable ADD DurationSeconds AS DATEDIFF(SECOND, 0, Duration);
```
And here's a version that avoids DATEDIFF() entirely:
```
CAST(CAST('00:30:00' AS datetime) AS float) * 86400
```
My original answer used SUBSTRING() to directly convert the hours, minutes, and seconds to a total number of seconds. My testing found that DATEDIFF() was slower, but YMMV. Here's the alternate method:
```
ALTER TABLE timetable ADD DurationSeconds AS
3600 * CAST(LEFT(Duration, 2) AS int)
+ 60 * CAST(SUBSTRING(Duration, 4, 2) AS int)
+ CAST(RIGHT(Duration, 2) AS int);
```
Regardless which method you choose, you get a dynamically-calculated value that you can pass to AVERAGE(), SUM(), etc. as needed. |
20,668,314 | I appreciate ideas on how to stream data from an On-Premise Windows server to a persistent EMR cluster?
**Some Background**
I would like to run a persistent cluster running a MR job much like the WordCount examples that are available. I would like to stream text from a local Windows Server up to the cluster and have it processed by the running job.
All of the streaming WordCount examples I have reviewed always start with a static text file in S3 and don't cover how to implement anything to generate the stream.
Does this need to be treated in two parts?
1. Get the data first into S3
2. Stream it into the EMR cluster?
I have seen tools like Logstash which tend to run agents on the local server which tail the end of a weblog and transfer it.
As you can probably tell, I'm a Windows guy, stretching into EMR and by association Linux. Feel free to let me know if there is some way cool command line tool that already does this.
Thanks in advance. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20668314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116818/"
] | When you do a `LEFT JOIN` it's possible that the joined table will have `NULL` for all data:
```
SELECT ... WHERE table_pictures.chapter_id IS NULL
```
So you can do this to find all those where the link doesn't work, or as an inverse, `RIGHT JOIN` and select all those not in the list with a `WHERE ... NOT IN (SELECT ...)` | ```
DELETE FROM table_meta WHERE chapter_id NOT IN(
SELECT chapter_id FROM table_pictures
WHERE table_meta.chapter_id = table_pictures.chapter_id
);
``` |
20,668,314 | I appreciate ideas on how to stream data from an On-Premise Windows server to a persistent EMR cluster?
**Some Background**
I would like to run a persistent cluster running a MR job much like the WordCount examples that are available. I would like to stream text from a local Windows Server up to the cluster and have it processed by the running job.
All of the streaming WordCount examples I have reviewed always start with a static text file in S3 and don't cover how to implement anything to generate the stream.
Does this need to be treated in two parts?
1. Get the data first into S3
2. Stream it into the EMR cluster?
I have seen tools like Logstash which tend to run agents on the local server which tail the end of a weblog and transfer it.
As you can probably tell, I'm a Windows guy, stretching into EMR and by association Linux. Feel free to let me know if there is some way cool command line tool that already does this.
Thanks in advance. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20668314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116818/"
] | Here's an example how to negate your `LEFT JOIN` and use it for deleting the data in `table_meta`:
```
DELETE table_meta
FROM table_meta
LEFT JOIN table_pictures ON table_meta.chapter_id = table_pictures.chapter_id
WHERE ISNULL(table_pictures.chapter_id);
``` | When you do a `LEFT JOIN` it's possible that the joined table will have `NULL` for all data:
```
SELECT ... WHERE table_pictures.chapter_id IS NULL
```
So you can do this to find all those where the link doesn't work, or as an inverse, `RIGHT JOIN` and select all those not in the list with a `WHERE ... NOT IN (SELECT ...)` |
20,668,314 | I appreciate ideas on how to stream data from an On-Premise Windows server to a persistent EMR cluster?
**Some Background**
I would like to run a persistent cluster running a MR job much like the WordCount examples that are available. I would like to stream text from a local Windows Server up to the cluster and have it processed by the running job.
All of the streaming WordCount examples I have reviewed always start with a static text file in S3 and don't cover how to implement anything to generate the stream.
Does this need to be treated in two parts?
1. Get the data first into S3
2. Stream it into the EMR cluster?
I have seen tools like Logstash which tend to run agents on the local server which tail the end of a weblog and transfer it.
As you can probably tell, I'm a Windows guy, stretching into EMR and by association Linux. Feel free to let me know if there is some way cool command line tool that already does this.
Thanks in advance. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20668314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116818/"
] | Here's an example how to negate your `LEFT JOIN` and use it for deleting the data in `table_meta`:
```
DELETE table_meta
FROM table_meta
LEFT JOIN table_pictures ON table_meta.chapter_id = table_pictures.chapter_id
WHERE ISNULL(table_pictures.chapter_id);
``` | ```
DELETE FROM table_meta WHERE chapter_id NOT IN(
SELECT chapter_id FROM table_pictures
WHERE table_meta.chapter_id = table_pictures.chapter_id
);
``` |
1,817,179 | >
> I need to examine whether the following limit exists, or not.
> $$\lim\_{n \to +\infty} \frac{1}{n^2} \sum\_{k=1}^{n} k \ln\left( \frac{k^2+n^2}{n^2}\right )$$
> If it does, I need to calculate its value.
>
>
>
How to even start this? I've got no idea. | 2016/06/07 | [
"https://math.stackexchange.com/questions/1817179",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294766/"
] | **An idea:** "Riemann sums" may be a good start.
Massage your current sum into something of the form
$$
\frac{1}{n}\sum\_{k=0}^n \frac{k}{n} \ln \left( 1+\left(\frac{k}{n}\right)^2\right)
$$
and recognize a Riemann sum for the (continuous) function $f\colon[0,1]\to\mathbb{R}$ defined by $f(x) = x\ln(1+x^2)$.
---
**Update:** Jack d'Aurizio gave a way (actually, two) to evaluate the integral $$\int\_0^1 x\ln(1+x^2)dx$$ in his [separate answer](https://math.stackexchange.com/a/1817617/75808), which complements this one. | Just to complete [Clement C.'s answer](https://math.stackexchange.com/a/1817181/44121), integration by parts leads to:
$$\begin{eqnarray\*} I=\int\_{0}^{1}x \log(1+x^2)\,dx &=& \left.\frac{x^2}{2}\log(1+x^2)\right|\_{0}^{1}-\int\_{0}^{1}\frac{x^3}{1+x^2}\,dx\\&=&\frac{\log(2)}{2}-\int\_{0}^{1}x\,dx+\int\_{0}^{1}\frac{x\,dx}{1+x^2} \\&=&\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$
Another chance is given by termwise integration of a Taylor series:
$$\begin{eqnarray\*}I = \int\_{0}^{1}\sum\_{n\geq 1}\frac{(-1)^{n+1}x^{2n+1}}{n}\,dx&=&\frac{1}{2}\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n(n+1)}\\&=&\frac{1}{2}\left(\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n}-\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n+1}\right)\\&=&\frac{1}{2}\left(2\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n}-1\right)=\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$
A third way is given by the substitution $x=\sqrt{z-1}$ plus Feynman's trick, from which:
$$\begin{eqnarray\*} I = \frac{1}{2}\int\_{1}^{2}\log(z)\,dz = \left.\frac{1}{2}\frac{d}{d\alpha}\int\_{1}^{2}z^{\alpha}\,dz\,\right|\_{\alpha=0}&=&\left.\frac{1}{2}\frac{d}{d\alpha}\frac{2^{\alpha}-1}{\alpha}\,\right|\_{\alpha=1}\\&=&\left.\frac{1+2^a(a\log 2-1)}{2a^2}\right|\_{\alpha=1}\\&=&\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$ |
1,817,179 | >
> I need to examine whether the following limit exists, or not.
> $$\lim\_{n \to +\infty} \frac{1}{n^2} \sum\_{k=1}^{n} k \ln\left( \frac{k^2+n^2}{n^2}\right )$$
> If it does, I need to calculate its value.
>
>
>
How to even start this? I've got no idea. | 2016/06/07 | [
"https://math.stackexchange.com/questions/1817179",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294766/"
] | **An idea:** "Riemann sums" may be a good start.
Massage your current sum into something of the form
$$
\frac{1}{n}\sum\_{k=0}^n \frac{k}{n} \ln \left( 1+\left(\frac{k}{n}\right)^2\right)
$$
and recognize a Riemann sum for the (continuous) function $f\colon[0,1]\to\mathbb{R}$ defined by $f(x) = x\ln(1+x^2)$.
---
**Update:** Jack d'Aurizio gave a way (actually, two) to evaluate the integral $$\int\_0^1 x\ln(1+x^2)dx$$ in his [separate answer](https://math.stackexchange.com/a/1817617/75808), which complements this one. | Another approach. Using [Abel's summation](https://en.wikipedia.org/wiki/Abel%27s_summation_formula) we have $$S=\sum\_{k=0}^{n}k\log\left(1+\left(\frac{k}{n}\right)^{2}\right)=\frac{n\left(n+1\right)\log\left(2\right)}{2}-\int\_{0}^{n}\frac{\left\lfloor t\left(t+1\right)\right\rfloor t}{n^{2}+t^{2}}dt
$$ where $\left\lfloor x\right\rfloor
$ is the floor function. Since $\left\lfloor x\right\rfloor =x+O\left(1\right)
$ we have $$S=\frac{n\left(n+1\right)\log\left(2\right)}{2}-\int\_{0}^{n}\frac{t^{2}\left(t+1\right)}{n^{2}+t^{2}}dt+O\left(1\right)
$$ and the integral is not too complicated $$\int\_{0}^{n}\frac{t^{2}\left(t+1\right)}{n^{2}+t^{2}}dt=-n^{2}\int\_{0}^{n}\frac{t}{n^{2}+t^{2}}dt-n\int\_{0}^{n}\frac{1}{n^{2}+t^{2}}dt+\int\_{0}^{n}tdt+\int\_{0}^{n}1dt
$$ $$=-\frac{1}{4}n^{2}\log\left(4\right)+\frac{n^{2}}{2}-\frac{\pi}{4}n+n
$$ hence $$\frac{1}{n^{2}}\sum\_{k=0}^{n}k\log\left(1+\left(\frac{k}{n}\right)^{2}\right)=\log\left(2\right)+\frac{\log\left(2\right)}{n}-\frac{1}{2}-\frac{\pi}{4n}+\frac{1}{n}+O\left(\frac{1}{n}\right)\rightarrow\log\left(2\right)-\frac{1}{2}
$$ as $n\rightarrow\infty$. |
1,817,179 | >
> I need to examine whether the following limit exists, or not.
> $$\lim\_{n \to +\infty} \frac{1}{n^2} \sum\_{k=1}^{n} k \ln\left( \frac{k^2+n^2}{n^2}\right )$$
> If it does, I need to calculate its value.
>
>
>
How to even start this? I've got no idea. | 2016/06/07 | [
"https://math.stackexchange.com/questions/1817179",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294766/"
] | Just to complete [Clement C.'s answer](https://math.stackexchange.com/a/1817181/44121), integration by parts leads to:
$$\begin{eqnarray\*} I=\int\_{0}^{1}x \log(1+x^2)\,dx &=& \left.\frac{x^2}{2}\log(1+x^2)\right|\_{0}^{1}-\int\_{0}^{1}\frac{x^3}{1+x^2}\,dx\\&=&\frac{\log(2)}{2}-\int\_{0}^{1}x\,dx+\int\_{0}^{1}\frac{x\,dx}{1+x^2} \\&=&\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$
Another chance is given by termwise integration of a Taylor series:
$$\begin{eqnarray\*}I = \int\_{0}^{1}\sum\_{n\geq 1}\frac{(-1)^{n+1}x^{2n+1}}{n}\,dx&=&\frac{1}{2}\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n(n+1)}\\&=&\frac{1}{2}\left(\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n}-\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n+1}\right)\\&=&\frac{1}{2}\left(2\sum\_{n\geq 1}\frac{(-1)^{n+1}}{n}-1\right)=\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$
A third way is given by the substitution $x=\sqrt{z-1}$ plus Feynman's trick, from which:
$$\begin{eqnarray\*} I = \frac{1}{2}\int\_{1}^{2}\log(z)\,dz = \left.\frac{1}{2}\frac{d}{d\alpha}\int\_{1}^{2}z^{\alpha}\,dz\,\right|\_{\alpha=0}&=&\left.\frac{1}{2}\frac{d}{d\alpha}\frac{2^{\alpha}-1}{\alpha}\,\right|\_{\alpha=1}\\&=&\left.\frac{1+2^a(a\log 2-1)}{2a^2}\right|\_{\alpha=1}\\&=&\color{red}{\log(2)-\frac{1}{2}}.\end{eqnarray\*}$$ | Another approach. Using [Abel's summation](https://en.wikipedia.org/wiki/Abel%27s_summation_formula) we have $$S=\sum\_{k=0}^{n}k\log\left(1+\left(\frac{k}{n}\right)^{2}\right)=\frac{n\left(n+1\right)\log\left(2\right)}{2}-\int\_{0}^{n}\frac{\left\lfloor t\left(t+1\right)\right\rfloor t}{n^{2}+t^{2}}dt
$$ where $\left\lfloor x\right\rfloor
$ is the floor function. Since $\left\lfloor x\right\rfloor =x+O\left(1\right)
$ we have $$S=\frac{n\left(n+1\right)\log\left(2\right)}{2}-\int\_{0}^{n}\frac{t^{2}\left(t+1\right)}{n^{2}+t^{2}}dt+O\left(1\right)
$$ and the integral is not too complicated $$\int\_{0}^{n}\frac{t^{2}\left(t+1\right)}{n^{2}+t^{2}}dt=-n^{2}\int\_{0}^{n}\frac{t}{n^{2}+t^{2}}dt-n\int\_{0}^{n}\frac{1}{n^{2}+t^{2}}dt+\int\_{0}^{n}tdt+\int\_{0}^{n}1dt
$$ $$=-\frac{1}{4}n^{2}\log\left(4\right)+\frac{n^{2}}{2}-\frac{\pi}{4}n+n
$$ hence $$\frac{1}{n^{2}}\sum\_{k=0}^{n}k\log\left(1+\left(\frac{k}{n}\right)^{2}\right)=\log\left(2\right)+\frac{\log\left(2\right)}{n}-\frac{1}{2}-\frac{\pi}{4n}+\frac{1}{n}+O\left(\frac{1}{n}\right)\rightarrow\log\left(2\right)-\frac{1}{2}
$$ as $n\rightarrow\infty$. |
2,432,050 | Suppose a query "select streetAdr from Address" returns "236 a1 road" "333 a2 road" and 444 a4 road" as 3 rows. How i can display only "236" "333" and "444" in SQL Server. | 2010/03/12 | [
"https://Stackoverflow.com/questions/2432050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243323/"
] | Try:
```
Select left(yourcolumn, charindex(' ',yourcolumn)) ...
``` | Just to be on the safe side, if any of your addresses should only have a number and nothing else:
```
declare @Address table (AddressLine1 nvarchar(50) NOT NULL)
insert into @Address values ('236 a1 road')
insert into @Address values ('333 a2 road')
insert into @Address values ('444 a4 road')
insert into @Address values ('555')
select
CASE
WHEN charindex(' ', AddressLine1) > 0 THEN
Left(AddressLine1, charindex(' ', AddressLine1))
ELSE
AddressLine1
END AS AddressLine1
from @Address
``` |
15,171,457 | This is an extension to my [previous question](https://stackoverflow.com/questions/15169663/format-string-by-binary-list) but in a reversed order: that is, with string `-t-c-over----`, is there a way to generate a binary list that all valid letters have `1` and hyphens have `0`:
```
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
- t - c - o v e r - - - -
```
I feel sorry for the back and forth but it has to go like this. | 2013/03/02 | [
"https://Stackoverflow.com/questions/15171457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021602/"
] | ```
>>> s = '-t-c-over----'
>>> lst = [0 if i == '-' else 1 for i in s]
>>> print lst
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
```
The list comp checks if a letter is `'-'` - if it is, it puts a `0` in the list, otherwise it puts a `1` in. | You can use this
```
string = "-t-c-over----"
[0 if i == "-" else 1 for i in string]
Output: [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
``` |
15,171,457 | This is an extension to my [previous question](https://stackoverflow.com/questions/15169663/format-string-by-binary-list) but in a reversed order: that is, with string `-t-c-over----`, is there a way to generate a binary list that all valid letters have `1` and hyphens have `0`:
```
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
- t - c - o v e r - - - -
```
I feel sorry for the back and forth but it has to go like this. | 2013/03/02 | [
"https://Stackoverflow.com/questions/15171457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021602/"
] | ```
>>> s = '-t-c-over----'
>>> lst = [0 if i == '-' else 1 for i in s]
>>> print lst
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
```
The list comp checks if a letter is `'-'` - if it is, it puts a `0` in the list, otherwise it puts a `1` in. | Another option is use a lambda function and a map function.
```
s = '-t-c-over----'
output = map(lambda x: 0 if x == '-' else 1, s)
```
Edit: Apparently this doesn't work in Python 3.2 so the practical solution would be something like this.
```
s = '-t-c-over----'
output = [0 if x == '-' else 1 for x in s]
``` |
15,171,457 | This is an extension to my [previous question](https://stackoverflow.com/questions/15169663/format-string-by-binary-list) but in a reversed order: that is, with string `-t-c-over----`, is there a way to generate a binary list that all valid letters have `1` and hyphens have `0`:
```
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
- t - c - o v e r - - - -
```
I feel sorry for the back and forth but it has to go like this. | 2013/03/02 | [
"https://Stackoverflow.com/questions/15171457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021602/"
] | You can use this
```
string = "-t-c-over----"
[0 if i == "-" else 1 for i in string]
Output: [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
``` | Another option is use a lambda function and a map function.
```
s = '-t-c-over----'
output = map(lambda x: 0 if x == '-' else 1, s)
```
Edit: Apparently this doesn't work in Python 3.2 so the practical solution would be something like this.
```
s = '-t-c-over----'
output = [0 if x == '-' else 1 for x in s]
``` |
7,417,747 | I have a Business Object Layer that I use in a couple of other applications and I want to use it on my MVC application. My concern is more a design concern: Is it correct to have something like the following:
```
using Interface.MyOtherProject
public class MyMVCController: Controller
{
[HttpGet]
public string GetSomethingById(Int32 id)
{
return new JavaScriptSerializer().Serialize(MyObject.GetById(id));
}
}
```
So the question would be can I do this, should I do this in the Model instead and return this string directly from the Model or should I rewrite my BLL into my Model. I read some of the answers with similar question but it is not still clear to me if I can or cannot (rather if I should or not). I do not want to break the pattern since I will be showing this project to some companions in school.
Thanks for the help!
Hanlet | 2011/09/14 | [
"https://Stackoverflow.com/questions/7417747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752527/"
] | When we had to confront this decision, we went with creating view models that encapsulated/mirrored our business objects. This gives us more control over how the objects should look when serialized in json without having to add view logic in our business layer.
Example: Suppose we had a Person business object:
```
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
}
```
When a client is going to consume our web service, we wouldn't want them to know what the `Id` value is, since that's an internal database key. The two options we considered for fixing that is 1) add a `[ScriptIgnore]` attribute onto `Person.Id` property or create a separate view model for our Person, which is custom-tailored to the view domain.
We stayed away from option 1 because we didn't want to add view logic in our business layer for much of the same reason you don't... our business layer isn't directly tied to our presentation layer.
This is a very simplified scenario, but the larger idea is still intact. With separate view models you have the ability to include/exclude data in your view without hampering the cleanliness of your business layer. | I don't see any glaring design concerns here. To address one specific point in the question:
>
> should I do this in the Model instead and return this string directly from the Model
>
>
>
Do you mean should the model provide the JSON-serialized string? I'd say no. The model is just a representation of a business concept and contains the logic which acts upon that concept. The `JavaScriptSerializer` is basically creating a view of that model. It's UI logic and belongs right where it is, in the presentation code. The model shouldn't care how it's being viewed, it just worries about the state of what it represents.
>
> should I rewrite my BLL into my Model
>
>
>
I'm not sure what you're asking here. The models should contain the business logic, that's for certain. If your BLL is just a bunch of utility methods which use the models as bare DTOs then you might want to look into moving that business logic into the models themselves. But it's hard to tell with the code presented here.
When I see `MyObject.GetById(id)` I picture that `GetById` is just a static factory method on the `MyObject` model which calls any dependencies it needs, such as a DAL repository (maybe supplied by some other means than parameters to the method, but hopefully not internally instantiated), and returns an instance of `MyObject`, which seems fine. I use that same pattern myself very often, occasionally experimenting with how I name the methods to make the whole thing more fluid. |
58,006,435 | So this is a bit of a strange issue that I can't seem to find reference to anywhere online. Was hoping someone here could shed some light on the following, as well as a potential fix -
I have and Angular CLI application which is compliant with Google's PWA requirements. Everything works just as expected, however some of the images are not being cached by the service worker.
Here is my ngsw-config.json -
```
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js",
"../assets/signalR/appHub.js",
"../admin/images/**",
"../manifest/manifest.json"
],
"urls": [
"/api/WhoAmI",
"/api/GetApps"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)",
"../admin/images/**"
]
}
}
]
}
```
Inside the admin/images folder, there are some background images, logos, spinners, icon etc.
However, when I run 'ng-build --prod', the only images that get cached are those which are references in CSS (background-image). Any which are placed onto the page itself are ignored.
This results in an offline page with no logos or icons.
Looking at the generated 'dist' folder, the 'working' image files are copied and given a random suffix.
[](https://i.stack.imgur.com/5Ryp2.png)
Inside the generated ngsw.json file, these are the only images referenced, no mention of the missing logos etc.
```
{
"configVersion": 1,
"timestamp": 1568879436433,
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"updateMode": "prefetch",
"urls": [
"/favicon.ico",
"/index.html",
"/main-es2015.b125878abf05e7d82b63.js",
"/main-es5.6e9e620d3fbd96496f98.js",
"/polyfills-es2015.4d31cca2afc45cfd85b5.js",
"/polyfills-es5.2219c87348e60efc0076.js",
"/runtime-es2015.703a23e48ad83c851e49.js",
"/runtime-es5.465c2333d355155ec5f3.js",
"/scripts.f616c8c0191ed4649bce.js",
"/styles.a4be089a70c69f63e366.css"
],
"patterns": [
"\\/api\\/WhoAmI",
"\\/api\\/GetApps"
]
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"urls": [
"/assets/signalR/appHub.js",
"/bgrounds-geometric-black.8d983f6875c006eda992.png",
"/bgrounds-geometric-red.1484266e3058319624bd.png",
"/block-spinner-dark.20f05a2ddef506c61f4d.gif",
...
}
...
}
```
Is anyone able to demystify this at all?
Apologies for the long question, but if you've got this far, thank you :)
Any help is appreciated! | 2019/09/19 | [
"https://Stackoverflow.com/questions/58006435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4453661/"
] | Through messing around with a few different things, I found a workaround for this - doesn't explain why it was not working initially though.
It seems that renaming my folder from `admin/images` to `assets/images` and updating the relevant `resource > files paths` got it working.
If anyone stumbled upon some more insight into the cause of this, please let me know.
Thanks,
Rob | I added below line to ngsw-config.json
```
"/runtime*",
"/main*",
"/style*",
"/polyfill*"
```
It looks like this afterwards
```
{
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/runtime*",
"/main*",
"/style*",
"/polyfill*",
"/favicon.ico",
"/index.html",
"/css",
"/js"
]
}
}, {
```
Then it worked. |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | Here's a quick/simple example of what you're asking for:
**EDIT** - I've update the code for reuse and include the day 0 padding change.
```
var d = new Date();
console.log(formatDate(d));
function formatDate(d){
var months = ["Januaray", "February", "March"]; //you would need to include the rest
var days = ["Sunday", "Monday", "Tuesday"];//you would need to include the rest
return days[d.getDay()] + ", " + months[d.getMonth()] + " " + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + ", " + d.getFullYear();
}
```
Output for today: `Tuesday, Januaray 08, 2013`
[**EXAMPLE**](http://jsbin.com/atuves/7/edit) | Simply use [**DateJS**](http://www.datejs.com/) not to reinvent the wheel.
You may read the API documentation here:
* <http://code.google.com/p/datejs/wiki/APIDocumentation> |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | The simplest answer is to use:
```
date.toLocaleDateString()
```
But, it will use the locale defined by the user's system. The American/English locale fitting your desired output. (I'm not sure about other locales and how they format dates).
So, if you want the date string to **always** be in that format, this will not be the best answer for you. But, if you want the date to match the user's locale, this answer is the simplest and most correct. :)
<http://jsfiddle.net/SyjpS/>
```
var date = new Date();
console.log(date.toLocaleDateString()); // Tuesday, January 08, 2013 (on my machine)
```
**EDIT** — If you're asking how to change the calendar so that today is Thursday instead of Tuesday, you may need to talk to Caesar about adjusting the calendar realignment. For this, you'll need a time machine. I suggest that you seek out the Doctor, but he may not be willing to change history willy nilly. | Simply use [**DateJS**](http://www.datejs.com/) not to reinvent the wheel.
You may read the API documentation here:
* <http://code.google.com/p/datejs/wiki/APIDocumentation> |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | Simply use [**DateJS**](http://www.datejs.com/) not to reinvent the wheel.
You may read the API documentation here:
* <http://code.google.com/p/datejs/wiki/APIDocumentation> | The date methods allow you to retrieve all of the different parts of the date and time as numerical values. In the case of the month of the year and the day of the week, the number that is provided is one less than you would normally expect. The reason for this is that the most common use for these values is to use it to look up the name of the month or day from an array and as arrays in JavaScript are numbered from zero, providing the numbers like that reduces the amount of code needed to do the name lookups.
We can go one better than just doing this lookup using the retrieved values though. What we can do is to add extra methods to the Date object to allow us to retrieve the month and day names whenever we want the exact same way that we retrieve any of the other information about the date.
The probable reason why the following methods are not built into the JavaScript language itself is that they are language dependent and need to have different values substituted into the code depending on the language that you want to display the month and day in. For the purpose of showing you how to code this I am going to use the Emglish names for the months and days. If you want to display dates in a different language you will need to substitute the names from that language for their English equivalents.
What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name. What we are actually doing is building the required array lookups into the new methods so that we can automatically get the correct names for any of our date objects simply by calling the appropriate method.
We don't neeed all that much code to do this. All you need to do to add the getMonthName() and getDayName() methods to all of the date objects that you use is to add the following short piece of code to the very top of the javaScript code attached to the head of your page. Any subsequent processing of date objects will then be able to use these methods.
```
Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
return d[this.getDay()];
}
```
So now with that in place we can display today's date on the page using those new methods in addition to the existing ones. For example we might use the following to get the full date and display it using an alert:
```
var today = new Date;
alert((today.getDayName() + ', ' + today.getDate() + ' ' + today.getMonthName() + ', ' + today.getFullYear());
```
Alternatively, we can just retrieve the current month June and day of the week Sunday and use them however we want just the same as for any of the other parts of the date.
```
function disp() {
var today = new Date;
document.getElementById('mth').innerHTML = today.getMonthName();
document.getElementById('dow').innerHTML = today.getDayName();
}
``` |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | Here's a quick/simple example of what you're asking for:
**EDIT** - I've update the code for reuse and include the day 0 padding change.
```
var d = new Date();
console.log(formatDate(d));
function formatDate(d){
var months = ["Januaray", "February", "March"]; //you would need to include the rest
var days = ["Sunday", "Monday", "Tuesday"];//you would need to include the rest
return days[d.getDay()] + ", " + months[d.getMonth()] + " " + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + ", " + d.getFullYear();
}
```
Output for today: `Tuesday, Januaray 08, 2013`
[**EXAMPLE**](http://jsbin.com/atuves/7/edit) | The simplest answer is to use:
```
date.toLocaleDateString()
```
But, it will use the locale defined by the user's system. The American/English locale fitting your desired output. (I'm not sure about other locales and how they format dates).
So, if you want the date string to **always** be in that format, this will not be the best answer for you. But, if you want the date to match the user's locale, this answer is the simplest and most correct. :)
<http://jsfiddle.net/SyjpS/>
```
var date = new Date();
console.log(date.toLocaleDateString()); // Tuesday, January 08, 2013 (on my machine)
```
**EDIT** — If you're asking how to change the calendar so that today is Thursday instead of Tuesday, you may need to talk to Caesar about adjusting the calendar realignment. For this, you'll need a time machine. I suggest that you seek out the Doctor, but he may not be willing to change history willy nilly. |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | Here's a quick/simple example of what you're asking for:
**EDIT** - I've update the code for reuse and include the day 0 padding change.
```
var d = new Date();
console.log(formatDate(d));
function formatDate(d){
var months = ["Januaray", "February", "March"]; //you would need to include the rest
var days = ["Sunday", "Monday", "Tuesday"];//you would need to include the rest
return days[d.getDay()] + ", " + months[d.getMonth()] + " " + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + ", " + d.getFullYear();
}
```
Output for today: `Tuesday, Januaray 08, 2013`
[**EXAMPLE**](http://jsbin.com/atuves/7/edit) | The date methods allow you to retrieve all of the different parts of the date and time as numerical values. In the case of the month of the year and the day of the week, the number that is provided is one less than you would normally expect. The reason for this is that the most common use for these values is to use it to look up the name of the month or day from an array and as arrays in JavaScript are numbered from zero, providing the numbers like that reduces the amount of code needed to do the name lookups.
We can go one better than just doing this lookup using the retrieved values though. What we can do is to add extra methods to the Date object to allow us to retrieve the month and day names whenever we want the exact same way that we retrieve any of the other information about the date.
The probable reason why the following methods are not built into the JavaScript language itself is that they are language dependent and need to have different values substituted into the code depending on the language that you want to display the month and day in. For the purpose of showing you how to code this I am going to use the Emglish names for the months and days. If you want to display dates in a different language you will need to substitute the names from that language for their English equivalents.
What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name. What we are actually doing is building the required array lookups into the new methods so that we can automatically get the correct names for any of our date objects simply by calling the appropriate method.
We don't neeed all that much code to do this. All you need to do to add the getMonthName() and getDayName() methods to all of the date objects that you use is to add the following short piece of code to the very top of the javaScript code attached to the head of your page. Any subsequent processing of date objects will then be able to use these methods.
```
Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
return d[this.getDay()];
}
```
So now with that in place we can display today's date on the page using those new methods in addition to the existing ones. For example we might use the following to get the full date and display it using an alert:
```
var today = new Date;
alert((today.getDayName() + ', ' + today.getDate() + ' ' + today.getMonthName() + ', ' + today.getFullYear());
```
Alternatively, we can just retrieve the current month June and day of the week Sunday and use them however we want just the same as for any of the other parts of the date.
```
function disp() {
var today = new Date;
document.getElementById('mth').innerHTML = today.getMonthName();
document.getElementById('dow').innerHTML = today.getDayName();
}
``` |
14,222,817 | how to display the date in this below format using jQuery.
```
Thursday, January 08, 2013
```
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too. | 2013/01/08 | [
"https://Stackoverflow.com/questions/14222817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287211/"
] | The simplest answer is to use:
```
date.toLocaleDateString()
```
But, it will use the locale defined by the user's system. The American/English locale fitting your desired output. (I'm not sure about other locales and how they format dates).
So, if you want the date string to **always** be in that format, this will not be the best answer for you. But, if you want the date to match the user's locale, this answer is the simplest and most correct. :)
<http://jsfiddle.net/SyjpS/>
```
var date = new Date();
console.log(date.toLocaleDateString()); // Tuesday, January 08, 2013 (on my machine)
```
**EDIT** — If you're asking how to change the calendar so that today is Thursday instead of Tuesday, you may need to talk to Caesar about adjusting the calendar realignment. For this, you'll need a time machine. I suggest that you seek out the Doctor, but he may not be willing to change history willy nilly. | The date methods allow you to retrieve all of the different parts of the date and time as numerical values. In the case of the month of the year and the day of the week, the number that is provided is one less than you would normally expect. The reason for this is that the most common use for these values is to use it to look up the name of the month or day from an array and as arrays in JavaScript are numbered from zero, providing the numbers like that reduces the amount of code needed to do the name lookups.
We can go one better than just doing this lookup using the retrieved values though. What we can do is to add extra methods to the Date object to allow us to retrieve the month and day names whenever we want the exact same way that we retrieve any of the other information about the date.
The probable reason why the following methods are not built into the JavaScript language itself is that they are language dependent and need to have different values substituted into the code depending on the language that you want to display the month and day in. For the purpose of showing you how to code this I am going to use the Emglish names for the months and days. If you want to display dates in a different language you will need to substitute the names from that language for their English equivalents.
What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name. What we are actually doing is building the required array lookups into the new methods so that we can automatically get the correct names for any of our date objects simply by calling the appropriate method.
We don't neeed all that much code to do this. All you need to do to add the getMonthName() and getDayName() methods to all of the date objects that you use is to add the following short piece of code to the very top of the javaScript code attached to the head of your page. Any subsequent processing of date objects will then be able to use these methods.
```
Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
return d[this.getDay()];
}
```
So now with that in place we can display today's date on the page using those new methods in addition to the existing ones. For example we might use the following to get the full date and display it using an alert:
```
var today = new Date;
alert((today.getDayName() + ', ' + today.getDate() + ' ' + today.getMonthName() + ', ' + today.getFullYear());
```
Alternatively, we can just retrieve the current month June and day of the week Sunday and use them however we want just the same as for any of the other parts of the date.
```
function disp() {
var today = new Date;
document.getElementById('mth').innerHTML = today.getMonthName();
document.getElementById('dow').innerHTML = today.getDayName();
}
``` |
3,859 | Esiste una forma di voyeurismo alla rovescia in cui si prova piacere a mostrare nudo il proprio partner. In inglese prende nome da [re Candaule di Lidia](http://www.treccani.it/enciclopedia/candaule/) ed è detta *candaulism*. Per l'italiano non trovo la forma corrispondente su alcun dizionario (né inglese-italiano né monolingue), mentre in rete trovo entrambe le forme “candaulismo” e “candaulesimo” (la seconda soprattutto sulla [Wikipedia italiana](https://it.wikipedia.org/wiki/Candaulesimo), di cui non mi fido in generale e tanto meno per questa voce, in cui sono più i “tag” di avvertimento del testo).
Conoscete qualche fonte affidabile (magari un dizionario medico o un sito attendibile, e non uno generico di consigli psicologici) su quale forma sia più corretta in italiano?
---
Per chiarire meglio: non mi interessano citazioni dalla wikipedia o da suoi cloni, non mi interessano citazioni da siti generici di psicologia (tutte queste cose le ho già trovate anch'io); conosco le differenze d'uso tra “-ismo” ed “-esimo”; non mi interessano più di tanto opinioni personali se non nei commenti. Vorrei solo sapere se in testi medici, articoli scientifici, saggi pubblicati, documenti ufficiali italiani è comparso finora il termine di cui parliamo. | 2015/01/13 | [
"https://italian.stackexchange.com/questions/3859",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/37/"
] | [Fondamenti di sessuologia](https://books.google.se/books?id=Vys0RazGiJsC&pg=PA338&dq=Candaulismo&hl=en&sa=X&ei=bpHQVLLxGYToaPDNgsAJ&ved=0CDEQ6AEwAw#v=onepage&q=Candaulismo&f=false) di Salvatore Capodieci, Leonardo Boccadoro (Libreriauniversitaria ed., 2012), p.338:
>
> Triolismo, o triolagnia, o candaulismo, parafilia consistente nel provare piacere a osservare il/la propria partner impegnato/a in attività sessuali con un'altra persona
>
>
>
Si veda anche [Trattato moderno di psicopatologia della sessualità](https://books.google.se/books?id=TIPt9oWsrtkC&lpg=PA104&ots=bqXaRUvBG-&dq=triolagnia&pg=PA104#v=onepage&q=triolismo&f=falsesa=X&ei=15LQVJ7eFIXkaNy8gOAJ&ved=0CDgQ6AEwAw#v=onepage&q=triolismo&f=false) di Fernando Liggio (Libreriauniversitaria ed., 2010), p. 104. | Cuckoldismo sembra essere un alternativa a candaulesimo/candaulismo. In effetti questi termini sembrano non essere ancora entrati in dizionari di medicina o psicologia.
[Candaulesimo](http://infatti-italiano.it/candaulesimo):
>
> * Il termine candaulesimo indica la pratica umana di tipo sessuale con la quale il soggetto prova soddisfacimento nell'osservare il partner durante l'atto sessuale con un'altra persona (Borneman, 1988). Il nome deriva da una vicenda narrata da Erodoto nelle sue Storie a proposito di Candaule, re di Lidia dell'VIII secolo a.C., e di sua moglie.
> * Nel linguaggio contemporaneo è frequente usare come sinonimo **l'anglicismo "cuckoldismo" dalla parola inglese "cuckold".**
>
>
>
[Cuckoldismo o candaulesimo](http://www.nienteansia.it/articoli-di-psicologia/atri-argomenti/calofilia-calofobia-oggetti-di-desiderio-oggetti-di-rappresentanza-%E2%80%93-candaulesimo-la-giustizia-di-afrodite/613/):
>
> * Esporre le nudità comporta un’occasione per rivelare ciò che abitualmente potrebbe essere solo intravisto o immaginato. Svelare una qualche parte del corpo, che siano le gambe, le spalle, il seno, equivale a puntare su quel fascino parziale, reso feticcio di sé, in base all’idea che ci si è fatti della propria capacità di attirare attenzione.
> * Chi espone con disinvoltura, in toto o in parte, questi aspetti non trascurabili del proprio essere “oggetto”, ricerca gli sguardi attenti, purché siano discreti, onde viverli con un buon dosaggio di gratificazione.
> * Una soddisfazione questa condivisibile dal partner che ha puntato sul valore di rappresentanza dell’oggetto. **Il “cuckoldismo” (da cuculo), o meglio candaulesimo (commistione di voyeurismo ed esibizionismo indiretto per identificazione con l’anima gemella)**, in fondo, verrebbe esplicitato su questo tavolo da gioco. La rappresentanza predomina sul desiderio e l’oggetto viene spostato sul medesimo desiderio di chi viene sedotto (Ernest Borneman: “Lexicon der Liebe”,1984).
>
>
> |
3,859 | Esiste una forma di voyeurismo alla rovescia in cui si prova piacere a mostrare nudo il proprio partner. In inglese prende nome da [re Candaule di Lidia](http://www.treccani.it/enciclopedia/candaule/) ed è detta *candaulism*. Per l'italiano non trovo la forma corrispondente su alcun dizionario (né inglese-italiano né monolingue), mentre in rete trovo entrambe le forme “candaulismo” e “candaulesimo” (la seconda soprattutto sulla [Wikipedia italiana](https://it.wikipedia.org/wiki/Candaulesimo), di cui non mi fido in generale e tanto meno per questa voce, in cui sono più i “tag” di avvertimento del testo).
Conoscete qualche fonte affidabile (magari un dizionario medico o un sito attendibile, e non uno generico di consigli psicologici) su quale forma sia più corretta in italiano?
---
Per chiarire meglio: non mi interessano citazioni dalla wikipedia o da suoi cloni, non mi interessano citazioni da siti generici di psicologia (tutte queste cose le ho già trovate anch'io); conosco le differenze d'uso tra “-ismo” ed “-esimo”; non mi interessano più di tanto opinioni personali se non nei commenti. Vorrei solo sapere se in testi medici, articoli scientifici, saggi pubblicati, documenti ufficiali italiani è comparso finora il termine di cui parliamo. | 2015/01/13 | [
"https://italian.stackexchange.com/questions/3859",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/37/"
] | [Fondamenti di sessuologia](https://books.google.se/books?id=Vys0RazGiJsC&pg=PA338&dq=Candaulismo&hl=en&sa=X&ei=bpHQVLLxGYToaPDNgsAJ&ved=0CDEQ6AEwAw#v=onepage&q=Candaulismo&f=false) di Salvatore Capodieci, Leonardo Boccadoro (Libreriauniversitaria ed., 2012), p.338:
>
> Triolismo, o triolagnia, o candaulismo, parafilia consistente nel provare piacere a osservare il/la propria partner impegnato/a in attività sessuali con un'altra persona
>
>
>
Si veda anche [Trattato moderno di psicopatologia della sessualità](https://books.google.se/books?id=TIPt9oWsrtkC&lpg=PA104&ots=bqXaRUvBG-&dq=triolagnia&pg=PA104#v=onepage&q=triolismo&f=falsesa=X&ei=15LQVJ7eFIXkaNy8gOAJ&ved=0CDgQ6AEwAw#v=onepage&q=triolismo&f=false) di Fernando Liggio (Libreriauniversitaria ed., 2010), p. 104. | *-ismo* e *-esimo* sono solo dei suffissi che hanno lo stesso identico scopo. Quello più antico e usato nella formazione di nuove parole è *-ismo*. Poche sono le eccezioni che usano *-esimo* (cristian-esimo, feudal-esimo).
Per cui, senza sapere cos'abbiano scelto medici-psicologi propenderei per la forma in *-ismo*.
Sembra esserci una sorta di regola per cui le parole che terminano in *-ano* e sono nei settori: filosofico, letterario, scientifico, artistico; preferiscono *-esimo*.
Una spiegazione approfondita sui suffissi la trovi [qui](https://books.google.fr/books?id=ITchAAAAQBAJ&pg=PA256&lpg=PA256&dq=suffisso%20ismo%20esimo&source=bl&ots=k0Md_iu2kI&sig=BL61SbxruNBdqiHfkwI13TgRT-o&hl=it&sa=X&ei=uby1VNWMIoTLaIKUgeAC&ved=0CFMQ6AEwCA#v=onepage&q=suffisso%20ismo%20esimo&f=false). |
3,859 | Esiste una forma di voyeurismo alla rovescia in cui si prova piacere a mostrare nudo il proprio partner. In inglese prende nome da [re Candaule di Lidia](http://www.treccani.it/enciclopedia/candaule/) ed è detta *candaulism*. Per l'italiano non trovo la forma corrispondente su alcun dizionario (né inglese-italiano né monolingue), mentre in rete trovo entrambe le forme “candaulismo” e “candaulesimo” (la seconda soprattutto sulla [Wikipedia italiana](https://it.wikipedia.org/wiki/Candaulesimo), di cui non mi fido in generale e tanto meno per questa voce, in cui sono più i “tag” di avvertimento del testo).
Conoscete qualche fonte affidabile (magari un dizionario medico o un sito attendibile, e non uno generico di consigli psicologici) su quale forma sia più corretta in italiano?
---
Per chiarire meglio: non mi interessano citazioni dalla wikipedia o da suoi cloni, non mi interessano citazioni da siti generici di psicologia (tutte queste cose le ho già trovate anch'io); conosco le differenze d'uso tra “-ismo” ed “-esimo”; non mi interessano più di tanto opinioni personali se non nei commenti. Vorrei solo sapere se in testi medici, articoli scientifici, saggi pubblicati, documenti ufficiali italiani è comparso finora il termine di cui parliamo. | 2015/01/13 | [
"https://italian.stackexchange.com/questions/3859",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/37/"
] | [Fondamenti di sessuologia](https://books.google.se/books?id=Vys0RazGiJsC&pg=PA338&dq=Candaulismo&hl=en&sa=X&ei=bpHQVLLxGYToaPDNgsAJ&ved=0CDEQ6AEwAw#v=onepage&q=Candaulismo&f=false) di Salvatore Capodieci, Leonardo Boccadoro (Libreriauniversitaria ed., 2012), p.338:
>
> Triolismo, o triolagnia, o candaulismo, parafilia consistente nel provare piacere a osservare il/la propria partner impegnato/a in attività sessuali con un'altra persona
>
>
>
Si veda anche [Trattato moderno di psicopatologia della sessualità](https://books.google.se/books?id=TIPt9oWsrtkC&lpg=PA104&ots=bqXaRUvBG-&dq=triolagnia&pg=PA104#v=onepage&q=triolismo&f=falsesa=X&ei=15LQVJ7eFIXkaNy8gOAJ&ved=0CDgQ6AEwAw#v=onepage&q=triolismo&f=false) di Fernando Liggio (Libreriauniversitaria ed., 2010), p. 104. | DaG, la tua domanda era "Vorrei solo sapere se in testi medici, articoli scientifici, saggi pubblicati, documenti ufficiali italiani è comparso finora il termine di cui parliamo".
Posso, invece, rispondere solo dal punto di vista di chi appartenga a comunità in cui ciò si pratica. In nessuna discussione scritta ho visto adoperare né il termine "candaulismo" né il termine "Triolagnia". Tutti, all'interno di queste comunità, utilizzano il termine inglese "cuckoldry" per indicare generalmente la pratica e "cuckold" o "cuckquean" per indicare rispettivamente l'uomo o la donna che induca volontariamente il proprio partner a vivere esperienze sessuali con altre persone |
104,982 | I am planning on building a suit of armor and [animating](http://www.d20pfsrd.com/bestiary/monster-listings/constructs/animated-object/#gargantuan) it via [craft construct](http://www.d20pfsrd.com/feats/item-creation-feats/craft-construct-item-creation) and I was looking for ways to make it tougher as I plan on wearing it via the [Construct Armor modification](http://www.d20pfsrd.com/magic/building-and-modifying-constructs/).
I ran across a post that mentioned [Fortifying stones](http://www.d20pfsrd.com/magic-items/wondrous-items/wondrous-items/r-z/stone-fortifying) and reading their wording I realized it suggests that you can equip more than one of these at a time (See quote below), is there any limit to this? It seems rather cheap and I could put like 5 of these on the suit of armor and have 100 extra HP and a hardness of 25.
While I don't want to go that far I'm curious if there is any rule against this or at least a limit somewhere as I could not find anything on it.
>
> ...Any effect that breaks or destroys the protected object also destroys **any attached fortifying stones**.
>
>
> | 2017/08/09 | [
"https://rpg.stackexchange.com/questions/104982",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/8933/"
] | You cannot apply fortifying stones to a creature.
-------------------------------------------------
While it is true that there are creatures with hardness (see [animated objects](http://www.d20pfsrd.com/bestiary/monster-listings/constructs/animated-object/)), those are no longer objects but [construct creatures](http://www.d20pfsrd.com/bestiary/monster-listings/constructs/). The effect of the fortifying stone clearly applies to objects, not creatures.
So, while your suit of armor could possibly have more than one stone, the benefits would only apply while the suit of armor is an object. This benefit should disappear once it becomes a creature.
For instance, while a suit of plate mail should have at least 10 hardness due to the [metal's inherent hardness](http://www.d20pfsrd.com/equipment/damaging-objects/), a [medium-sized animated object](http://www.d20pfsrd.com/bestiary/monster-listings/constructs/animated-object/animated-object-medium/) only has hardness 5. While you could use the construction points to add the *Metal* property and increase it's hardness to 10, it has little effect on the creature's hit points. Armor has AC \* 5 hit points, the creature is fixed at 36 hit points.
Considering how detailed the rules for creating animated objects are, I would expect at least a mention of using the fortifying stones to build constructs. Like happens to the [Irespan Basalt](https://pathfinderwiki.com/wiki/Irespan) shown on [Magnimar, City of Monuments](http://paizo.com/products/btpy8slp?Pathfinder-Campaign-Setting-Magnimar-City-of-Monuments), which has the following properties when used to create constructs:
>
> **Physical Properties**: Irespan basalt is **as hard as iron**, while retaining its other stony features for carving and building. It has hardness 10 and typically fetches a price of about 5 sp per pound. However, since few buyers are interested in stones of less than 1,ooo pounds, the Irespan bas alt trade is relatively limited to specialists capable of harvesting and transporting such heavy blocks.
>
>
> **Building Constructs**: When a construct's materials consist entirely of Irespan stone, its Craft DC increases by +5, but the required Caster Level decreases by 1. In addition, stone constructs crafted from Irespan stone gain a +2 bonus to Strength and gain twice as many bonus hit points as normal from the construct type.
>
>
>
We might see more on this subject on the upcoming [Construct Builder's Guidebook](http://paizo.com/products/btpy9sk8?Pathfinder-Campaign-Setting-Construct-Builders-Guidebook).
As for stacking fortifying stones, you could possibly add several stones to a single object, and a lot community members seem to allow the effects to stack. The only thing that puts me off is the text about working like temporary hit points, as we know that [temporary hit points from the same source do not stack](http://paizo.com/paizo/faq/v5748nruor1fm#v5748eaic9r43) (like multiple castings of [Aid](http://paizo.com/pathfinderRPG/prd/coreRulebook/spells/aid.html)). But, considering the cost of each stone (1,000 gp), I personally would allow them to stack on the same object. | Core page 208: "Bonuses without a type always stack, unless they are from the same source." Here is an obvious example of untyped bonuses from the same source. Thus, they will not stack.
Additionally, there is no particular reason to believe that the Fortifying Stones effect would apply directly to construct stats. They could be used to improve the stats of the base material used prior to conversion, but unless there is some RAW way for the one to affect the other, that won't matter much. |
153,350 | I'm writing a report on the mathematics of GPS, but I'm wondering what methods the GPS actually uses. What I've done is set up the four sphere equations and solve them using the Newton-Raphson method for four variables (using the Jacobian matrix of partial derivatives). But is this what a GPS receiver actually does, with the an initial guess and iterations? Because I saw that on several websites, but I've also read about other methods such as a least squares solution. Or is this something that depends on the receiver? | 2015/07/06 | [
"https://gis.stackexchange.com/questions/153350",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/54773/"
] | After some more research, I found the solution [here](http://osgeo-org.1560.x6.nabble.com/Feature-style-doesn-t-support-contexts-td3896881.html).
The `feature.style` property only accepts the symbolizer as hash style. So, we must use the `styleMap` to create a symbolizer for the current feature
```
var highlight = function(feature) {
var style = $.extend({}, styleMap.createSymbolizer(feature), {
strokeWidth: 5
});
feature.style = style;
vector.drawFeature(feature);
};
```
I created a [new CodePen](http://codepen.io/joaorodr84/pen/zGWreG), where the highlighting works correctly. :) | One other option would be to define a new Style and assign the stroke width...
but the solution you found looks smarter ;)
```
var highlight = function(feature) {
feature.style = new OpenLayers.Style();
feature.style.strokeWidth = 3;
feature.style.fillColor=context.getFillColor(feature);
vector.drawFeature(feature);
};
```
working example: <http://codepen.io/anon/pen/doeMEm> |
40,970,137 | In this snippet it will generate mixed words and numbers randomly but i'm wondering why it always return zero in second character? if you click refresh button it always return 0 in second position. any idea?
```js
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
var myLength = 4;
function Captcha() {
$('#Captcha').html("");
for (var i = 0; i < myLength; i++) {
var word = words[Math.floor(Math.random() * words.length)];
$('#Captcha').append(word + i++);
}
}
Captcha();
$('#reCaptchaRefresh').click(function(){
Captcha();
});
});
```
```css
#Captcha {
border: 1px solid black;
padding: 10px;
float: left;
}
#reCaptchaRefresh {
clear: both;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha" ></div>
<div id="reCaptchaRefresh">
Refresh
</div>
``` | 2016/12/05 | [
"https://Stackoverflow.com/questions/40970137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540183/"
] | `i++` will cause the problem . since you are appending `i++` at the end of every character . and loop will also run only `2 times` .
```js
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
var myLength = 4;
function Captcha() {
$('#Captcha').html("");
for (var i = 0; i < myLength; i++) {
var word = words[Math.floor(Math.random() * words.length)];
$('#Captcha').append(word);
// ^^^^^ edited here
}
}
Captcha();
$('#reCaptchaRefresh').click(function(){
Captcha();
});
});
```
```css
#Captcha {
border: 1px solid black;
padding: 10px;
float: left;
}
#reCaptchaRefresh {
clear: both;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha" ></div>
<div id="reCaptchaRefresh">
Refresh
</div>
``` | The reason is because you're appending `i` to the output string. You're also incrementing `i` twice in each iteration. Try this:
```js
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz"
var myLength = 4;
function Captcha() {
$('#Captcha').empty();
for (var i = 0; i < myLength; i++) {
var word = words[Math.floor(Math.random() * words.length)];
$('#Captcha').append(word); // Note the removal of the concatenation and '++' here
}
}
$('#reCaptchaRefresh').click(Captcha).trigger('click');
});
```
```css
#Captcha {
border: 1px solid black;
padding: 10px;
float: left;
}
#reCaptchaRefresh {
clear: both;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Captcha"></div>
<div id="reCaptchaRefresh">
Refresh
</div>
``` |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | Primitives are passed by value, and Objects are passed by "copy of a reference".
Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the *contents* of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:
```
function replace(ref) {
ref = {}; // this code does _not_ affect the object passed
}
function update(ref) {
ref.key = 'newvalue'; // this code _does_ affect the _contents_ of the object
}
var a = { key: 'value' };
replace(a); // a still has its original value - it's unmodfied
update(a); // the _contents_ of 'a' are changed
``` | In the interest of creating a simple example that uses const...
```
const myRef = { foo: 'bar' };
const myVal = true;
function passes(r, v) {
r.foo = 'baz';
v = false;
}
passes(myRef, myVal);
console.log(myRef, myVal); // Object {foo: "baz"} true
``` |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | JavaScript is pass by value.
For primitives, primitive's value is passed. For Objects, Object's reference "value" is passed.
Example with Object:
```
var f1 = function(inputObject){
inputObject.a = 2;
}
var f2 = function(){
var inputObject = {"a": 1};
f1(inputObject);
console.log(inputObject.a);
}
```
Calling f2 results in printing out "a" value as 2 instead of 1, as the reference is passed and the "a" value in reference is updated.
Example with primitive:
```
var f1 = function(a){
a = 2;
}
var f2 = function(){
var a = 1;
f1(a);
console.log(a);
}
```
Calling f2 results in printing out "a" value as 1. | In practical terms, [Alnitak is correct](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference/13104500#13104500) and makes it easy to understand, but ultimately in JavaScript, everything is passed by value.
What is the "value" of an object? It is the object reference.
When you pass in an object, you get a copy of this value (hence the 'copy of a reference' that Alnitak described). If you change this value, you do not change the original object; you are changing your copy of that reference. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | Think of it like this:
Whenever you create an *object* in ECMAscript, this object is formed in a mystique *ECMAscript universal place* where no man will ever be able to get. All you get back is a *reference* to that object in this mystique place.
```
var obj = { };
```
Even `obj` is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this *reference* around. Effectively, any piece of code which accesses *obj* will modify the *object* which is far, far away. | Function arguments are passed either by-value or by-sharing, but never **ever** by reference in JavaScript!
Call-by-Value
-------------
Primitive types are passed by-value:
```js
var num = 123, str = "foo";
function f(num, str) {
num += 1;
str += "bar";
console.log("inside of f:", num, str);
}
f(num, str);
console.log("outside of f:", num, str);
```
**Reassignments** inside a function scope are not visible in the surrounding scope.
This also applies to `String`s, which are a composite data type and yet immutable:
```js
var str = "foo";
function f(str) {
str[0] = "b"; // doesn't work, because strings are immutable
console.log("inside of f:", str);
}
f(str);
console.log("outside of f:", str);
```
Call-by-Sharing
---------------
Objects, that is to say all types that are not primitives, are passed by-sharing. A variable that holds a reference to an object actually holds merely a copy of this reference. If JavaScript would pursue a *call-by-reference* evaluation strategy, the variable would hold the original reference. This is the crucial difference between by-sharing and by-reference.
What are the practical consequences of this distinction?
```js
var o = {x: "foo"}, p = {y: 123};
function f(o, p) {
o.x = "bar"; // Mutation
p = {x: 456}; // Reassignment
console.log("o inside of f:", o);
console.log("p inside of f:", p);
}
f(o, p);
console.log("o outside of f:", o);
console.log("p outside of f:", p);
```
**Mutating** means to modify certain properties of an existing `Object`. The reference copy that a variable is bound to and that refers to this object remains the same. Mutations are thus visible in the caller's scope.
**Reassigning** means to replace the reference copy bound to a variable. Since it is only a copy, other variables holding a copy of the same reference remain unaffected. Reassignments are thus not visible in the caller's scope like they would be with a *call-by-reference* evaluation strategy.
Further information on [evaluation strategies](http://dmitrysoshnikov.com/ecmascript/chapter-8-evaluation-strategy/#call-by-sharing) in ECMAScript. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | My two cents.... It's irrelevant whether JavaScript passes parameters by reference or value. What really matters is assignment vs. mutation.
I wrote a longer, [more detailed explanation in this link](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language/25117245#25117245).
When you pass anything (whether that be an object or a primitive), all JavaScript does is assign a new variable while inside the function... just like using the equal sign (`=`).
How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign... Take these simple examples.
```js
var myString = 'Test string 1';
// Assignment - A link to the same place as myString
var sameString = myString;
// If I change sameString, it will not modify myString,
// it just re-assigns it to a whole new string
sameString = 'New string';
console.log(myString); // Logs 'Test string 1';
console.log(sameString); // Logs 'New string';
```
If I were to pass `myString` as a parameter to a function, it behaves as if I simply assigned it to a new variable. Now, let's do the same thing, but with a function instead of a simple assignment
```js
function myFunc(sameString) {
// Reassignment... Again, it will not modify myString
sameString = 'New string';
}
var myString = 'Test string 1';
// This behaves the same as if we said sameString = myString
myFunc(myString);
console.log(myString); // Again, logs 'Test string 1';
```
The only reason that you can modify objects when you pass them to a function is because you are not reassigning... Instead, objects can be changed or mutated.... Again, it works the same way.
```
var myObject = { name: 'Joe'; }
// Assignment - We simply link to the same object
var sameObject = myObject;
// This time, we can mutate it. So a change to myObject affects sameObject and visa versa
myObject.name = 'Jack';
console.log(sameObject.name); // Logs 'Jack'
sameObject.name = 'Jill';
console.log(myObject.name); // Logs 'Jill'
// If we re-assign it, the link is lost
sameObject = { name: 'Howard' };
console.log(myObject.name); // Logs 'Jill'
```
If I were to pass `myObject` as a parameter to a function, it behaves as if I simply assigned it to a new variable. Again, the same thing with the exact same behavior but with a function.
```js
function myFunc(sameObject) {
// We mutate the object, so the myObject gets the change too... just like before.
sameObject.name = 'Jill';
// But, if we re-assign it, the link is lost
sameObject = {
name: 'Howard'
};
}
var myObject = {
name: 'Joe'
};
// This behaves the same as if we said sameObject = myObject;
myFunc(myObject);
console.log(myObject.name); // Logs 'Jill'
```
Every time you pass a variable to a function, you are "assigning" to whatever the name of the parameter is, just like if you used the equal `=` sign.
Always remember that the equals sign `=` means assignment.
And passing a parameter to a function also means assignment.
They are the same and the two variables are connected in exactly the same way.
The only time that modifying a variable affects a different variable is when the underlying object is mutated.
There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable. | As with C, ultimately, everything is passed by value. Unlike C, you can't actually back up and pass the location of a variable, because it doesn't have pointers, just references.
And the references it has are all to objects, not variables. There are several ways of achieving the same result, but they have to be done by hand, not just adding a keyword at either the call or declaration site. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | Function arguments are passed either by-value or by-sharing, but never **ever** by reference in JavaScript!
Call-by-Value
-------------
Primitive types are passed by-value:
```js
var num = 123, str = "foo";
function f(num, str) {
num += 1;
str += "bar";
console.log("inside of f:", num, str);
}
f(num, str);
console.log("outside of f:", num, str);
```
**Reassignments** inside a function scope are not visible in the surrounding scope.
This also applies to `String`s, which are a composite data type and yet immutable:
```js
var str = "foo";
function f(str) {
str[0] = "b"; // doesn't work, because strings are immutable
console.log("inside of f:", str);
}
f(str);
console.log("outside of f:", str);
```
Call-by-Sharing
---------------
Objects, that is to say all types that are not primitives, are passed by-sharing. A variable that holds a reference to an object actually holds merely a copy of this reference. If JavaScript would pursue a *call-by-reference* evaluation strategy, the variable would hold the original reference. This is the crucial difference between by-sharing and by-reference.
What are the practical consequences of this distinction?
```js
var o = {x: "foo"}, p = {y: 123};
function f(o, p) {
o.x = "bar"; // Mutation
p = {x: 456}; // Reassignment
console.log("o inside of f:", o);
console.log("p inside of f:", p);
}
f(o, p);
console.log("o outside of f:", o);
console.log("p outside of f:", p);
```
**Mutating** means to modify certain properties of an existing `Object`. The reference copy that a variable is bound to and that refers to this object remains the same. Mutations are thus visible in the caller's scope.
**Reassigning** means to replace the reference copy bound to a variable. Since it is only a copy, other variables holding a copy of the same reference remain unaffected. Reassignments are thus not visible in the caller's scope like they would be with a *call-by-reference* evaluation strategy.
Further information on [evaluation strategies](http://dmitrysoshnikov.com/ecmascript/chapter-8-evaluation-strategy/#call-by-sharing) in ECMAScript. | JavaScript is pass by value.
For primitives, primitive's value is passed. For Objects, Object's reference "value" is passed.
Example with Object:
```
var f1 = function(inputObject){
inputObject.a = 2;
}
var f2 = function(){
var inputObject = {"a": 1};
f1(inputObject);
console.log(inputObject.a);
}
```
Calling f2 results in printing out "a" value as 2 instead of 1, as the reference is passed and the "a" value in reference is updated.
Example with primitive:
```
var f1 = function(a){
a = 2;
}
var f2 = function(){
var a = 1;
f1(a);
console.log(a);
}
```
Calling f2 results in printing out "a" value as 1. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | Think of it like this:
Whenever you create an *object* in ECMAscript, this object is formed in a mystique *ECMAscript universal place* where no man will ever be able to get. All you get back is a *reference* to that object in this mystique place.
```
var obj = { };
```
Even `obj` is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this *reference* around. Effectively, any piece of code which accesses *obj* will modify the *object* which is far, far away. | JavaScript is pass by value.
For primitives, primitive's value is passed. For Objects, Object's reference "value" is passed.
Example with Object:
```
var f1 = function(inputObject){
inputObject.a = 2;
}
var f2 = function(){
var inputObject = {"a": 1};
f1(inputObject);
console.log(inputObject.a);
}
```
Calling f2 results in printing out "a" value as 2 instead of 1, as the reference is passed and the "a" value in reference is updated.
Example with primitive:
```
var f1 = function(a){
a = 2;
}
var f2 = function(){
var a = 1;
f1(a);
console.log(a);
}
```
Calling f2 results in printing out "a" value as 1. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | As with C, ultimately, everything is passed by value. Unlike C, you can't actually back up and pass the location of a variable, because it doesn't have pointers, just references.
And the references it has are all to objects, not variables. There are several ways of achieving the same result, but they have to be done by hand, not just adding a keyword at either the call or declaration site. | Primitives are passed by value. But in case you only need to read the value of a primitve (and value is not known at the time when function is called) you can pass function which retrieves the value at the moment you need it.
```
function test(value) {
console.log('retrieve value');
console.log(value());
}
// call the function like this
var value = 1;
test(() => value);
``` |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | As with C, ultimately, everything is passed by value. Unlike C, you can't actually back up and pass the location of a variable, because it doesn't have pointers, just references.
And the references it has are all to objects, not variables. There are several ways of achieving the same result, but they have to be done by hand, not just adding a keyword at either the call or declaration site. | "Global" JavaScript variables are members of the window object. You could access the reference as a member of the window object.
```
var v = "initialized";
function byref(ref) {
window[ref] = "changed by ref";
}
byref((function(){for(r in window){if(window[r]===v){return(r);}}})());
// It could also be called like... byref('v');
console.log(v); // outputs changed by ref
```
Note, the above example will not work for variables declared within a function. |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | Without purisms, I think that the best way to emulate scalar argument by reference in JavaScript is using object, like previous an answer tells.
However, I do a little bit different:
I've made the object assignment inside function call, so one can see the reference parameters near the function call. It increases the source readability.
In function declaration, I put the properties like a comment, for the very same reason: readability.
```
var r;
funcWithRefScalars(r = {amount:200, message:null} );
console.log(r.amount + " - " + r.message);
function funcWithRefScalars(o) { // o(amount, message)
o.amount *= 1.2;
o.message = "20% increase";
}
```
In the above example, `null` indicates clearly an output reference parameter.
The exit:
```
240 - 20% Increase
```
On the client-side, `console.log` should be replaced by `alert`.
★ ★ ★
Another method that can be even more readable:
```
var amount, message;
funcWithRefScalars(amount = [200], message = [null] );
console.log(amount[0] + " - " + message[0]);
function funcWithRefScalars(amount, message) { // o(amount, message)
amount[0] *= 1.2;
message[0] = "20% increase";
}
```
Here you don't even need to create new dummy names, like `r` above. | Primitives are passed by value. But in case you only need to read the value of a primitve (and value is not known at the time when function is called) you can pass function which retrieves the value at the moment you need it.
```
function test(value) {
console.log('retrieve value');
console.log(value());
}
// call the function like this
var value = 1;
test(() => value);
``` |
13,104,494 | Does JavaScript pass by references or pass by values?
Here is an example from *[JavaScript: The Good Parts](https://en.wikipedia.org/wiki/Douglas_Crockford#Bibliography)*. I am very confused about the `my` parameter for the rectangle function. It is actually `undefined`, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.
Is it a closure? But no function is returned.
```
var shape = function (config) {
var that = {};
that.name = config.name || "";
that.area = function () {
return 0;
};
return that;
};
var rectangle = function (config, my) {
my = my || {};
my.l = config.length || 1;
my.w = config.width || 1;
var that = shape(config);
that.area = function () {
return my.l * my.w;
};
return that;
};
myShape = shape({
name: "Unhnown"
});
myRec = rectangle({
name: "Rectangle",
length: 4,
width: 6
});
console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());
``` | 2012/10/27 | [
"https://Stackoverflow.com/questions/13104494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778912/"
] | JavaScript is pass by value.
For primitives, primitive's value is passed. For Objects, Object's reference "value" is passed.
Example with Object:
```
var f1 = function(inputObject){
inputObject.a = 2;
}
var f2 = function(){
var inputObject = {"a": 1};
f1(inputObject);
console.log(inputObject.a);
}
```
Calling f2 results in printing out "a" value as 2 instead of 1, as the reference is passed and the "a" value in reference is updated.
Example with primitive:
```
var f1 = function(a){
a = 2;
}
var f2 = function(){
var a = 1;
f1(a);
console.log(a);
}
```
Calling f2 results in printing out "a" value as 1. | "Global" JavaScript variables are members of the window object. You could access the reference as a member of the window object.
```
var v = "initialized";
function byref(ref) {
window[ref] = "changed by ref";
}
byref((function(){for(r in window){if(window[r]===v){return(r);}}})());
// It could also be called like... byref('v');
console.log(v); // outputs changed by ref
```
Note, the above example will not work for variables declared within a function. |
17,099,491 | I have a long running multirow update such as:
```
UPDATE T set C1 = calculation(C2) where C1 is NULL
```
If table is large this update may take many seconds or even minutes.
During this time all other queries on this table fail with "database is locked"
after connection timeout expires (currently my timeout is 5 seconds).
I would like to stop this update query after, say, 3 seconds,
then restart it. Hopefully, after several restarts entire table will be updated.
Another option is to stop this update query before making any other request
(this will require inter-process cooperation, but it may be doable).
But I cannot find a way to stop update query without rolling back
all previously updated records.
I tried calling interrupt and returning non-0 from progress\_handler.
Both these approaches abort the update command
and roll back all the changes.
So, it appears that sqlite treats this update as a transaction,
which does not make much sense in this case because all rows are independent.
But I cannot start a new transaction for each row, can I?
If interrupt and progress\_handler cannot help me, what else I can do?
I also tried UPDATE with LIMIT and also WHERE custom\_condition(C1).
These approaches do allow me to terminate update earlier,
but they are significantly slower than regular update
and they cannot terminate the query at specific time
(before another connection timeout expires).
Any other ideas?
This multirow update is such a common operation
that, I hope, other people have a good solution for it. | 2013/06/14 | [
"https://Stackoverflow.com/questions/17099491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/894324/"
] | >
> So, it appears that sqlite treats this update as a transaction, which does not make much sense in this case because all rows are independent.
>
>
>
No, that actually makes perfect sense, because you're not executing multiple, independent updates. You're executing a single update statement. The [fine manual](http://www.sqlite.org/lang_transaction.html) says
>
> No changes can be made to the database except within a transaction.
> Any command that changes the database (basically, any SQL command
> other than SELECT) will automatically start a transaction if one is
> not already in effect. Automatically started transactions are
> committed when the last query finishes.
>
>
>
If you can determine the range of keys involved, you can execute multiple update statements. For example, if a key is an integer, and you determine the range to be from 1 to 1,000,000, you can write code to execute this series of updates.
```
begin transaction;
UPDATE T set C1 = calculation(C2)
where C1 is NULL and your_key between 1 and 100000;
commit;
begin transaction;
UPDATE T set C1 = calculation(C2)
where C1 is NULL and your_key between 100001 and 200000;
commit;
```
Other possibilities . . .
* You can sleep for a bit between transactions to give other queries a chance to execute.
* You can also time execution using application code, and calculate a best guess at range values that will avoid timeouts and still give good performance.
* You can select the keys for the rows that will be updated, and use their values to optimize the range of keys.
In my experience, it's unusual to treat updates this way, but it sounds like it fits your application.
>
> But I cannot start a new transaction for each row, can I?
>
>
>
Well, you *can*, but it's *probably* not going to help. It's essentially the same as the method above, using a single key instead of a range. I wouldn't fire you for testing that, though.
---
On my desktop, I can insert 100k rows in 1.455 seconds, and update 100k rows with a simple calculation in 420 ms. If you're running on a phone, that's probably not relevant. | You mentioned poor performance with LIMIT. Do you have a lastupdated column with an index on it? At the top of your procedure you would get the COMMENCED\_DATETIME and use it for every batch in the run:
```
update foo
set myvalue = 'x', lastupdated = UPDATE_COMMENCED
where id in
(
select id from foo where lastupdated < UPDATE_COMMENCED
limit SOME_REASONABLE_NUMBER
)
```
P.S. With respect to slowness:
`I also tried UPDATE with LIMIT and also WHERE custom_condition(C1). These approaches do allow me to terminate update earlier, but they are significantly slower than regular update...`
If you're willing to give other processes access to stale data, and your update is designed so as not to hog system resources, why is there a need to have the update complete within a certain amount of time? There seems to be no need to worry about perfomance in *absolute* terms. The concern should be *relative* to other processes -- make sure they're not blocked. |
17,099,491 | I have a long running multirow update such as:
```
UPDATE T set C1 = calculation(C2) where C1 is NULL
```
If table is large this update may take many seconds or even minutes.
During this time all other queries on this table fail with "database is locked"
after connection timeout expires (currently my timeout is 5 seconds).
I would like to stop this update query after, say, 3 seconds,
then restart it. Hopefully, after several restarts entire table will be updated.
Another option is to stop this update query before making any other request
(this will require inter-process cooperation, but it may be doable).
But I cannot find a way to stop update query without rolling back
all previously updated records.
I tried calling interrupt and returning non-0 from progress\_handler.
Both these approaches abort the update command
and roll back all the changes.
So, it appears that sqlite treats this update as a transaction,
which does not make much sense in this case because all rows are independent.
But I cannot start a new transaction for each row, can I?
If interrupt and progress\_handler cannot help me, what else I can do?
I also tried UPDATE with LIMIT and also WHERE custom\_condition(C1).
These approaches do allow me to terminate update earlier,
but they are significantly slower than regular update
and they cannot terminate the query at specific time
(before another connection timeout expires).
Any other ideas?
This multirow update is such a common operation
that, I hope, other people have a good solution for it. | 2013/06/14 | [
"https://Stackoverflow.com/questions/17099491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/894324/"
] | >
> So, it appears that sqlite treats this update as a transaction, which does not make much sense in this case because all rows are independent.
>
>
>
No, that actually makes perfect sense, because you're not executing multiple, independent updates. You're executing a single update statement. The [fine manual](http://www.sqlite.org/lang_transaction.html) says
>
> No changes can be made to the database except within a transaction.
> Any command that changes the database (basically, any SQL command
> other than SELECT) will automatically start a transaction if one is
> not already in effect. Automatically started transactions are
> committed when the last query finishes.
>
>
>
If you can determine the range of keys involved, you can execute multiple update statements. For example, if a key is an integer, and you determine the range to be from 1 to 1,000,000, you can write code to execute this series of updates.
```
begin transaction;
UPDATE T set C1 = calculation(C2)
where C1 is NULL and your_key between 1 and 100000;
commit;
begin transaction;
UPDATE T set C1 = calculation(C2)
where C1 is NULL and your_key between 100001 and 200000;
commit;
```
Other possibilities . . .
* You can sleep for a bit between transactions to give other queries a chance to execute.
* You can also time execution using application code, and calculate a best guess at range values that will avoid timeouts and still give good performance.
* You can select the keys for the rows that will be updated, and use their values to optimize the range of keys.
In my experience, it's unusual to treat updates this way, but it sounds like it fits your application.
>
> But I cannot start a new transaction for each row, can I?
>
>
>
Well, you *can*, but it's *probably* not going to help. It's essentially the same as the method above, using a single key instead of a range. I wouldn't fire you for testing that, though.
---
On my desktop, I can insert 100k rows in 1.455 seconds, and update 100k rows with a simple calculation in 420 ms. If you're running on a phone, that's probably not relevant. | I also posted this question at
<http://thread.gmane.org/gmane.comp.db.sqlite.general/81946>
and got several interesting answers, such as:
* divide range of rowid into slices and update one slice at a time
* use AUTOINCREMENT feature to start new update at the place where the previous update ended (by LIMIT 10000)
* create a trigger that calls select raise(fail, ...) to abort update without rollback |
65,779,401 | I want to create something like this on Swift It's for Alamofire json parse
```js
interface Question {
value: string;
data: [string]
}
interface Advice {
type: string;
data: { value: string }
}
interface CurrentItem {
type: string;
data: Advice | Question | string
}
``` | 2021/01/18 | [
"https://Stackoverflow.com/questions/65779401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14421893/"
] | Use an enum with associated values to represent the different possibilities:
```
enum Data {
case advice (Advice)
case question (Question)
case string (String)
}
```
You can then create your CurrentItem as a Struct
```
struct CurrentItem {
type: String
data: Data
}
```
If you're decoding from JSON you'll need to conform the struct to Decodable and write a custom `init(from decoder: Decoder)` method that looks at the data provided and then create the appropriate instance of the Data enum. | I think in Swift the way you'd handle a union type like this is with protocols.
```
struct Test {
var value: MyProtocol
}
```
(Note I put `struct` but it can be whatever type of object you need.)
Where `Type1`, `Type2` and `Type3` conform to some shared protocol. Either by construction, or they can be extended to adopt the protocol. This is advantageous because your object doesn't have to be limited to one of three types and handle each one separately, but rather it doesn't have to know about the inner workings of each of the types it has to support.
And where `MyProtocol` would look something like:
```
protocol MyProtocol {
var myValue: Bar { get set }
func myMethod(_ foo: Foo) -> SomeType
}
```
And say you wanted to extend `Type1` to adopt `MyProtocol`:
```
extension Type1: MyProtocol {
var myValue: Bar { foo }
func myMethod(_ foo: Foo) -> SomeType { bar }
}
```
Alternatively, Swift has lots of built-in protocols which might already be shared in common between your three types.
Note you could declare a type that conforms to a union of multiple types with `&` but Swift doesn't have a corresponding idea for "this type OR that type".
Note also that if your protocol has `Self` or associated type requirements it cannot be used as a generic constraint as shown above.
Read more about protocols in the [Swift Language Guide](https://docs.swift.org/swift-book/LanguageGuide/Protocols.html).
However, if your three types don't have anything in common, Swift also has the `Any` type and in your code you can test for each type as needed using conditional casting:
```
struct Test {
var value: Any
func doSomething() {
if let value = value as? Type1 {
doTheThing()
} // etc.
}
}
``` |
34,879,243 | I got this problem: I found a very cool pen on codepen, I take it, modified, but when I put this in my html page doesn't work with other divs.
Here the pen <https://jsfiddle.net/jtz21sz3/>
```
<canvas id="stage" width="400" height="400">
<p>Your browser doesn't support canvas.</p>
</canvas>
```
everything work, but when i try to insert a sticky menu in the top the canvas draws the circle, but I can't drag them.
<https://jsfiddle.net/Lp9w34sd/1/>
```
<div class="sticky-menu-wrapper">
<nav class="main-menu clear">
<div class="menu-menu-1-container"><ul id="menu-menu-1" class="menu" style="text-align:center">
<li id="menu-item-135" class="menu-item menu-item-type-custom menu-item-object-custom" style=" text-align:left; float: left; padding-top:16px;"><a>RELEASE</a></li>
</ul></div>
</nav>
</div>
<canvas id="stage" width="400" height="400">
<p>Your browser doesn't support canvas.</p>
</canvas>
```
Any idea how to fix it? | 2016/01/19 | [
"https://Stackoverflow.com/questions/34879243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4627712/"
] | Excel's COM interface speaks American so you need to use the US list separators in the formula strings. replace your semicolons with commas and you should be fine.
```
Range rng = activeWorksheet.get_Range("A1");
rng.FormulaArray = "=SUM(A4*C4,A5*C5,A6*C6,A7*C7)/SUM(A4:A7)";
``` | You need to update your formula to an array formula using the FormulaArray property of the range object, using { } and an R1C1 reference.
* <https://msdn.microsoft.com/en-us/library/office/ff837104.aspx>
>
> "=SUM(R4C1\*R4C3;R5C1\*R5C3;R6C1\*R6C3;R7C1\*R7C3)/SUM(R4C1:R7C1)"
>
>
> |
414,783 | I have a file that contains more than 4000 characters and I want to grep the string between the position 148 and 1824. How can I do this? | 2018/01/04 | [
"https://unix.stackexchange.com/questions/414783",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/268827/"
] | You don't use grep. There is a tool that has been designed for precisely this sort of thing: `cut`. To get characters 148 to 1824, do:
```
cut -c 148-1824 file
```
The `-c` flag means select characters. Use `-b` if you want to work on bytes.
If you insist on using `grep`, you would have to do something like this (assuming GNU grep)
```
grep -Po '^.{147}\K.{1675}' file
```
This matches the first 147 characters (`^.{147}`) and discards them (`\K`). Then it matches the next 1675 characters. The `-o` flag tells `grep` to only print the matching section of a line and the `-P` flag turns on perl-compatible regular expressions which let us use `\K`. | The command below will do the same. I tested it and it works fine. It extracts all characters from the 148th to the 1824th position.
```
awk '{print substr($0,148,1676)}' filename
```
`substr($0,148,1676)}` will take a substring of the current line (`$0`), starting at the 148th character and continuing until the character at position 148 + 1676. That means it ends at position 1824. |
414,783 | I have a file that contains more than 4000 characters and I want to grep the string between the position 148 and 1824. How can I do this? | 2018/01/04 | [
"https://unix.stackexchange.com/questions/414783",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/268827/"
] | You don't use grep. There is a tool that has been designed for precisely this sort of thing: `cut`. To get characters 148 to 1824, do:
```
cut -c 148-1824 file
```
The `-c` flag means select characters. Use `-b` if you want to work on bytes.
If you insist on using `grep`, you would have to do something like this (assuming GNU grep)
```
grep -Po '^.{147}\K.{1675}' file
```
This matches the first 147 characters (`^.{147}`) and discards them (`\K`). Then it matches the next 1675 characters. The `-o` flag tells `grep` to only print the matching section of a line and the `-P` flag turns on perl-compatible regular expressions which let us use `\K`. | To "grep" against a subsection of each line in a file, use awk to extract that subsection and then compare that section against your regular expression.
A simplified example:
```
$ cat input
junkjeffjunk
$ awk '{ piece=substr($0, 5, 4); if (piece ~ /jeff/) print piece; }' input
jeff
```
For your case:
```
awk '{ piece=substr($0, 148, 1676); if (piece ~ /your-regex-here/) print piece; }' input
``` |
414,783 | I have a file that contains more than 4000 characters and I want to grep the string between the position 148 and 1824. How can I do this? | 2018/01/04 | [
"https://unix.stackexchange.com/questions/414783",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/268827/"
] | The command below will do the same. I tested it and it works fine. It extracts all characters from the 148th to the 1824th position.
```
awk '{print substr($0,148,1676)}' filename
```
`substr($0,148,1676)}` will take a substring of the current line (`$0`), starting at the 148th character and continuing until the character at position 148 + 1676. That means it ends at position 1824. | To "grep" against a subsection of each line in a file, use awk to extract that subsection and then compare that section against your regular expression.
A simplified example:
```
$ cat input
junkjeffjunk
$ awk '{ piece=substr($0, 5, 4); if (piece ~ /jeff/) print piece; }' input
jeff
```
For your case:
```
awk '{ piece=substr($0, 148, 1676); if (piece ~ /your-regex-here/) print piece; }' input
``` |
73,143,408 | I have the input like this
```
8.8.8.8,678,fog,hat
8.8.4.4,5674,rat,fruit
www.google.com,1234,can,zone
```
I want to split this input in Python so that only the IP address needs to be fetched which I will use for PING purpose. I really appreciate your help in this regard. | 2022/07/27 | [
"https://Stackoverflow.com/questions/73143408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15471384/"
] | This will preferentially select Approved, then Pending, then everything else. If you don't want "everything else" just filter in the WHERE clause.
```
select id,
name,
date,
status
from (
select *,
row_number() over
( partition by id
order by case when status = 'Approved' then 1
when status = 'Pending' then 2
else 3
end asc,
date
) as first_by_date_with_approved_precedence
from your_table
) tmp
where first_by_date_with_approved_precedence = 1
``` | It could also be as easy as the following (provided status is not blank or null)
```
Select Top 1 with ties *
from YourTable
order by row_number() over (partition by id order by Status)
```
**Results**
```
ID NAME DATE STATUS
1 Joe 01-22 Approved
2 Bill 02-22 Approved
3 John 01-22 Approved
4 Bob 02-22 Pending
``` |
831,810 | My database has a parent table with an auto-incrementing primary key identity 'ID', and a normal 'TIMESTAMP column'. I have child tables with a foreign key that refer to the parent 'ID' column.
I want to write a stored procedure that inserts a new column into both the parent and child databases. How would I set the child 'ID' column to equal the new auto-incremented parent 'ID' column? Does this require a separate:
```
SELECT TOP 1 * FROM PARENT_TABLE
```
Or is there another way? | 2009/05/06 | [
"https://Stackoverflow.com/questions/831810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85170/"
] | You can retrieve it from SCOPE\_IDENTITY(). For example:
```
declare @myid int
INSERT INTO table (field) VALUES ('value')
SELECT @myid = SCOPE_IDENTITY()
``` | select scope\_identity(); |
45,021,644 | I have a bunch of websites running on a single instance of Azure App Service, and they're all set to Always On. They all suddenly restarted at the same time, causing everything to go slow for a few minutes as everything hit a cold request.
I would expect this if the service had moved me to a new host, but that didn't happen -- I'm still on the same hostname.
CPU and memory usage were normal at the time of the restart, and I didn't initiate any deployments or anything like that. I don't see an obvious reason for the restart.
Is there any logging anywhere that I can see to figure out *why* they all restarted? Or is this just a normal thing that App Service does from time to time? | 2017/07/10 | [
"https://Stackoverflow.com/questions/45021644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32187/"
] | So, it seems the answer to this is "no, you can't really know *why*, you can just infer that it *did*."
I mean, you can add some Application Insights logging like
```
private void Application_End()
{
log.Warn($"The application is shutting down because of '{HostingEnvironment.ShutdownReason}'.");
TelemetryConfiguration.Active.TelemetryChannel.Flush();
// Server Channel flush is async, wait a little while and hope for the best
Thread.Sleep(TimeSpan.FromSeconds(2));
}
```
and you will end up with `"The application is shutting down because of 'ConfigurationChange'."` or `"The application is shutting down because of 'HostingEnvironment'."`, but it doesn't really tell you what's going on at the host level.
What I needed to accept is that App Service is going to restart things from time to time, and ask myself why I cared. App Service is supposed to be smart enough to wait for the application pool to be warmed up before sending requests to it (like overlapped recycling). Yet, my apps would sit there CPU-crunching for 1-2 minutes after a recycle.
It took me a while to figure out, but the culprit was that all of my apps have a rewrite rule to redirect from HTTP to HTTPS. This does not work with the Application Initialization module: it sends a request to the root, and all it gets its a 301 redirect from the URL Rewrite module, and the ASP.NET pipeline isn't hit at all, the hard work wasn't actually done. App Service/IIS then thought the worker process was ready and then sends traffic to it. But the first "real" request actually follows the 301 redirect to the HTTPS URL, and bam! that user hits the pain of a cold start.
[I added a rewrite rule described here](https://support.microsoft.com/en-us/help/2843964/application-initialization-module-fails-when-web-site-requires-ssl) to exempt the Application Initialization module from needing HTTPS, so when it hits the root of the site, it will actually trigger the page load and thus the whole pipeline:
```
<rewrite>
<rules>
<clear />
<rule name="Do not force HTTPS for application initialization" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" />
<add input="{HTTP_USER_AGENT}" pattern="Initialization" />
</conditions>
<action type="Rewrite" url="{URL}" />
</rule>
<rule name="Force HTTPS" enabled="true" stopProcessing="true">
<match url="(.*)" ignoreCase="false" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
```
It's one of many entries in a diary of moving old apps into Azure -- turns out there's a lot of things you can get away with when something's running on a traditional VM that seldom restarts, but it'll need some TLC to work out the kinks when migrating to our brave new world in the cloud....
--
**UPDATE 10/27/2017:** Since this writing, Azure has added a new tool under "Diagnose and solve problems". Click "Web App Restarted", and it'll tell you the reason, usually because of storage latency or infrastructure upgrades. The above still stands though, in that when moving to Azure App Service, the best way forward is you really just have to coax your app into being comfortable with random restarts.
--
**UPDATE 2/11/2018:** After migrating several legacy systems to a single instance of a medium App Service Plan (with plenty of CPU and memory overhead), I was having a vexing problem where my deployments from staging slots would go seamlessly, but whenever I'd get booted to a new host because of Azure infrastructure maintenance, everything would go haywire with downtime of 2-3 minutes. I was driving myself nuts trying to figure out why this was happening, because App Service is supposed to wait until it receives a successful response from your app before booting you to the new host.
I was so frustrated by this that I was ready to classify App Service as enterprise garbage and go back to IaaS virtual machines.
It turned out to be multiple issues, and I suspect others will come across them while porting their own beastly legacy ASP.NET apps to App Service, so I thought I'd run through them all here.
The first thing to check is that you're actually doing real work in your `Application_Start`. For example, I'm using NHibernate, which while good at many things is quite a pig at loading its configuration, so I make sure to actually create the `SessionFactory` during `Application_Start` to make sure that the hard work is done.
The second thing to check, as mentioned above, is that you don't have a rewrite rule for SSL that is interfering with App Service's warmup check. You can exclude the warmup checks from your rewrite rule as mentioned above. Or, in the time since I originally wrote that work around, App Service has added an [HTTPS Only](https://blogs.msdn.microsoft.com/benjaminperkins/2017/11/30/how-to-make-an-azure-app-service-https-only/) flag that allows you to do the HTTPS redirect at the load balancer instead of within your web.config file. Since it's handled at a layer of indirection above your application code, you don't have to think about it, so I would recommend the HTTPS Only flag as the way to go.
The third thing to consider is whether or not you're using the [App Service Local Cache Option](https://learn.microsoft.com/en-us/azure/app-service/app-service-local-cache-overview). In brief, this is an option where App Service will copy your app's files to the local storage of the instances that it's running on rather than off of a network share, and is a great option to enable if your app doesn't care if it loses changes written to the local filesystem. It speeds up I/O performance (which is important because, remember, [App Service runs on potatoes](https://stackoverflow.com/questions/36966505/azure-web-apps-are-really-slow)) and eliminates restarts that are caused by any maintenance on network share. But, there is a specific subtlety regarding App Service's infrastructure upgrades that is poorly documented and you need to be aware of. Specifically, the Local Cache option is initiated in the background in a separate app domain after the first request, and then you're switched to the app domain when the local cache is ready. That means that App Service will hit a warmup request against your site, get a successful response, point traffic to that instance, but (whoops!) now Local Cache is grinding I/O in the background, and if you have a lot of sites on this instance, you've ground to a halt because App Service I/O is horrendous. If you don't know this is happening, it looks spooky in the logs because it's as if your app is starting up twice on the same instance (because it is). The solution is to follow this [Jet blog post](https://tech.jet.com/blog/2017/02-01-azure-web-apps/) and create an application initialization warmup page to monitors for the environment variable that tells you when the Local Cache is ready. This way, you can force App Service to delay booting you to the new instance until the Local Cache is fully prepped. Here's one that I use to make sure I can talk to the database, too:
```
public class WarmupHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public ISession Session
{
get;
set;
}
public void ProcessRequest(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var request = context.Request;
var response = context.Response;
var localCacheVariable = Environment.GetEnvironmentVariable("WEBSITE_LOCAL_CACHE_OPTION");
var localCacheReadyVariable = Environment.GetEnvironmentVariable("WEBSITE_LOCALCACHE_READY");
var databaseReady = true;
try
{
using (var transaction = this.Session.BeginTransaction())
{
var query = this.Session.QueryOver<User>()
.Take(1)
.SingleOrDefault<User>();
transaction.Commit();
}
}
catch
{
databaseReady = false;
}
var result = new
{
databaseReady,
machineName = Environment.MachineName,
localCacheEnabled = "Always".Equals(localCacheVariable, StringComparison.OrdinalIgnoreCase),
localCacheReady = "True".Equals(localCacheReadyVariable, StringComparison.OrdinalIgnoreCase),
};
response.ContentType = "application/json";
var warm = result.databaseReady && (!result.localCacheEnabled || result.localCacheReady);
response.StatusCode = warm ? (int)HttpStatusCode.OK : (int)HttpStatusCode.ServiceUnavailable;
var serializer = new JsonSerializer();
serializer.Serialize(response.Output, result);
}
}
```
Also remember to map a route and add the application initialization your `web.config`:
```
<applicationInitialization doAppInitAfterRestart="true">
<add initializationPage="/warmup" />
</applicationInitialization>
```
The fourth thing to consider is that sometimes App Service will restart your app for seemingly garbage reasons. It seems that setting the `fcnMode` property to `Disabled` can help; it prevents the runtime from restarting your app if someone diddles with configuration files or code on the server. If you're using staging slots and doing deployments that way, this shouldn't bother you. But if you expect to be able to FTP in and diddle with a file and see that change reflected in production, then don't use this option:
```
<httpRuntime fcnMode="Disabled" targetFramework="4.5" />
```
The fifth thing to consider, *and this was primarily my problem all along*, is whether or not you are using staging slots with the `AlwaysOn` option enabled. The `AlwaysOn` option works by pinging your site every minute or so to make sure it's warm so that IIS doesn't spin it down. Inexplicably, [this isn't a sticky setting](https://social.msdn.microsoft.com/Forums/azure/en-US/f1a4664d-efba-4983-878b-9368a54a97f1/why-is-alwayson-not-a-slot-setting?forum=windowsazurewebsitespreview), so you may have turned on `AlwaysOn` on both your production and staging slots so you don't have to mess with it every time. This causes a problem with App Service infrastructure upgrades when they boot you to a new host. Here's what happens: let's say you have 7 sites hosted on an instance, each with its own staging slot, everything with `AlwaysOn` enabled. App Service does the warmup and application initialization to your 7 production slots and dutifully waits for them to respond successfully before redirecting traffic over. **But it doesn't do this for the staging slots.** So it directs traffic over to the new instance, but then `AlwaysOn` kicks in 1-2 minutes later on the staging slots, so now you have 7 more sites starting up at the same time. Remember, [App Service runs on potatoes](https://stackoverflow.com/questions/36966505/azure-web-apps-are-really-slow), so all this additional I/O happening at the same time is going to destroy the performance of your production slots and will be perceived as downtime.
The solution is to keep `AlwaysOn` off on your staging slots so you don't get nailed by this simultaneous I/O frenzy after an infrastructure update. If you are using a swap script via PowerShell, maintaining this "Off in staging, On in production" is surprisingly verbose to do:
```
Login-AzureRmAccount -SubscriptionId {{ YOUR_SUBSCRIPTION_ID }}
$resourceGroupName = "YOUR-RESOURCE-GROUP"
$appName = "YOUR-APP-NAME"
$slotName = "YOUR-SLOT-NAME-FOR-EXAMPLE-STAGING"
$props = @{ siteConfig = @{ alwaysOn = $true; } }
Set-AzureRmResource `
-PropertyObject $props `
-ResourceType "microsoft.web/sites/slots" `
-ResourceGroupName $resourceGroupName `
-ResourceName "$appName/$slotName" `
-ApiVersion 2015-08-01 `
-Force
Swap-AzureRmWebAppSlot `
-SourceSlotName $slotName `
-ResourceGroupName $resourceGroupName `
-Name $appName
$props = @{ siteConfig = @{ alwaysOn = $false; } }
Set-AzureRmResource `
-PropertyObject $props `
-ResourceType "microsoft.web/sites/slots" `
-ResourceGroupName $resourceGroupName `
-ResourceName "$appName/$slotName" `
-ApiVersion 2015-08-01 `
-Force
```
This script sets the staging slot to have `AlwaysOn` turned on, does the swap so that staging is now production, then sets the staging slot to have `AlwaysOn` turned off, so it doesn't blow things up after an infrastructure upgrade.
Once you get this working, it is indeed nice to have a PaaS that handles security updates and hardware failures for you. But it's a little bit more difficult to achieve in practice than the marketing materials might suggest. Hope this helps someone.
--
**UPDATE 07/17/2020:** In the blurb above, I talk about needing to diddle with "AlwaysOn" if you're using staging slots, as it would swap with the slots, and having it on all slots can cause performance issues. At some point that isn't clear to me, [they seem to have fixed this so that "AlwaysOn" isn't swapped](https://learn.microsoft.com/en-us/azure/app-service/deploy-staging-slots#what-happens-during-a-swap). My script actually still does the diddling with AlwaysOn, but in effect it ends up being a no-op now. So the advice to keep AlwaysOn off for your staging slots still stands, but you shouldn't have to do this little juggle in a script anymore. | If your service restarted due to OutOfMemoryExceptions Application\_End might not run due to the app crashing.
We moved our ASP.NET 4.8 MVC 5 app to Azure App Services (with windows containers) and were faced with OOMs once we went live. Application crashes were so severe that the Application\_End event was not able to log any messages. We did get intermittent OOMEs that AppInsights was able to dispatch before the restart.
Our engineers had been searching to increase the memory of the website (as we did use a lot in our previous environment) but could not find any usable reference. We were saved at last by Microsoft support who suggested using this application setting (to be added under Configuration) to increase memory:
`WEBSITE_MEMORY_LIMIT_MB = 3072`
They added this reference to the Azure documentation:
<https://github.com/MicrosoftDocs/azure-docs/issues/13263#issuecomment-655051828>
Now our application is running happily committing around 4200M at peak times. My service plan has 32G, has 2 app services, total of 5 slots, one of which is configured to use 5120M. Still have around 40% memory left for spinning up staging slots. |
19,220,177 | I need help with writing a regular expression for the following rules:
1. White spaces aren't allowed.
2. The only case where white spaces are allowed is inside brackets `[]`.
I have came up with this expression:
```
[^(\\[\s\\])]
```
But in this case each of the chars: `[`, white space, and `]` is not allowed separately.
Please help
Thanks | 2013/10/07 | [
"https://Stackoverflow.com/questions/19220177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2853840/"
] | I changed your method `change` a bit to make it work.
From Plunker you can see that on *master* change all children still have old value. So I added `onMasterChange` method
**HTML**
```
<input type="checkbox"
ng-model="master"
ng-change="onMasterChange(master)"></input>
```
I created as default: `$scope.master = false;`
```
....
$scope.master = false;
$scope.onMasterChange = function(master){
for(var i = 0; i < $scope.votes.length; i++) {
$scope.votes[i].cb = master;
}
};
$scope.change = function(value) {
for(var i = 0; i < $scope.votes.length; i++) {
//if($scope.votes[i].cb == undefined){
// $scope.votes[i].cb = false;
// }
if($scope.master == true){
$scope.votes[i].cb = $scope.master;
$scope.votes[i].status = value;
}
else if( $scope.votes[i].cb == true) {
$scope.votes[i].status = value;
}
}
};
```
See `[Plunker](http://plnkr.co/edit/d6nHDDf0oWgM2V2ORiAx?p=preview)`
Hope it will help, | It is working, but I believe ng-model is taking precedence over ng-checked. If you remove ng-model from the checkboxes, ng-checked is working as expected.
```
<input type="checkbox" ng-checked="master"></input>
```
<http://plnkr.co/edit/q35JlhOVSGxmu6QW8e98?p=preview>
It is important to note, however, that ng-checked does not update your model, it only changes the presentation of the checkbox. A way of tackling this would be to remove the master binding, and call a method with ng-click on your master checkbox which changes .cb on each box.
Edit: Working version using a watch on the master checkbox.
<http://plnkr.co/edit/3NwGtp1FX8g9bfMrbWU5?p=preview> |
353,639 | My university department has a local DNS server that serves all of the computers in the department. I am concerned about the privacy and security implications of this. Posit that I am merely one of the users on a workstation, with no privileged access to the DNS server, or any HTTP proxy.
* Can I make use of the DNS server to determine whether someone else in the department has accessed a page on some arbitrary external WWW site? Can I do so for accesses within the last few seconds?
* If the answer to the preceding question is "Yes." what tradeoffs do I have to make in order to close this leak? If adjustments need to be made to the DNS server, what form would they take? Could I address this purely from the individual workstation end, without touching the server?
* Would installing more than one DNS server affect this? If so, how? How about running DNS servers on the workstations?
* Is this actually a leak? Would I be able to determine the same information *without* using the DNS server? Would I be able to determine *better* information, indeed? | 2012/01/25 | [
"https://serverfault.com/questions/353639",
"https://serverfault.com",
"https://serverfault.com/users/108319/"
] | There's no standard way to query NIC teaming configuration because this is done with proprietary driver-based mechanisms. Broadcom drivers, for example, do it differently than Intel drivers. You'd probably end up needing to parse the proprietary configuration information these drivers store in the registry in order to figure out what the teaming configuration was.
You could use `ipconfig /all` as @joeqwerty suggested to get the IP configuration information. You could also use `netsh dump`, which will give you the interface names and IP configuration. You won't get teaming configuration out of either of those, though. | Wouldn't it make more sense to use a monitoring solution like Nagios? Take a look at <http://nagios.sourceforge.net/docs/3_0/monitoring-windows.html>.
Besides, if this is a brandname server, monitoring can be done using the vendor-provided applications, like Dell OMSA with IT-Assistant for example. |
353,639 | My university department has a local DNS server that serves all of the computers in the department. I am concerned about the privacy and security implications of this. Posit that I am merely one of the users on a workstation, with no privileged access to the DNS server, or any HTTP proxy.
* Can I make use of the DNS server to determine whether someone else in the department has accessed a page on some arbitrary external WWW site? Can I do so for accesses within the last few seconds?
* If the answer to the preceding question is "Yes." what tradeoffs do I have to make in order to close this leak? If adjustments need to be made to the DNS server, what form would they take? Could I address this purely from the individual workstation end, without touching the server?
* Would installing more than one DNS server affect this? If so, how? How about running DNS servers on the workstations?
* Is this actually a leak? Would I be able to determine the same information *without* using the DNS server? Would I be able to determine *better* information, indeed? | 2012/01/25 | [
"https://serverfault.com/questions/353639",
"https://serverfault.com",
"https://serverfault.com/users/108319/"
] | Use the GWMI commandlet in powershell. You can use a -computername parameter to specify the remote machines. I believe the two namespaces you'll want to play with are Win32\_NetworkAdapterConfiguration
Win32\_NetworkAdapterSetting | Wouldn't it make more sense to use a monitoring solution like Nagios? Take a look at <http://nagios.sourceforge.net/docs/3_0/monitoring-windows.html>.
Besides, if this is a brandname server, monitoring can be done using the vendor-provided applications, like Dell OMSA with IT-Assistant for example. |
353,639 | My university department has a local DNS server that serves all of the computers in the department. I am concerned about the privacy and security implications of this. Posit that I am merely one of the users on a workstation, with no privileged access to the DNS server, or any HTTP proxy.
* Can I make use of the DNS server to determine whether someone else in the department has accessed a page on some arbitrary external WWW site? Can I do so for accesses within the last few seconds?
* If the answer to the preceding question is "Yes." what tradeoffs do I have to make in order to close this leak? If adjustments need to be made to the DNS server, what form would they take? Could I address this purely from the individual workstation end, without touching the server?
* Would installing more than one DNS server affect this? If so, how? How about running DNS servers on the workstations?
* Is this actually a leak? Would I be able to determine the same information *without* using the DNS server? Would I be able to determine *better* information, indeed? | 2012/01/25 | [
"https://serverfault.com/questions/353639",
"https://serverfault.com",
"https://serverfault.com/users/108319/"
] | There's no standard way to query NIC teaming configuration because this is done with proprietary driver-based mechanisms. Broadcom drivers, for example, do it differently than Intel drivers. You'd probably end up needing to parse the proprietary configuration information these drivers store in the registry in order to figure out what the teaming configuration was.
You could use `ipconfig /all` as @joeqwerty suggested to get the IP configuration information. You could also use `netsh dump`, which will give you the interface names and IP configuration. You won't get teaming configuration out of either of those, though. | this links may help you.
<http://technet.microsoft.com/en-us/library/bb726987.aspx>
<http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8781> |
353,639 | My university department has a local DNS server that serves all of the computers in the department. I am concerned about the privacy and security implications of this. Posit that I am merely one of the users on a workstation, with no privileged access to the DNS server, or any HTTP proxy.
* Can I make use of the DNS server to determine whether someone else in the department has accessed a page on some arbitrary external WWW site? Can I do so for accesses within the last few seconds?
* If the answer to the preceding question is "Yes." what tradeoffs do I have to make in order to close this leak? If adjustments need to be made to the DNS server, what form would they take? Could I address this purely from the individual workstation end, without touching the server?
* Would installing more than one DNS server affect this? If so, how? How about running DNS servers on the workstations?
* Is this actually a leak? Would I be able to determine the same information *without* using the DNS server? Would I be able to determine *better* information, indeed? | 2012/01/25 | [
"https://serverfault.com/questions/353639",
"https://serverfault.com",
"https://serverfault.com/users/108319/"
] | There's no standard way to query NIC teaming configuration because this is done with proprietary driver-based mechanisms. Broadcom drivers, for example, do it differently than Intel drivers. You'd probably end up needing to parse the proprietary configuration information these drivers store in the registry in order to figure out what the teaming configuration was.
You could use `ipconfig /all` as @joeqwerty suggested to get the IP configuration information. You could also use `netsh dump`, which will give you the interface names and IP configuration. You won't get teaming configuration out of either of those, though. | Use the GWMI commandlet in powershell. You can use a -computername parameter to specify the remote machines. I believe the two namespaces you'll want to play with are Win32\_NetworkAdapterConfiguration
Win32\_NetworkAdapterSetting |
353,639 | My university department has a local DNS server that serves all of the computers in the department. I am concerned about the privacy and security implications of this. Posit that I am merely one of the users on a workstation, with no privileged access to the DNS server, or any HTTP proxy.
* Can I make use of the DNS server to determine whether someone else in the department has accessed a page on some arbitrary external WWW site? Can I do so for accesses within the last few seconds?
* If the answer to the preceding question is "Yes." what tradeoffs do I have to make in order to close this leak? If adjustments need to be made to the DNS server, what form would they take? Could I address this purely from the individual workstation end, without touching the server?
* Would installing more than one DNS server affect this? If so, how? How about running DNS servers on the workstations?
* Is this actually a leak? Would I be able to determine the same information *without* using the DNS server? Would I be able to determine *better* information, indeed? | 2012/01/25 | [
"https://serverfault.com/questions/353639",
"https://serverfault.com",
"https://serverfault.com/users/108319/"
] | Use the GWMI commandlet in powershell. You can use a -computername parameter to specify the remote machines. I believe the two namespaces you'll want to play with are Win32\_NetworkAdapterConfiguration
Win32\_NetworkAdapterSetting | this links may help you.
<http://technet.microsoft.com/en-us/library/bb726987.aspx>
<http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8781> |
39,045,211 | When using the Microsoft Dynamics CRM Online 2016 OData API, I ran into a problem
creating a task/phonecall with statecode equal to completed.
Problem Description:
1. create a phone call entity with statecode=1 (Completed)
statuscode=2 (Made)
same idea with task (constants defined [here](https://technet.microsoft.com/en-us/library/dn531157.aspx))
2. API returns an internal server error saying that:
>
> 2 is not a valid status code for state code PhoneCallState.Open on phonecall with Id cfdb5757-3666-e611-80fa-3863bb2ed1f8.
>
>
>
Dynamics server ignored the PhoneCallState.Completed (statecode = 1) parameter
that I passed to it.
For now, the workaround is to make a separate PATCH request to update the statecode and statuscode.
Is there a way to create a task/phonecall with completed state in one request? | 2016/08/19 | [
"https://Stackoverflow.com/questions/39045211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271991/"
] | The best Moq can do in this case is create a proxy as a derived class of `Jeep` but it cannot override the non-virtual `Type` property. Remember that when you attempt to create a Mock with Moq, the framework generates a class that either implements the target interface or derives from the target class.
[Microsoft Fakes](https://msdn.microsoft.com/en-us/library/hh549175.aspx) work well with Moq provided that you have the Visual Studio license level to access it. | Since this is a rather generalized question, I'm going to suggest a different approach. Mocking / Faking / Stubbing a class or interface that you don't control is generally difficult. Furthermore, this typically leads to replicating someone else's functionality in your mock instance.
A better approach is to isolate interaction with the external library into a wrapping class that you control the interface and implementation of. This will allow you to easily mock/fake/stub *your* interface for testing consumers of your interface.
This still leaves the question of what to do with the isolation layer class. For this, you'll need to do more of an integration test that actually exercises both your wrapping class and the external class. Then, verify that you get the expected behavior from the combination of your class and the external classes you're wrapping. |
39,045,211 | When using the Microsoft Dynamics CRM Online 2016 OData API, I ran into a problem
creating a task/phonecall with statecode equal to completed.
Problem Description:
1. create a phone call entity with statecode=1 (Completed)
statuscode=2 (Made)
same idea with task (constants defined [here](https://technet.microsoft.com/en-us/library/dn531157.aspx))
2. API returns an internal server error saying that:
>
> 2 is not a valid status code for state code PhoneCallState.Open on phonecall with Id cfdb5757-3666-e611-80fa-3863bb2ed1f8.
>
>
>
Dynamics server ignored the PhoneCallState.Completed (statecode = 1) parameter
that I passed to it.
For now, the workaround is to make a separate PATCH request to update the statecode and statuscode.
Is there a way to create a task/phonecall with completed state in one request? | 2016/08/19 | [
"https://Stackoverflow.com/questions/39045211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271991/"
] | The best Moq can do in this case is create a proxy as a derived class of `Jeep` but it cannot override the non-virtual `Type` property. Remember that when you attempt to create a Mock with Moq, the framework generates a class that either implements the target interface or derives from the target class.
[Microsoft Fakes](https://msdn.microsoft.com/en-us/library/hh549175.aspx) work well with Moq provided that you have the Visual Studio license level to access it. | >
> So my question is: is there a way to setup the Type property when mocking the Jeep class?
>
>
>
The short answer is no, you cannot Mock a non virtual member using Moq.
However, I don't think there's any reason in this case to mock anything, since there isn't any behaviour to mock. The only member you have there is a simple `string` property. So even if you could, you probably shouldn't.
* If you are trying to test the `Jeep` class, just test it directly
without mocking any of its members; mocking should only be used when you need to control the behaviour of one of the dependencies of the System Under Test (SUT)
* If you *are* passing the `Jeep`
class to another method as a dependency in order to test that method, you can just
`new` up a `Jeep` instance and pass it in your test in this case; since it doesn't
have any boundary-crossing behaviours (network calls, etc) then there
is no need to mock it.
You might also consider that if it's the second case, you ought to be able to pass an `IVehicle` instead of a `Jeep`, in which case mocking is back on the table (although as mentioned, there is no apparent need in this case)
Incidentally, your hierarchy looks a little off - why does `Vehicle` not itself implement `IVehicle`?
i.e.
```
public interface IVehicle
{
string Type { get; }
}
public class Vehicle: IVehicle
{
public string Type { get; }
}
public class Jeep : Vehicle
{
}
```
Then `Jeep` will already be both a Vehicle and an `IVehicle` :) |
39,045,211 | When using the Microsoft Dynamics CRM Online 2016 OData API, I ran into a problem
creating a task/phonecall with statecode equal to completed.
Problem Description:
1. create a phone call entity with statecode=1 (Completed)
statuscode=2 (Made)
same idea with task (constants defined [here](https://technet.microsoft.com/en-us/library/dn531157.aspx))
2. API returns an internal server error saying that:
>
> 2 is not a valid status code for state code PhoneCallState.Open on phonecall with Id cfdb5757-3666-e611-80fa-3863bb2ed1f8.
>
>
>
Dynamics server ignored the PhoneCallState.Completed (statecode = 1) parameter
that I passed to it.
For now, the workaround is to make a separate PATCH request to update the statecode and statuscode.
Is there a way to create a task/phonecall with completed state in one request? | 2016/08/19 | [
"https://Stackoverflow.com/questions/39045211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271991/"
] | The best Moq can do in this case is create a proxy as a derived class of `Jeep` but it cannot override the non-virtual `Type` property. Remember that when you attempt to create a Mock with Moq, the framework generates a class that either implements the target interface or derives from the target class.
[Microsoft Fakes](https://msdn.microsoft.com/en-us/library/hh549175.aspx) work well with Moq provided that you have the Visual Studio license level to access it. | disclaimer: I work at Typemock.
By using [Typemock Isolator](http://www.typemock.com/) you will be able to mock non-virtual methods and won't need to change your code in order to do so, in this specific example you can fake an instance of `Jeep` and then modify his methods behavior.
Here is an example for a test that mock `Jeep`:
```
[TestMethod]
public void CallFakeJeepType_WillReturnWantedString()
{
var jeep = Isolate.Fake.Instance<Jeep>();
Isolate.WhenCalled(() => jeep.Type).WillReturn("fake jeep");
var result = Jeep.DoSomthing(jeep);
Assert.AreEqual("fake jeep", result);
}
```
note: if the `Jeep.Type` had a setter as well you could use typemock's [True property](https://www.typemock.com/docs?book=Isolator&page=Documentation%2FHtmlDocs%2Fcontrollingpropertybehaviorusingtrueproperties.htm) and the test will look like this
```
var jeep = Isolate.Fake.Instance<Jeep>();
jeep.Type = "fake jeep";
``` |
39,045,211 | When using the Microsoft Dynamics CRM Online 2016 OData API, I ran into a problem
creating a task/phonecall with statecode equal to completed.
Problem Description:
1. create a phone call entity with statecode=1 (Completed)
statuscode=2 (Made)
same idea with task (constants defined [here](https://technet.microsoft.com/en-us/library/dn531157.aspx))
2. API returns an internal server error saying that:
>
> 2 is not a valid status code for state code PhoneCallState.Open on phonecall with Id cfdb5757-3666-e611-80fa-3863bb2ed1f8.
>
>
>
Dynamics server ignored the PhoneCallState.Completed (statecode = 1) parameter
that I passed to it.
For now, the workaround is to make a separate PATCH request to update the statecode and statuscode.
Is there a way to create a task/phonecall with completed state in one request? | 2016/08/19 | [
"https://Stackoverflow.com/questions/39045211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271991/"
] | Since this is a rather generalized question, I'm going to suggest a different approach. Mocking / Faking / Stubbing a class or interface that you don't control is generally difficult. Furthermore, this typically leads to replicating someone else's functionality in your mock instance.
A better approach is to isolate interaction with the external library into a wrapping class that you control the interface and implementation of. This will allow you to easily mock/fake/stub *your* interface for testing consumers of your interface.
This still leaves the question of what to do with the isolation layer class. For this, you'll need to do more of an integration test that actually exercises both your wrapping class and the external class. Then, verify that you get the expected behavior from the combination of your class and the external classes you're wrapping. | >
> So my question is: is there a way to setup the Type property when mocking the Jeep class?
>
>
>
The short answer is no, you cannot Mock a non virtual member using Moq.
However, I don't think there's any reason in this case to mock anything, since there isn't any behaviour to mock. The only member you have there is a simple `string` property. So even if you could, you probably shouldn't.
* If you are trying to test the `Jeep` class, just test it directly
without mocking any of its members; mocking should only be used when you need to control the behaviour of one of the dependencies of the System Under Test (SUT)
* If you *are* passing the `Jeep`
class to another method as a dependency in order to test that method, you can just
`new` up a `Jeep` instance and pass it in your test in this case; since it doesn't
have any boundary-crossing behaviours (network calls, etc) then there
is no need to mock it.
You might also consider that if it's the second case, you ought to be able to pass an `IVehicle` instead of a `Jeep`, in which case mocking is back on the table (although as mentioned, there is no apparent need in this case)
Incidentally, your hierarchy looks a little off - why does `Vehicle` not itself implement `IVehicle`?
i.e.
```
public interface IVehicle
{
string Type { get; }
}
public class Vehicle: IVehicle
{
public string Type { get; }
}
public class Jeep : Vehicle
{
}
```
Then `Jeep` will already be both a Vehicle and an `IVehicle` :) |
39,045,211 | When using the Microsoft Dynamics CRM Online 2016 OData API, I ran into a problem
creating a task/phonecall with statecode equal to completed.
Problem Description:
1. create a phone call entity with statecode=1 (Completed)
statuscode=2 (Made)
same idea with task (constants defined [here](https://technet.microsoft.com/en-us/library/dn531157.aspx))
2. API returns an internal server error saying that:
>
> 2 is not a valid status code for state code PhoneCallState.Open on phonecall with Id cfdb5757-3666-e611-80fa-3863bb2ed1f8.
>
>
>
Dynamics server ignored the PhoneCallState.Completed (statecode = 1) parameter
that I passed to it.
For now, the workaround is to make a separate PATCH request to update the statecode and statuscode.
Is there a way to create a task/phonecall with completed state in one request? | 2016/08/19 | [
"https://Stackoverflow.com/questions/39045211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271991/"
] | Since this is a rather generalized question, I'm going to suggest a different approach. Mocking / Faking / Stubbing a class or interface that you don't control is generally difficult. Furthermore, this typically leads to replicating someone else's functionality in your mock instance.
A better approach is to isolate interaction with the external library into a wrapping class that you control the interface and implementation of. This will allow you to easily mock/fake/stub *your* interface for testing consumers of your interface.
This still leaves the question of what to do with the isolation layer class. For this, you'll need to do more of an integration test that actually exercises both your wrapping class and the external class. Then, verify that you get the expected behavior from the combination of your class and the external classes you're wrapping. | disclaimer: I work at Typemock.
By using [Typemock Isolator](http://www.typemock.com/) you will be able to mock non-virtual methods and won't need to change your code in order to do so, in this specific example you can fake an instance of `Jeep` and then modify his methods behavior.
Here is an example for a test that mock `Jeep`:
```
[TestMethod]
public void CallFakeJeepType_WillReturnWantedString()
{
var jeep = Isolate.Fake.Instance<Jeep>();
Isolate.WhenCalled(() => jeep.Type).WillReturn("fake jeep");
var result = Jeep.DoSomthing(jeep);
Assert.AreEqual("fake jeep", result);
}
```
note: if the `Jeep.Type` had a setter as well you could use typemock's [True property](https://www.typemock.com/docs?book=Isolator&page=Documentation%2FHtmlDocs%2Fcontrollingpropertybehaviorusingtrueproperties.htm) and the test will look like this
```
var jeep = Isolate.Fake.Instance<Jeep>();
jeep.Type = "fake jeep";
``` |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | You can make Json.Net call the private constructor by marking it with a `[JsonConstructor]` attribute:
```
[JsonConstructor]
private Test()
{
//NOTHING TO INITIALIZE
}
```
Note that the serializer will still use the public setters to populate the object after calling the constructor.
---
Another possible option is to use the `ConstructorHandling` setting:
```
JsonSerializerSettings settings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
Test t = JsonConvert.DeserializeObject<Test>(json, settings);
``` | It doesn't seem like you need to take any extra steps.
Using Json.NET v6.0.8, the following C# program works inside LINQPad:
```
void Main()
{
var o = JsonConvert.DeserializeObject<Test>("{\"Property\":\"Instance\"}");
Debug.Assert(o.Property == "Instance",
"Property value not set when deserializing.");
}
public class Test
{
public string Property { get; set; }
private Test()
{
}
public Test(string propertyValue)
{
Property = propertyValue;
}
}
``` |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | You can make Json.Net call the private constructor by marking it with a `[JsonConstructor]` attribute:
```
[JsonConstructor]
private Test()
{
//NOTHING TO INITIALIZE
}
```
Note that the serializer will still use the public setters to populate the object after calling the constructor.
---
Another possible option is to use the `ConstructorHandling` setting:
```
JsonSerializerSettings settings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
Test t = JsonConvert.DeserializeObject<Test>(json, settings);
``` | No need to create a Serializer setting and give assign ConstructorHandling here. Please remember to define the `[JsonConstructor]` attribute to the private constructor.
I have similar case with abstract BaseNode.cs and its concrete ComputerNode.cs implementation. You can create the classes, copy/paste the code below and do some experiment.
```
public abstract class BaseNode
{
[JsonConstructor] // ctor used when Json Deserializing
protected BaseNode(string Owner, string Name, string Identifier)
{
this.Name = Name;
this.Identifier = Identifier;
}
// ctor called by concrete class.
protected BaseNode(string [] specifications)
{
if (specifications == null)
{
throw new ArgumentNullException();
}
if (specifications.Length == 0)
{
throw new ArgumentException();
}
Name = specifications[0];
Identifier = specifications[1];
}
public string Name{ get; protected set; }
public string Identifier { get; protected set; }
}
public class ComputerNode: BaseNode
{
public string Owner { get; private set; }
[JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization.
private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
{
this.Owner = Owner;
}
public ComputerNode(string[] specifications):base(specifications)
{
Owner = specifications[2];
}
}
```
For JSon Read and Write following code helps -
```
public class Operation<T>
{
public string path;
public Operation()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");
if (File.Exists(path) == false)
{
using (File.Create(path))
{
}
}
this.path = path;
}
public void Write(string path, List<T> nodes)
{
var ser = JsonConvert.SerializeObject(nodes, Formatting.Indented);
File.WriteAllText(path, ser);
}
public List<T> Read(string path)
{
var text = File.ReadAllText(path);
var res = JsonConvert.DeserializeObject<List<T>>(text);
return res;
}
}
```
**All the best!** |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | You can make Json.Net call the private constructor by marking it with a `[JsonConstructor]` attribute:
```
[JsonConstructor]
private Test()
{
//NOTHING TO INITIALIZE
}
```
Note that the serializer will still use the public setters to populate the object after calling the constructor.
---
Another possible option is to use the `ConstructorHandling` setting:
```
JsonSerializerSettings settings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
Test t = JsonConvert.DeserializeObject<Test>(json, settings);
``` | Today the short answer is: Rename the constructor parameter `prop` to `property` and your code will work fine.
```cs
public class Test
{
public string Property { get; }
public Test(string property)
{
Property = property;
}
}
Console.WriteLine(
JsonConvert.DeserializeObject(new Test("Instance")));
```
Newtonsoft.Json supports initializing properties using constructor parameters out of the box, without needing to set any additional attributes or changing any settings. The only constraint is that the parameter name needs to be a case insensitive match to the property name. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | You can make Json.Net call the private constructor by marking it with a `[JsonConstructor]` attribute:
```
[JsonConstructor]
private Test()
{
//NOTHING TO INITIALIZE
}
```
Note that the serializer will still use the public setters to populate the object after calling the constructor.
---
Another possible option is to use the `ConstructorHandling` setting:
```
JsonSerializerSettings settings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
Test t = JsonConvert.DeserializeObject<Test>(json, settings);
``` | I discovered today that having a **public** constructor *that takes parameters* and no ***declared*** unparameterized constructor causes NewtonSoft to attempt to call the public constructor, the only one that it can find, since there is no explicit default constructor, and it cannot apparently find and call the default constructor provided by the framework *unless* it is ***the only constructor***.
Explicitly declaring a default constructor causes NewtonSoft to call the correct (unparameterized) constructor. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | It doesn't seem like you need to take any extra steps.
Using Json.NET v6.0.8, the following C# program works inside LINQPad:
```
void Main()
{
var o = JsonConvert.DeserializeObject<Test>("{\"Property\":\"Instance\"}");
Debug.Assert(o.Property == "Instance",
"Property value not set when deserializing.");
}
public class Test
{
public string Property { get; set; }
private Test()
{
}
public Test(string propertyValue)
{
Property = propertyValue;
}
}
``` | Today the short answer is: Rename the constructor parameter `prop` to `property` and your code will work fine.
```cs
public class Test
{
public string Property { get; }
public Test(string property)
{
Property = property;
}
}
Console.WriteLine(
JsonConvert.DeserializeObject(new Test("Instance")));
```
Newtonsoft.Json supports initializing properties using constructor parameters out of the box, without needing to set any additional attributes or changing any settings. The only constraint is that the parameter name needs to be a case insensitive match to the property name. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | It doesn't seem like you need to take any extra steps.
Using Json.NET v6.0.8, the following C# program works inside LINQPad:
```
void Main()
{
var o = JsonConvert.DeserializeObject<Test>("{\"Property\":\"Instance\"}");
Debug.Assert(o.Property == "Instance",
"Property value not set when deserializing.");
}
public class Test
{
public string Property { get; set; }
private Test()
{
}
public Test(string propertyValue)
{
Property = propertyValue;
}
}
``` | I discovered today that having a **public** constructor *that takes parameters* and no ***declared*** unparameterized constructor causes NewtonSoft to attempt to call the public constructor, the only one that it can find, since there is no explicit default constructor, and it cannot apparently find and call the default constructor provided by the framework *unless* it is ***the only constructor***.
Explicitly declaring a default constructor causes NewtonSoft to call the correct (unparameterized) constructor. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | No need to create a Serializer setting and give assign ConstructorHandling here. Please remember to define the `[JsonConstructor]` attribute to the private constructor.
I have similar case with abstract BaseNode.cs and its concrete ComputerNode.cs implementation. You can create the classes, copy/paste the code below and do some experiment.
```
public abstract class BaseNode
{
[JsonConstructor] // ctor used when Json Deserializing
protected BaseNode(string Owner, string Name, string Identifier)
{
this.Name = Name;
this.Identifier = Identifier;
}
// ctor called by concrete class.
protected BaseNode(string [] specifications)
{
if (specifications == null)
{
throw new ArgumentNullException();
}
if (specifications.Length == 0)
{
throw new ArgumentException();
}
Name = specifications[0];
Identifier = specifications[1];
}
public string Name{ get; protected set; }
public string Identifier { get; protected set; }
}
public class ComputerNode: BaseNode
{
public string Owner { get; private set; }
[JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization.
private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
{
this.Owner = Owner;
}
public ComputerNode(string[] specifications):base(specifications)
{
Owner = specifications[2];
}
}
```
For JSon Read and Write following code helps -
```
public class Operation<T>
{
public string path;
public Operation()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");
if (File.Exists(path) == false)
{
using (File.Create(path))
{
}
}
this.path = path;
}
public void Write(string path, List<T> nodes)
{
var ser = JsonConvert.SerializeObject(nodes, Formatting.Indented);
File.WriteAllText(path, ser);
}
public List<T> Read(string path)
{
var text = File.ReadAllText(path);
var res = JsonConvert.DeserializeObject<List<T>>(text);
return res;
}
}
```
**All the best!** | Today the short answer is: Rename the constructor parameter `prop` to `property` and your code will work fine.
```cs
public class Test
{
public string Property { get; }
public Test(string property)
{
Property = property;
}
}
Console.WriteLine(
JsonConvert.DeserializeObject(new Test("Instance")));
```
Newtonsoft.Json supports initializing properties using constructor parameters out of the box, without needing to set any additional attributes or changing any settings. The only constraint is that the parameter name needs to be a case insensitive match to the property name. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | No need to create a Serializer setting and give assign ConstructorHandling here. Please remember to define the `[JsonConstructor]` attribute to the private constructor.
I have similar case with abstract BaseNode.cs and its concrete ComputerNode.cs implementation. You can create the classes, copy/paste the code below and do some experiment.
```
public abstract class BaseNode
{
[JsonConstructor] // ctor used when Json Deserializing
protected BaseNode(string Owner, string Name, string Identifier)
{
this.Name = Name;
this.Identifier = Identifier;
}
// ctor called by concrete class.
protected BaseNode(string [] specifications)
{
if (specifications == null)
{
throw new ArgumentNullException();
}
if (specifications.Length == 0)
{
throw new ArgumentException();
}
Name = specifications[0];
Identifier = specifications[1];
}
public string Name{ get; protected set; }
public string Identifier { get; protected set; }
}
public class ComputerNode: BaseNode
{
public string Owner { get; private set; }
[JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization.
private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
{
this.Owner = Owner;
}
public ComputerNode(string[] specifications):base(specifications)
{
Owner = specifications[2];
}
}
```
For JSon Read and Write following code helps -
```
public class Operation<T>
{
public string path;
public Operation()
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");
if (File.Exists(path) == false)
{
using (File.Create(path))
{
}
}
this.path = path;
}
public void Write(string path, List<T> nodes)
{
var ser = JsonConvert.SerializeObject(nodes, Formatting.Indented);
File.WriteAllText(path, ser);
}
public List<T> Read(string path)
{
var text = File.ReadAllText(path);
var res = JsonConvert.DeserializeObject<List<T>>(text);
return res;
}
}
```
**All the best!** | I discovered today that having a **public** constructor *that takes parameters* and no ***declared*** unparameterized constructor causes NewtonSoft to attempt to call the public constructor, the only one that it can find, since there is no explicit default constructor, and it cannot apparently find and call the default constructor provided by the framework *unless* it is ***the only constructor***.
Explicitly declaring a default constructor causes NewtonSoft to call the correct (unparameterized) constructor. |
24,243,738 | I need to deserialize json for following class.
```
public class Test
{
public string Property { get; set; }
private Test()
{
//NOTHING TO INITIALIZE
}
public Test(string prop)
{
Property = prop;
}
}
```
I can create an instance of Test like
```
var instance = new Test("Instance");
```
considering my json something like
```
"{ "Property":"Instance" }"
```
How shall I create an object of Test class as my default constructor is private and I am getting object where **Property is NULL**
I am using Newtonsoft Json parser. | 2014/06/16 | [
"https://Stackoverflow.com/questions/24243738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203262/"
] | Today the short answer is: Rename the constructor parameter `prop` to `property` and your code will work fine.
```cs
public class Test
{
public string Property { get; }
public Test(string property)
{
Property = property;
}
}
Console.WriteLine(
JsonConvert.DeserializeObject(new Test("Instance")));
```
Newtonsoft.Json supports initializing properties using constructor parameters out of the box, without needing to set any additional attributes or changing any settings. The only constraint is that the parameter name needs to be a case insensitive match to the property name. | I discovered today that having a **public** constructor *that takes parameters* and no ***declared*** unparameterized constructor causes NewtonSoft to attempt to call the public constructor, the only one that it can find, since there is no explicit default constructor, and it cannot apparently find and call the default constructor provided by the framework *unless* it is ***the only constructor***.
Explicitly declaring a default constructor causes NewtonSoft to call the correct (unparameterized) constructor. |
38,119,661 | I am working on an application where I'm using AppBarLayout with CollapsingToolbarLayout and NestedScrollView. I have successfully implemented this and it is working fine.
Now what i am trying to do is, that on fling(fast swipe up) on the Nestedscrollview it should scroll completely to top. Similarly, on fling(fast swipe down) towards the bottom of the screen, it must scroll all the way to the bottom smoothly. However now, it only gets stuck in between which makes it look ugly.
I have tried many available solutions available here but nothing worked for me. My current setup is below.
```
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:zhy="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="RtlHardcoded">
<android.support.design.widget.AppBarLayout
android:id="@+id/main.appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/main.collapsing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/placeholder"
android:layout_width="match_parent"
android:layout_height="246dp"
android:scaleType="fitXY"
android:tint="#11000000"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.9" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:padding="10dp">
<FrameLayout
android:id="@+id/back_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<ImageView
android:id="@+id/back_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/abc_ic_ab_back_mtrl_am_alpha" />
</FrameLayout>
<FrameLayout
android:id="@+id/frameLayoutheart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:paddingTop="5dp">
<ImageView
android:id="@+id/favbtnicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/heart_profile" />
</FrameLayout>
</FrameLayout>
<FrameLayout
android:id="@+id/main.framelayout.title"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="bottom|center_horizontal"
android:orientation="vertical"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.3">
<LinearLayout
android:id="@+id/main.linearlayout.title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="top"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/profileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:inputType="textNoSuggestions"
android:singleLine="true"
android:text="Ankita arora"
android:textColor="@android:color/white"
android:textSize="25sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/onlinestatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:src="@drawable/online"
android:visibility="visible" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="textCapSentences"
android:text="asdas"
android:textColor="@android:color/white"
android:textSize="13sp" />
<TextView
android:layout_width="4dp"
android:layout_height="4dp"
android:layout_gravity="center"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:background="@drawable/white_dot" />
<TextView
android:id="@+id/sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="textCapSentences"
android:text="asdas"
android:textColor="@android:color/white"
android:textSize="13sp" />
<TextView
android:id="@+id/loc_point"
android:layout_width="4dp"
android:layout_height="4dp"
android:layout_gravity="center"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:background="@drawable/white_dot" />
<TextView
android:id="@+id/loc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="textCapSentences"
android:text="asdas"
android:textColor="@android:color/white"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
app:behavior_overlapTop="10dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
------content--------------
</android.support.v4.widget.NestedScrollView>
<android.support.v7.widget.Toolbar
android:id="@+id/main.toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/pinkColor"
android:visibility="invisible"
app:contentInsetEnd="0dp"
app:contentInsetStart="0dp"
app:layout_anchor="@id/main.framelayout.title"
app:theme="@style/ThemeOverlay.AppCompat.Dark"
app:title="">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/back"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="4dp"
android:src="@drawable/abc_ic_ab_back_mtrl_am_alpha"
android:visibility="invisible" />
<Space
android:layout_width="@dimen/image_final_width"
android:layout_height="@dimen/image_final_width" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/main.textview.title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="@string/quila_name2"
android:textColor="@android:color/white"
android:textSize="20sp" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="-4dp"
android:text="@string/quila_name2"
android:textColor="@android:color/white"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.Toolbar>
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profileimg"
android:layout_width="@dimen/image_width"
android:layout_height="@dimen/image_width"
android:layout_gravity="center_horizontal"
app:border_color="@android:color/white"
app:border_width="2dp"
app:finalHeight="@dimen/image_final_width"
app:finalYPosition="2dp"
app:layout_behavior="com.sdl.apps.yaarri.views.AvatarImageBehavior"
app:startHeight="2dp"
app:startToolbarPosition="2dp"
app:startXPosition="2dp" />
```
One of the most accepted answers, shown below did not work for me either.
[Unable to scroll AppBarLayout and collapsing toolbar with NestedScrollView smoothly](https://stackoverflow.com/questions/34527653/unable-to-scroll-appbarlayout-andcollapsing-toolbar-with-nestedscrollview-smoot) | 2016/06/30 | [
"https://Stackoverflow.com/questions/38119661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298789/"
] | When i was burning my midnight oil this library came like batman
<https://github.com/henrytao-me/smooth-app-bar-layout>
According to which the behavior can be improved by following these steps:
1.Change
```
android.support.design.widget.AppBarLayout
```
to
```
me.henrytao.smoothappbarlayout.SmoothAppBarLayout and set android:id
```
2.Remove
```
app:layout_behavior="@string/appbar_scrolling_view_behavior"
```
3.Add header to your NestedScrollView or RecyclerView
Which actually made it to work like charm.
The final setup looks like
```
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
android:id="@+id/nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="@dimen/app_bar_height">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:text="@string/text_short" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="@string/text_long" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<me.henrytao.smoothappbarlayout.SmoothAppBarLayout
android:id="@+id/smooth_app_bar_layout"
android:layout_width="match_parent"
android:layout_height="@dimen/app_bar_height">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
app:layout_collapseMode="pin"
app:navigationIcon="@drawable/ic_menu_arrow_back"
style="@style/AppStyle.MdToolbar" />
</android.support.design.widget.CollapsingToolbarLayout>
</me.henrytao.smoothappbarlayout.SmoothAppBarLayout>
</android.support.design.widget.CoordinatorLayout>
```
If you still face any issue while implementing this ask here i would love to help and mark this up if this answer helps. | Use support-library 26.0.1 version.
This problem has been solved by google from the support library after version 26.0.0
<https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1> |
288,063 | I was just migrated from a Windows machine to an Apple, which I was told would be seamless, but it's pretty seamy...
My tech (i.e., husband) told me I should drag-and-drop icons to the desktop to create a shortcut, since there's no dropdown-menu item saying "create shortcut." However, all that did was move the file out of its logical spot into the desktop folder. That is absolutely not what I want.
I'm having a hard enough time sorting folders by date or reverse alpha sort. I don't know whether that's even possible using an Apple, but my first problem is the desktop shortcut. For ergo-medical reasons, I definitely don't want to be navigating to my favorite folders, and I don't want to move them out of their logical places. | 2017/06/26 | [
"https://apple.stackexchange.com/questions/288063",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/-1/"
] | Drag an app to the desktop, and hold both `command` and `option` while you release it. This will create a shortcut much like those on Windows.
You can also try activating Spotlight (Apple's name for the search functionality) by pressing `command + space`. You can then type the first letters of the name of the app you need, then press `enter` to launch it. This could be even ergonomically better, as you don't need access to the desktop or to move your hand to the mouse. | If you press Ctrl while clicking in Finder, you will see an option "Create Alias" this is the shortcut you're talking about. It will be created in the same folder you are in at the moment. After you have this, you can drag it to your Desktop. |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | A linked list is not a good data structure for the open set. You have to find the node with the smallest F from it, you can either search through the list in O(n) or insert in sorted position in O(n), either way it's O(n). With a heap it's only O(log n). Updating the G score would remain O(n) (since you have to find the node first), unless you also added a HashTable from nodes to indexes in the heap.
A linked list is also not a good data structure for the closed set, where you need fast "Contains", which is O(n) in a linked list. You should use a HashSet for that. | 1. Find bottlenecks of your implementation using profiler . [ex. jprofiler is easy to use](http://java.dzone.com/articles/jprofiler-your-java-code-could)
2. Use threads in areas where algorithm can run simultaneously.
3. Profile your JavaVM to run faster.
[Allocate more RAM](http://www.wikihow.com/Allocate-More-RAM-to-Minecraft) |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | A linked list is not a good data structure for the open set. You have to find the node with the smallest F from it, you can either search through the list in O(n) or insert in sorted position in O(n), either way it's O(n). With a heap it's only O(log n). Updating the G score would remain O(n) (since you have to find the node first), unless you also added a HashTable from nodes to indexes in the heap.
A linked list is also not a good data structure for the closed set, where you need fast "Contains", which is O(n) in a linked list. You should use a HashSet for that. | a) As mentioned, you should use a heap in A\* - either a basic binary heap or a pairing heap which should be theoretically faster.
b) In larger maps, it always happens that you need some time for the algorithm to run (i.e., when you request a path, it will simply have to take some time). What can be done is to use some local navigation algorithm (e.g., "run directly to the target") while the path computes.
c) If you have reasonable amount of locations (e.g., in a navmesh) and some time at the start of your code, why not to use Floyd-Warshall's algorithm? Using that, you can the information where to go next in O(1). |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | You can optimize the problem by using a different algorithm, the following page illustrates and compares many different aglorihms and heuristics:
* A\*
* IDA\*
* Djikstra
* JumpPoint
* ...
<http://qiao.github.io/PathFinding.js/visual/>
 | From your implementation it seems that you are using naive A\* algorithm. Use following way:-
>
> 1. A\* is algorithm which is implemented using priority queue similar to BFS.
> 2. Heuristic function is evaluated at each node to define its fitness to be selected as next node to be visited.
> 3. As new node is visited its neighboring unvisited nodes are added into queue with its heuristic values as keys.
> 4. Do this till every heuristic value in the queue is less than(or greater) calculated value of goal state.
>
>
> |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | You can optimize the problem by using a different algorithm, the following page illustrates and compares many different aglorihms and heuristics:
* A\*
* IDA\*
* Djikstra
* JumpPoint
* ...
<http://qiao.github.io/PathFinding.js/visual/>
 | a) As mentioned, you should use a heap in A\* - either a basic binary heap or a pairing heap which should be theoretically faster.
b) In larger maps, it always happens that you need some time for the algorithm to run (i.e., when you request a path, it will simply have to take some time). What can be done is to use some local navigation algorithm (e.g., "run directly to the target") while the path computes.
c) If you have reasonable amount of locations (e.g., in a navmesh) and some time at the start of your code, why not to use Floyd-Warshall's algorithm? Using that, you can the information where to go next in O(1). |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | A linked list is not a good data structure for the open set. You have to find the node with the smallest F from it, you can either search through the list in O(n) or insert in sorted position in O(n), either way it's O(n). With a heap it's only O(log n). Updating the G score would remain O(n) (since you have to find the node first), unless you also added a HashTable from nodes to indexes in the heap.
A linked list is also not a good data structure for the closed set, where you need fast "Contains", which is O(n) in a linked list. You should use a HashSet for that. | I built a new pathfinding algorithm. called Fast\* or Fastaer, It is a BFS like A\* but is faster and efficient than A\*, the accuracy is 90% A\*. please see this link for info and demo.
<https://drbendanilloportfolio.wordpress.com/2015/08/14/fastaer-pathfinder/>
It has a fast greedy line tracer, to make path straighter.
The demo file has it all. Check Task manager when using the demo for performance metrics. So far upon building this the profiler results of this has maximum surviving generation of 4 and low to nil GC time. |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | You can optimize the problem by using a different algorithm, the following page illustrates and compares many different aglorihms and heuristics:
* A\*
* IDA\*
* Djikstra
* JumpPoint
* ...
<http://qiao.github.io/PathFinding.js/visual/>
 | I built a new pathfinding algorithm. called Fast\* or Fastaer, It is a BFS like A\* but is faster and efficient than A\*, the accuracy is 90% A\*. please see this link for info and demo.
<https://drbendanilloportfolio.wordpress.com/2015/08/14/fastaer-pathfinder/>
It has a fast greedy line tracer, to make path straighter.
The demo file has it all. Check Task manager when using the demo for performance metrics. So far upon building this the profiler results of this has maximum surviving generation of 4 and low to nil GC time. |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | You can optimize the problem by using a different algorithm, the following page illustrates and compares many different aglorihms and heuristics:
* A\*
* IDA\*
* Djikstra
* JumpPoint
* ...
<http://qiao.github.io/PathFinding.js/visual/>
 | 1. Find bottlenecks of your implementation using profiler . [ex. jprofiler is easy to use](http://java.dzone.com/articles/jprofiler-your-java-code-could)
2. Use threads in areas where algorithm can run simultaneously.
3. Profile your JavaVM to run faster.
[Allocate more RAM](http://www.wikihow.com/Allocate-More-RAM-to-Minecraft) |
21,161,430 | Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`?
For example, the simplest way is:
```
// generate url
Link link = linkSource.createPageRenderLink("SomePageLink");
String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue;
// get info stream from url
HttpGet httpGet = new HttpGet(urlAsString);
httpGet.addHeader("cookie", request.getHeader("cookie"));
HttpResponse response = new DefaultHttpClient().execute(httpGet);
InputStream is = response.getEntity().getContent();
...
```
But it seems it must be some more easy method how to archive the same result. Any ideas? | 2014/01/16 | [
"https://Stackoverflow.com/questions/21161430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479414/"
] | From your implementation it seems that you are using naive A\* algorithm. Use following way:-
>
> 1. A\* is algorithm which is implemented using priority queue similar to BFS.
> 2. Heuristic function is evaluated at each node to define its fitness to be selected as next node to be visited.
> 3. As new node is visited its neighboring unvisited nodes are added into queue with its heuristic values as keys.
> 4. Do this till every heuristic value in the queue is less than(or greater) calculated value of goal state.
>
>
> | a) As mentioned, you should use a heap in A\* - either a basic binary heap or a pairing heap which should be theoretically faster.
b) In larger maps, it always happens that you need some time for the algorithm to run (i.e., when you request a path, it will simply have to take some time). What can be done is to use some local navigation algorithm (e.g., "run directly to the target") while the path computes.
c) If you have reasonable amount of locations (e.g., in a navmesh) and some time at the start of your code, why not to use Floyd-Warshall's algorithm? Using that, you can the information where to go next in O(1). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.