qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
`timeIntervalSinceReferenceDate` is perfectly fine.
However, unless it's a long-running method, this won't bear much fruit. Execution times can vary wildly when you're talking about a few millisecond executions. If your thread/process gets preempted mid-way through, you'll have non-deterministic spikes. Essentially, your sample size is too small. Either use a profiler or run 100,000 iterations to get total time and divide by 100,000 to get average run-time.
|
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation:
---
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this:
[Timing things in Objective-C: A stopwatch](http://metal-sole.com/2012/01/24/timing-things-in-objective-c-a-stopwatch/)
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
```
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
```
And you end up with:
```
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
```
in the log...
Again, check out my post for a little more or download it here:
[MMStopwatch.zip](http://metal-sole.com/wp-content/uploads/2012/01/MMStopwatch.zip)
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
Actually, `+[NSDate timeIntervalSinceReferenceDate]` returns an `NSTimeInterval`, which is a typedef for a double. The docs say
>
> NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.
>
>
>
So it's safe to use for millisecond-precision timing. I do so all the time.
|
@bladnman I love your stopwatch thing.. I use it all the time.. Here's a little block I wrote that eliminates the need for the closing call, and makes it even EASIER (if that even seemed possible) to use, lol.
```
+(void)stopwatch:(NSString*)name timing:(void(^)())block {
[MMStopwatch start:name];
block();
[MMStopwatch stop: name];
}
```
then you can just call it wherever..
```
[MMStopwatch stopwatch:@"slowAssFunction" timing:^{
NSLog(@"%@",@"someLongAssFunction");
}];
```
↪`someLongAssFunction`
```
-> Stopwatch: [slowAssFunction] runtime:[0.054435]
```
You should post that sucker to github - so people can find it easily / contribute, etc. it's great. thanks.
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation:
---
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this:
[Timing things in Objective-C: A stopwatch](http://metal-sole.com/2012/01/24/timing-things-in-objective-c-a-stopwatch/)
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
```
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
```
And you end up with:
```
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
```
in the log...
Again, check out my post for a little more or download it here:
[MMStopwatch.zip](http://metal-sole.com/wp-content/uploads/2012/01/MMStopwatch.zip)
|
@bladnman I love your stopwatch thing.. I use it all the time.. Here's a little block I wrote that eliminates the need for the closing call, and makes it even EASIER (if that even seemed possible) to use, lol.
```
+(void)stopwatch:(NSString*)name timing:(void(^)())block {
[MMStopwatch start:name];
block();
[MMStopwatch stop: name];
}
```
then you can just call it wherever..
```
[MMStopwatch stopwatch:@"slowAssFunction" timing:^{
NSLog(@"%@",@"someLongAssFunction");
}];
```
↪`someLongAssFunction`
```
-> Stopwatch: [slowAssFunction] runtime:[0.054435]
```
You should post that sucker to github - so people can find it easily / contribute, etc. it's great. thanks.
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
*Do not use `NSDate` for this.* You're loosing a lot of precision to call methods and instantiate objects, maybe even releasing something internal. You just don't have enough control.
Use either `time.h` or as [Stephen Canon](https://stackoverflow.com/questions/1615998/rudimentary-ways-to-measure-execution-time-of-a-method/1616376#1616376) suggested `mach/mach_time.h`. They are both much more accurate.
The best way to do this is to fire up Instruments or Shark, attach them to your process (works even if it's already running) and let them measure the time a method takes.
After you're familiar with it this takes even less time than any put-in-mach-time-functions-and-recompile-the-whole-application solution. You even get a lot of information extra. I wouldn't settle for anything less.
|
If you're trying to tune your code's performance, you would do better to use Instruments or Shark to get an overall picture of where your app is spending its time.
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
For very fine-grained timings on OS X, I use `mach_absolute_time( )`, which is defined in `<mach/mach_time.h>`. You can use it as follows:
```
#include <mach/mach_time.h>
#include <stdint.h>
static double ticksToNanoseconds = 0.0;
uint64_t startTime = mach_absolute_time( );
// Do some stuff you want to time here
uint64_t endTime = mach_absolute_time( );
// Elapsed time in mach time units
uint64_t elapsedTime = endTime - startTime;
// The first time we get here, ask the system
// how to convert mach time units to nanoseconds
if (0.0 == ticksToNanoseconds) {
mach_timebase_info_data_t timebase;
// to be completely pedantic, check the return code of this next call.
mach_timebase_info(&timebase);
ticksToNanoseconds = (double)timebase.numer / timebase.denom;
}
double elapsedTimeInNanoseconds = elapsedTime * ticksToNanoseconds;
```
|
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation:
---
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this:
[Timing things in Objective-C: A stopwatch](http://metal-sole.com/2012/01/24/timing-things-in-objective-c-a-stopwatch/)
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
```
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
```
And you end up with:
```
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
```
in the log...
Again, check out my post for a little more or download it here:
[MMStopwatch.zip](http://metal-sole.com/wp-content/uploads/2012/01/MMStopwatch.zip)
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
If you're trying to tune your code's performance, you would do better to use Instruments or Shark to get an overall picture of where your app is spending its time.
|
@bladnman I love your stopwatch thing.. I use it all the time.. Here's a little block I wrote that eliminates the need for the closing call, and makes it even EASIER (if that even seemed possible) to use, lol.
```
+(void)stopwatch:(NSString*)name timing:(void(^)())block {
[MMStopwatch start:name];
block();
[MMStopwatch stop: name];
}
```
then you can just call it wherever..
```
[MMStopwatch stopwatch:@"slowAssFunction" timing:^{
NSLog(@"%@",@"someLongAssFunction");
}];
```
↪`someLongAssFunction`
```
-> Stopwatch: [slowAssFunction] runtime:[0.054435]
```
You should post that sucker to github - so people can find it easily / contribute, etc. it's great. thanks.
|
1,615,998 |
What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?
NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.
Is there an equivalent version in objective-c/CocoaTouch?
|
2009/10/23
|
[
"https://Stackoverflow.com/questions/1615998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119382/"
] |
Actually, `+[NSDate timeIntervalSinceReferenceDate]` returns an `NSTimeInterval`, which is a typedef for a double. The docs say
>
> NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.
>
>
>
So it's safe to use for millisecond-precision timing. I do so all the time.
|
I will repost my answer from another post here. Note that my admittedly simple solution to this complex problem uses NSDate and NSTimeInterval as its foundation:
---
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this:
[Timing things in Objective-C: A stopwatch](http://metal-sole.com/2012/01/24/timing-things-in-objective-c-a-stopwatch/)
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
```
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
```
And you end up with:
```
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
```
in the log...
Again, check out my post for a little more or download it here:
[MMStopwatch.zip](http://metal-sole.com/wp-content/uploads/2012/01/MMStopwatch.zip)
|
11,299,663 |
I know that this line of code will make the cell text-wrap:
```
$objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setWrapText(true);
```
'D1' being the chosen cell.
Instead of using this code for every cell I need wrapped, is there a way to make the entire Excel Worksheet automatically wrap everything?
Or is there a better practice technique to use for specified columns?
|
2012/07/02
|
[
"https://Stackoverflow.com/questions/11299663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389807/"
] |
Apply to a range:
```
$objPHPExcel->getActiveSheet()->getStyle('D1:E999')
->getAlignment()->setWrapText(true);
```
Apply to a column
```
$objPHPExcel->getActiveSheet()->getStyle('D1:D'.$objPHPExcel->getActiveSheet()->getHighestRow())
->getAlignment()->setWrapText(true);
```
|
Apply to column
```
$highestRow = $$objPHPExcel->getActiveSheet()->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++){
$sheet->getStyle("D$row")->getAlignment()->setWrapText(true);
}
```
|
11,299,663 |
I know that this line of code will make the cell text-wrap:
```
$objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setWrapText(true);
```
'D1' being the chosen cell.
Instead of using this code for every cell I need wrapped, is there a way to make the entire Excel Worksheet automatically wrap everything?
Or is there a better practice technique to use for specified columns?
|
2012/07/02
|
[
"https://Stackoverflow.com/questions/11299663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389807/"
] |
Apply to a range:
```
$objPHPExcel->getActiveSheet()->getStyle('D1:E999')
->getAlignment()->setWrapText(true);
```
Apply to a column
```
$objPHPExcel->getActiveSheet()->getStyle('D1:D'.$objPHPExcel->getActiveSheet()->getHighestRow())
->getAlignment()->setWrapText(true);
```
|
```
$objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
```
|
11,299,663 |
I know that this line of code will make the cell text-wrap:
```
$objPHPExcel->getActiveSheet()->getStyle('D1')->getAlignment()->setWrapText(true);
```
'D1' being the chosen cell.
Instead of using this code for every cell I need wrapped, is there a way to make the entire Excel Worksheet automatically wrap everything?
Or is there a better practice technique to use for specified columns?
|
2012/07/02
|
[
"https://Stackoverflow.com/questions/11299663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389807/"
] |
```
$objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
```
|
Apply to column
```
$highestRow = $$objPHPExcel->getActiveSheet()->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++){
$sheet->getStyle("D$row")->getAlignment()->setWrapText(true);
}
```
|
10,779,130 |
```
enemyBlobArray = [[NSMutableArray alloc] init];
for(int i = 0; i < kEnemyCount; i++) {
[enemyArray addObject:[SpriteHelpers setupAnimatedSprite:self.view numFrames:3 withFilePrefix:@"greenbox" withDuration:((CGFloat)(arc4random()%2)/3 + 0.5) ofType:@"png" withValue:0]];
}
enemyView = [enemyArray objectAtIndex:0];
```
I am trying to make objects appear on screen from this array.
I get an error message saying that the object I add cannot be `nil`. I don't know why it's `nil`, though.
|
2012/05/28
|
[
"https://Stackoverflow.com/questions/10779130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1420896/"
] |
The method `setupAnimatedSprite:numFrames:withFilePrefix:withDuration:ofType:withValue:` is returning nil. So the problem is somewhere inside that method. Since we don't have the code for that method, I couldn't tell you what it might be.
|
According to the provided code, you make no mention of the allocation and initialization of "enemyArray"; however, you created a mutable array called "enemyBlobArray" which is never utilized within the provided code. Perhaps this is a simple issue of misspelling of a variable name.
|
806,060 |
Is it possible to define host variables for all hosts using a dynamic inventory?
Currently I can produce an inventory which allows me to assign variables to specific hosts, but what I want to achieve is something like this:
```
{
"_meta": {
"hostvars": {
"all": {
"my_global_random_variable": "global_random_value"
}
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
```
Which should allow me to access the "my\_global\_random\_variable" from any context as if I would have defined that variable in a vars file.
|
2016/09/29
|
[
"https://serverfault.com/questions/806060",
"https://serverfault.com",
"https://serverfault.com/users/235801/"
] |
I ended up using a lookup plugin instead of the inventory to retrieve my variables.
More information on lookups: <https://docs.ansible.com/ansible/playbooks_lookups.html>
|
Variables set by `dynamic inventory` are `inventory variables`. When a variable is set in multiple places Ansible set the value following [variable precedence](http://docs.ansible.com/ansible/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable):
>
>
> ```
> role defaults [1]
> inventory vars [2]
> inventory group_vars
> inventory host_vars
> playbook group_vars
> playbook host_vars
> host facts
> play vars
> play vars_prompt
> play vars_files
> registered vars
> set_facts
> role and include vars
> block vars (only for tasks in block)
> task vars (only for the task)
> extra vars (always win precedence)
>
> ```
>
>
Variables set in inventory have a relativ low precendence. So there is no need to use `dynamic inventory` to achive this. Just set the variable for example on role level.
|
806,060 |
Is it possible to define host variables for all hosts using a dynamic inventory?
Currently I can produce an inventory which allows me to assign variables to specific hosts, but what I want to achieve is something like this:
```
{
"_meta": {
"hostvars": {
"all": {
"my_global_random_variable": "global_random_value"
}
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
```
Which should allow me to access the "my\_global\_random\_variable" from any context as if I would have defined that variable in a vars file.
|
2016/09/29
|
[
"https://serverfault.com/questions/806060",
"https://serverfault.com",
"https://serverfault.com/users/235801/"
] |
Variables set by `dynamic inventory` are `inventory variables`. When a variable is set in multiple places Ansible set the value following [variable precedence](http://docs.ansible.com/ansible/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable):
>
>
> ```
> role defaults [1]
> inventory vars [2]
> inventory group_vars
> inventory host_vars
> playbook group_vars
> playbook host_vars
> host facts
> play vars
> play vars_prompt
> play vars_files
> registered vars
> set_facts
> role and include vars
> block vars (only for tasks in block)
> task vars (only for the task)
> extra vars (always win precedence)
>
> ```
>
>
Variables set in inventory have a relativ low precendence. So there is no need to use `dynamic inventory` to achive this. Just set the variable for example on role level.
|
I wanted to do this and seems to work with the following (adapted for your example):
```
{
"all": {
"vars": {
"my_global_random_variable": "global_random_value"
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
```
Possibly not best practice but keeps things simple.
|
806,060 |
Is it possible to define host variables for all hosts using a dynamic inventory?
Currently I can produce an inventory which allows me to assign variables to specific hosts, but what I want to achieve is something like this:
```
{
"_meta": {
"hostvars": {
"all": {
"my_global_random_variable": "global_random_value"
}
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
```
Which should allow me to access the "my\_global\_random\_variable" from any context as if I would have defined that variable in a vars file.
|
2016/09/29
|
[
"https://serverfault.com/questions/806060",
"https://serverfault.com",
"https://serverfault.com/users/235801/"
] |
I ended up using a lookup plugin instead of the inventory to retrieve my variables.
More information on lookups: <https://docs.ansible.com/ansible/playbooks_lookups.html>
|
I wanted to do this and seems to work with the following (adapted for your example):
```
{
"all": {
"vars": {
"my_global_random_variable": "global_random_value"
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
```
Possibly not best practice but keeps things simple.
|
48,345,049 |
According to most NVidia documentation CUDA cores are scalar processors and should only execute scalar operations, that will get vectorized to 32-component SIMT warps.
But OpenCL has vector types like for example `uchar8`.It has the same size as `ulong` (64 bit), which can be processed by a single scalar core. If I do operations on a `uchar8` vector (for example component-wise addition), will this also map to an instruction on a single core?
If there are 1024 work items in a block (work group), and each work items processes a `uchar8`, will this effectively process 8120 `uchar` in parallel?
**Edit:**
My question was if on CUDA architectures specifically (independently of OpenCL), there are some vector instructions available in "scalar" cores. Because if the core is already capable of handling a 32-bit type, it would be reasonable if it can also handle addition of a 32-bit `uchar4` for example, especially since vector operations are often used in computer graphics.
|
2018/01/19
|
[
"https://Stackoverflow.com/questions/48345049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4108376/"
] |
CUDA has "built-in" (i.e. predefined) vector types up to a size of 4 for 4-byte quantities (e.g. `int4`) and up to a size of 2 for 8-byte quantities (e.g. `double2`). A CUDA thread has a maximum read/write transaction size of 16 bytes, so these particular size choices tend to line up with [that maximum](http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-memory-accesses).
These are exposed as typical structures, so you can reference for example `.x` to access just the first element of a vector type.
Unlike OpenCL, CUDA does not provide built-in operations ("overloads") for basic arithmetic e.g. `+`, `-`, etc. for element-wise operations on these vector types. There's no particular reason you couldn't provide such overloads yourself. Likewise, if you wanted a `uchar8` you could easily provide a structure definition for such, as well as any desired operator overloads. These could probably be implemented just as you would expect for ordinary C++ code.
Probably an underlying question is, then, what is the difference in implementation between CUDA and OpenCL in this regard? If I operate on a `uchar8`, e.g.
```
uchar8 v1 = {...};
uchar8 v2 = {...};
uchar8 r = v1 + v2;
```
what will the difference be in terms of machine performance (or low-level code generation) between OpenCL and CUDA?
Probably not much, for a CUDA-capable GPU. A CUDA core (i.e. the underlying ALU) does not have direct native support for such an operation on a `uchar8`, and furthermore, if you write your own C++ compliant overload, you're probably going to use C++ semantics for this which will inherently be serial:
```
r.x = v1.x + v2.x;
r.y = v1.y + v2.y;
...
```
So this will decompose into a sequence of operations performed on the CUDA core (or in the appropriate integer unit within the CUDA SM). Since the NVIDIA GPU hardware doesn't provide any direct support for an 8-way uchar add within a single core/clock/instruction, there's really no way OpenCL (as implemented on a NVIDIA GPU) could be much different. At a low level, the underlying machine code is going to be a sequence of operations, not a single instruction.
As an aside, CUDA (or PTX, or CUDA intrinsics) does provide for a limited amount of vector operations within a single core/thread/instruction. Some examples of this are:
1. a limited set of "native" ["video" SIMD instructions](http://docs.nvidia.com/cuda/parallel-thread-execution/index.html#video-instructions). These instructions are per-thread, so if used, they allow for "native" support of up to 4x32 = 128 (8-bit) operands per warp, although the operands must be properly packed into 32-bit registers. You can access these from C++ directly via a set of built-in [intrinsics](http://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__SIMD.html#group__CUDA__MATH__INTRINSIC__SIMD). (A CUDA *warp* is a set of 32 threads, and is the fundamental unit of lockstep parallel execution and scheduling on a CUDA capable GPU.)
2. a vector (SIMD) multiply-accumulate operation, which is not directly translatable to a single particular elementwise operation overload, the so-called int8 dp2a and dp4a instructions. int8 here is somewhat misleading. It does not refer to an int8 vector type but rather a packed arrangement of 4 8-bit integer quantities in a single 32-bit word/register. Again, these are accessible via [intrinsics](https://devblogs.nvidia.com/mixed-precision-programming-cuda-8/).
3. 16-bit floating point is natively supported via `half2` vector type in cc 5.3 and higher GPUs, for certain operations.
4. The new Volta tensorCore is something vaguely like a SIMD-per-thread operation, but it operates (warp-wide) on a set of 16x16 input matrices producing a 16x16 matrix result.
Even with a smart OpenCL compiler that could map certain vector operations into the various operations "natively" supported by the hardware, it would not be complete coverage. There is no operational support for an 8-wide vector (e.g. `uchar8`) on a single core/thread, in a single instruction, to pick one example. So some serialization would be necessary. In practice, I don't think the OpenCL compiler from NVIDIA is that smart, so my expectation is that you would find such per-thread vector operations fully serialized, if you studied the machine code.
In CUDA, you could provide your own overload for *certain* operations and vector types, that could be represented approximately in a single instruction. For example a `uchar4` add could be performed "natively" with the [\_\_vadd4() intrinsic](http://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__SIMD.html#group__CUDA__MATH__INTRINSIC__SIMD_1g985e19defa6381f163004ac5dd6e68e8) (perhaps included in your implementation of an operator overload.) Likewise, if you are writing your own operator overload, I don't think it would be difficult to perform a `uchar8` elementwise vector add using two `__vadd4()` instructions.
|
>
> If I do operations on a uchar8 vector (for example component-wise addition), will this also map to an instruction on a single core?
>
>
>
AFAIK it'll always be on a single core (instructions from a single kernel / workitem don't cross cores, except special instructions like barriers), but it may be more than one instruction. This depends on whether your hardware support operations on uchar8 natively. If it does not, then uchar8 will be broken up to as many pieces as required, and each piece will be processed with a separate instruction.
OpenCL is very "generic" in the sense that it supports many different vector type/size combos, but real-world hardware usually only implements some vector type/size combinations. You can query OpenCL devices for "preferred vector size" which should tell you what's the most efficient for that hardware.
|
686,737 |
I'm using StartSSL which , after you proove who you say you are, provides a certificate which I can install to authenticate myself. I have some SSL certificates associated with this account.
I've bought a new server, and I need to move the certificates over, but I'm failing.
On my 'old W28k server', I went into Firefox, and viewed the certificates. I then exported them all, zipped them up and emailed them to my new W2012 server.
On my new server, I've registered with StartSSL and can authenticate, but now realise I have to use my old certificate.
When I open the certificate it shows I can install it, which I do, and the wizard gives the option to let it choose the best place to install it.
I've done, but when I now go to StartSLL I can't get authenticated.
Have I installed the certification incorrectly?
|
2015/04/30
|
[
"https://serverfault.com/questions/686737",
"https://serverfault.com",
"https://serverfault.com/users/284558/"
] |
You need to export the certificate as a whole - not just the certificate itself but also the private key, as pointed out by @EEAA in the comments below your question.
As per [the MS documentation on TechNet](https://technet.microsoft.com/en-us/library/cc754329.aspx):
>
> 1. Open the Certificates snap-in for a user, computer, or service.
> 2. In the console tree under the logical store that contains the certificate to export, click Certificates.
> 3. In the details pane, click the certificate that you want to export.
> 4. On the Action menu, point to All Tasks, and then click Export.
> 5. In the Certificate Export Wizard, click Yes, export the private key. (This option will appear only if the private key is marked as
> exportable and you have access to the private key.)
> 6. Under Export File Format, do any of the following, and then click Next. To include all certificates in the certification path, select
> the Include all certificates in the certification path if possible
> check box.To delete the private key if the export is successful,
> select the Delete the private key if the export is successful check
> box.To export the certificate's extended properties, select the Export
> all extended properties check box.
> 7. In Password, type a password to encrypt the private key you are exporting. In Confirm password, type the same password again, and then
> click Next.
> 8. In File name, type a file name and path for the PKCS #12 file that will store the exported certificate and private key. Click Next, and
> then click Finish.
>
>
>
You more or less need to reverse these steps on the new server to import the certificate and private key there.
**EDIT:** it's also worth noting, that since you mention in your question that you attempted exporting these personal identification certificates from Firefox, that you should identify whether or not you did indeed import the personal identification certificate to Firefox only or also to the system's certificate store (for use in IE and/or Chrome for example, whereas Firefox uses its own certificate store).
Finally you might find it useful to use the [StartSSL FAQ](https://www.startssl.com/?app=25) for such issues in future as a first-port-of-call. To back up the client certificate from Firefox, follow these steps [from the StartSSL FAQ page](https://www.startssl.com/?app=25#4):
>
> Select "Preferences|Options" -> "Advanced" -> "Certificates" -> "View
> Certificates", choose the "Your Certificates" tab and locate your
> client certificate from the list. The certificate will be listed under
> StartCom. Select the certificate and click on "Backup", choose a name
> for this backup file, provide a password and save it at a known
> location. Now you should either burn this file to a CD ROM or save it
> on a USB stick or smart card. Thereafter delete this file from your
> computer.
>
>
>
|
If you could export full certificates with private keys from a browser that would make them pointless!
You need to use the export feature ON the server, and then import on your new server.
See these guides:
<https://technet.microsoft.com/en-us/library/cc771103.aspx>
|
686,737 |
I'm using StartSSL which , after you proove who you say you are, provides a certificate which I can install to authenticate myself. I have some SSL certificates associated with this account.
I've bought a new server, and I need to move the certificates over, but I'm failing.
On my 'old W28k server', I went into Firefox, and viewed the certificates. I then exported them all, zipped them up and emailed them to my new W2012 server.
On my new server, I've registered with StartSSL and can authenticate, but now realise I have to use my old certificate.
When I open the certificate it shows I can install it, which I do, and the wizard gives the option to let it choose the best place to install it.
I've done, but when I now go to StartSLL I can't get authenticated.
Have I installed the certification incorrectly?
|
2015/04/30
|
[
"https://serverfault.com/questions/686737",
"https://serverfault.com",
"https://serverfault.com/users/284558/"
] |
You need to export the certificate as a whole - not just the certificate itself but also the private key, as pointed out by @EEAA in the comments below your question.
As per [the MS documentation on TechNet](https://technet.microsoft.com/en-us/library/cc754329.aspx):
>
> 1. Open the Certificates snap-in for a user, computer, or service.
> 2. In the console tree under the logical store that contains the certificate to export, click Certificates.
> 3. In the details pane, click the certificate that you want to export.
> 4. On the Action menu, point to All Tasks, and then click Export.
> 5. In the Certificate Export Wizard, click Yes, export the private key. (This option will appear only if the private key is marked as
> exportable and you have access to the private key.)
> 6. Under Export File Format, do any of the following, and then click Next. To include all certificates in the certification path, select
> the Include all certificates in the certification path if possible
> check box.To delete the private key if the export is successful,
> select the Delete the private key if the export is successful check
> box.To export the certificate's extended properties, select the Export
> all extended properties check box.
> 7. In Password, type a password to encrypt the private key you are exporting. In Confirm password, type the same password again, and then
> click Next.
> 8. In File name, type a file name and path for the PKCS #12 file that will store the exported certificate and private key. Click Next, and
> then click Finish.
>
>
>
You more or less need to reverse these steps on the new server to import the certificate and private key there.
**EDIT:** it's also worth noting, that since you mention in your question that you attempted exporting these personal identification certificates from Firefox, that you should identify whether or not you did indeed import the personal identification certificate to Firefox only or also to the system's certificate store (for use in IE and/or Chrome for example, whereas Firefox uses its own certificate store).
Finally you might find it useful to use the [StartSSL FAQ](https://www.startssl.com/?app=25) for such issues in future as a first-port-of-call. To back up the client certificate from Firefox, follow these steps [from the StartSSL FAQ page](https://www.startssl.com/?app=25#4):
>
> Select "Preferences|Options" -> "Advanced" -> "Certificates" -> "View
> Certificates", choose the "Your Certificates" tab and locate your
> client certificate from the list. The certificate will be listed under
> StartCom. Select the certificate and click on "Backup", choose a name
> for this backup file, provide a password and save it at a known
> location. Now you should either burn this file to a CD ROM or save it
> on a USB stick or smart card. Thereafter delete this file from your
> computer.
>
>
>
|
So, as far as I understand, you don't ask about importing/exporting SSL Certificates in gerneral (e.g. the ones you use for IIS) but the client authentication certificate from StartSSL?
In that case, you have to re-import it into Firefox. To do this, got to Options --> Advanced --> Certificates --> View Certificates --> on the Tab "My Certificates" --> Import
You can then log in to StartSSL.
Hope this helps...
|
686,737 |
I'm using StartSSL which , after you proove who you say you are, provides a certificate which I can install to authenticate myself. I have some SSL certificates associated with this account.
I've bought a new server, and I need to move the certificates over, but I'm failing.
On my 'old W28k server', I went into Firefox, and viewed the certificates. I then exported them all, zipped them up and emailed them to my new W2012 server.
On my new server, I've registered with StartSSL and can authenticate, but now realise I have to use my old certificate.
When I open the certificate it shows I can install it, which I do, and the wizard gives the option to let it choose the best place to install it.
I've done, but when I now go to StartSLL I can't get authenticated.
Have I installed the certification incorrectly?
|
2015/04/30
|
[
"https://serverfault.com/questions/686737",
"https://serverfault.com",
"https://serverfault.com/users/284558/"
] |
You need to export the certificate as a whole - not just the certificate itself but also the private key, as pointed out by @EEAA in the comments below your question.
As per [the MS documentation on TechNet](https://technet.microsoft.com/en-us/library/cc754329.aspx):
>
> 1. Open the Certificates snap-in for a user, computer, or service.
> 2. In the console tree under the logical store that contains the certificate to export, click Certificates.
> 3. In the details pane, click the certificate that you want to export.
> 4. On the Action menu, point to All Tasks, and then click Export.
> 5. In the Certificate Export Wizard, click Yes, export the private key. (This option will appear only if the private key is marked as
> exportable and you have access to the private key.)
> 6. Under Export File Format, do any of the following, and then click Next. To include all certificates in the certification path, select
> the Include all certificates in the certification path if possible
> check box.To delete the private key if the export is successful,
> select the Delete the private key if the export is successful check
> box.To export the certificate's extended properties, select the Export
> all extended properties check box.
> 7. In Password, type a password to encrypt the private key you are exporting. In Confirm password, type the same password again, and then
> click Next.
> 8. In File name, type a file name and path for the PKCS #12 file that will store the exported certificate and private key. Click Next, and
> then click Finish.
>
>
>
You more or less need to reverse these steps on the new server to import the certificate and private key there.
**EDIT:** it's also worth noting, that since you mention in your question that you attempted exporting these personal identification certificates from Firefox, that you should identify whether or not you did indeed import the personal identification certificate to Firefox only or also to the system's certificate store (for use in IE and/or Chrome for example, whereas Firefox uses its own certificate store).
Finally you might find it useful to use the [StartSSL FAQ](https://www.startssl.com/?app=25) for such issues in future as a first-port-of-call. To back up the client certificate from Firefox, follow these steps [from the StartSSL FAQ page](https://www.startssl.com/?app=25#4):
>
> Select "Preferences|Options" -> "Advanced" -> "Certificates" -> "View
> Certificates", choose the "Your Certificates" tab and locate your
> client certificate from the list. The certificate will be listed under
> StartCom. Select the certificate and click on "Backup", choose a name
> for this backup file, provide a password and save it at a known
> location. Now you should either burn this file to a CD ROM or save it
> on a USB stick or smart card. Thereafter delete this file from your
> computer.
>
>
>
|
You can export both the cert, and the key using this procedure:
<https://technet.microsoft.com/en-us/library/cc754329.aspx> One thing to note however is
"A private key is exportable only when it is specified in the certificate request"
If the key is exportable the cert export wizard will give you the option. If its non-exportable there are a few tools (jailbreak for non-64 bit systems, and mimkatz) that say they can export non exportable keys but I have no experience with them so I have no clue how well they work.
|
686,737 |
I'm using StartSSL which , after you proove who you say you are, provides a certificate which I can install to authenticate myself. I have some SSL certificates associated with this account.
I've bought a new server, and I need to move the certificates over, but I'm failing.
On my 'old W28k server', I went into Firefox, and viewed the certificates. I then exported them all, zipped them up and emailed them to my new W2012 server.
On my new server, I've registered with StartSSL and can authenticate, but now realise I have to use my old certificate.
When I open the certificate it shows I can install it, which I do, and the wizard gives the option to let it choose the best place to install it.
I've done, but when I now go to StartSLL I can't get authenticated.
Have I installed the certification incorrectly?
|
2015/04/30
|
[
"https://serverfault.com/questions/686737",
"https://serverfault.com",
"https://serverfault.com/users/284558/"
] |
If you could export full certificates with private keys from a browser that would make them pointless!
You need to use the export feature ON the server, and then import on your new server.
See these guides:
<https://technet.microsoft.com/en-us/library/cc771103.aspx>
|
You can export both the cert, and the key using this procedure:
<https://technet.microsoft.com/en-us/library/cc754329.aspx> One thing to note however is
"A private key is exportable only when it is specified in the certificate request"
If the key is exportable the cert export wizard will give you the option. If its non-exportable there are a few tools (jailbreak for non-64 bit systems, and mimkatz) that say they can export non exportable keys but I have no experience with them so I have no clue how well they work.
|
686,737 |
I'm using StartSSL which , after you proove who you say you are, provides a certificate which I can install to authenticate myself. I have some SSL certificates associated with this account.
I've bought a new server, and I need to move the certificates over, but I'm failing.
On my 'old W28k server', I went into Firefox, and viewed the certificates. I then exported them all, zipped them up and emailed them to my new W2012 server.
On my new server, I've registered with StartSSL and can authenticate, but now realise I have to use my old certificate.
When I open the certificate it shows I can install it, which I do, and the wizard gives the option to let it choose the best place to install it.
I've done, but when I now go to StartSLL I can't get authenticated.
Have I installed the certification incorrectly?
|
2015/04/30
|
[
"https://serverfault.com/questions/686737",
"https://serverfault.com",
"https://serverfault.com/users/284558/"
] |
So, as far as I understand, you don't ask about importing/exporting SSL Certificates in gerneral (e.g. the ones you use for IIS) but the client authentication certificate from StartSSL?
In that case, you have to re-import it into Firefox. To do this, got to Options --> Advanced --> Certificates --> View Certificates --> on the Tab "My Certificates" --> Import
You can then log in to StartSSL.
Hope this helps...
|
You can export both the cert, and the key using this procedure:
<https://technet.microsoft.com/en-us/library/cc754329.aspx> One thing to note however is
"A private key is exportable only when it is specified in the certificate request"
If the key is exportable the cert export wizard will give you the option. If its non-exportable there are a few tools (jailbreak for non-64 bit systems, and mimkatz) that say they can export non exportable keys but I have no experience with them so I have no clue how well they work.
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
```
Select distinct t1.Column1,
case when t1.Column2 < t2.Column2 then t1.Column2 else t2.Column2 end as Column2,
case when t1.Column3 > t2.Column3 then t1.Column3 else t2.Column3 end as Column3
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.column2 = t2.column3;
```
EDIT: A simpler one:
```
Select t1.*
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3
```
EDIT2: And if you want to also return rows where there is no such dupes:
```
Select t1.*
from myTable t1
left join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3 or t2.COlumn1 is null;
```
|
All the answer till now, will loose data for single combination entry. It is suppose to be below code
```
Select distinct t1.Column1,
case when t1.Column2 < t1.Column3 then t1.Column2 else t1.Column3 end as Column2,
case when t1.Column2 < t1.Column3 then t1.Column3 else t1.Column2 end as Column3
from myTable t1
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
```
Select distinct t1.Column1,
case when t1.Column2 < t2.Column2 then t1.Column2 else t2.Column2 end as Column2,
case when t1.Column3 > t2.Column3 then t1.Column3 else t2.Column3 end as Column3
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.column2 = t2.column3;
```
EDIT: A simpler one:
```
Select t1.*
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3
```
EDIT2: And if you want to also return rows where there is no such dupes:
```
Select t1.*
from myTable t1
left join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3 or t2.COlumn1 is null;
```
|
You can use `exists` to find the duplicates and then `<` (or `>`) to get one of the rows;
```
select t.*
from t
where exists (select 1
from t t2
where t2.column1 = t1.column1 and
t2.column2 = t1.column3 and
t2.column3 = t1.column2
) and
t.column1 < t.column2;
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
```
Select distinct t1.Column1,
case when t1.Column2 < t2.Column2 then t1.Column2 else t2.Column2 end as Column2,
case when t1.Column3 > t2.Column3 then t1.Column3 else t2.Column3 end as Column3
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.column2 = t2.column3;
```
EDIT: A simpler one:
```
Select t1.*
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3
```
EDIT2: And if you want to also return rows where there is no such dupes:
```
Select t1.*
from myTable t1
left join myTable t2 on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column3
where t1.column2 < t1.column3 or t2.COlumn1 is null;
```
|
I your case you can use `distinct` with `outer apply`. in outer apply you can add `order by` that you need
```
select distinct
t.column1,
r.column2,
r.column3
from myTable t
outer apply (
select top 1
r.column2,
r.column3
from myTable as r
where r.column1 = t.column1
) as r
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
If columns 2 and 3 contain "reverse duplicates" that you want to hide, you will have to decide what ordering you want to see:
```
SELECT column1, column2, column3
FROM aTable
WHERE column2 <= column3
```
|
From your data I assumed, that each entry has the same `column1` value, if they are duplicate. Try:
```
SELECT column1, column2, column3 FROM (
SELECT column1,
column2,
column3,
ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2, column3) rn
FROM MyTable
) a WHERE rn = 1
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
You can use `exists` to find the duplicates and then `<` (or `>`) to get one of the rows;
```
select t.*
from t
where exists (select 1
from t t2
where t2.column1 = t1.column1 and
t2.column2 = t1.column3 and
t2.column3 = t1.column2
) and
t.column1 < t.column2;
```
|
I your case you can use `distinct` with `outer apply`. in outer apply you can add `order by` that you need
```
select distinct
t.column1,
r.column2,
r.column3
from myTable t
outer apply (
select top 1
r.column2,
r.column3
from myTable as r
where r.column1 = t.column1
) as r
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
If columns 2 and 3 contain "reverse duplicates" that you want to hide, you will have to decide what ordering you want to see:
```
SELECT column1, column2, column3
FROM aTable
WHERE column2 <= column3
```
|
I your case you can use `distinct` with `outer apply`. in outer apply you can add `order by` that you need
```
select distinct
t.column1,
r.column2,
r.column3
from myTable t
outer apply (
select top 1
r.column2,
r.column3
from myTable as r
where r.column1 = t.column1
) as r
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
From your data I assumed, that each entry has the same `column1` value, if they are duplicate. Try:
```
SELECT column1, column2, column3 FROM (
SELECT column1,
column2,
column3,
ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2, column3) rn
FROM MyTable
) a WHERE rn = 1
```
|
All the answer till now, will loose data for single combination entry. It is suppose to be below code
```
Select distinct t1.Column1,
case when t1.Column2 < t1.Column3 then t1.Column2 else t1.Column3 end as Column2,
case when t1.Column2 < t1.Column3 then t1.Column3 else t1.Column2 end as Column3
from myTable t1
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
From your data I assumed, that each entry has the same `column1` value, if they are duplicate. Try:
```
SELECT column1, column2, column3 FROM (
SELECT column1,
column2,
column3,
ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2, column3) rn
FROM MyTable
) a WHERE rn = 1
```
|
I your case you can use `distinct` with `outer apply`. in outer apply you can add `order by` that you need
```
select distinct
t.column1,
r.column2,
r.column3
from myTable t
outer apply (
select top 1
r.column2,
r.column3
from myTable as r
where r.column1 = t.column1
) as r
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
If columns 2 and 3 contain "reverse duplicates" that you want to hide, you will have to decide what ordering you want to see:
```
SELECT column1, column2, column3
FROM aTable
WHERE column2 <= column3
```
|
You can use `exists` to find the duplicates and then `<` (or `>`) to get one of the rows;
```
select t.*
from t
where exists (select 1
from t t2
where t2.column1 = t1.column1 and
t2.column2 = t1.column3 and
t2.column3 = t1.column2
) and
t.column1 < t.column2;
```
|
51,518,362 |
Apologies if this is a duplicate question, I can't seem to find it anywhere else.
I have a table like so:
```
column1 column2 column3
entry 1 A B
ENTRY 2 A C
ENTRY 3 B C
ENTRY 1 B A
ENTRY 2 C A
ENTRY 3 C B
```
The table I'm using has more columns but the idea is the same.
Is there an easy clean way to get the distinct entries (i.e. I'm only interested in bringing back Entry 1 once, not twice.
|
2018/07/25
|
[
"https://Stackoverflow.com/questions/51518362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067427/"
] |
If columns 2 and 3 contain "reverse duplicates" that you want to hide, you will have to decide what ordering you want to see:
```
SELECT column1, column2, column3
FROM aTable
WHERE column2 <= column3
```
|
All the answer till now, will loose data for single combination entry. It is suppose to be below code
```
Select distinct t1.Column1,
case when t1.Column2 < t1.Column3 then t1.Column2 else t1.Column3 end as Column2,
case when t1.Column2 < t1.Column3 then t1.Column3 else t1.Column2 end as Column3
from myTable t1
```
|
57,385,016 |
I'm trying to read a file that is formatted like this:
```none
ruby 2.6.2
elixir 1.8.3
```
And convert into a two-dimensional array like this pseudocode:
```none
[
["ruby", "2.6.2"]
["elixir", "1.8.3"]
]
```
The code I have to do this in Rust is:
```rust
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::path::Path;
pub fn present() -> bool {
path().exists()
}
pub fn parse() -> Vec<Vec<String>> {
let f = BufReader::new(file().unwrap());
f.lines()
.map(|line| {
line.unwrap()
.split_whitespace()
.map(|x| x.to_string())
.collect()
})
.collect()
}
fn file() -> io::Result<File> {
let f = File::open(path())?;
return Ok(f);
}
fn path<'a>() -> &'a Path {
return Path::new(".tool-versions");
}
```
What I'm unsure of here, is this line in the middle of the `parse` function:
```
.map(|x| x.to_string())
```
This seems like a bit of "overwork", but I am not sure if my feeling is correct here.
Is there something I'm missing here, or is this the cleanest way to write this code to accomplish this particular task?
|
2019/08/06
|
[
"https://Stackoverflow.com/questions/57385016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15245/"
] |
Your code is generally idiomatic and good, I just have a few minor caveats.
As far as the "overwork", I would argue modifying the string in-place is overwork, since at every removed whitespace character, you either need to do one of 3 things:
1. Shift every character past that element down 1 (most moves, no allocations required though).
2. Store an index of every position, iterate in reverse order and shift each element down 1 (less moves, but requires an allocation).
3. Store an index of every position, track the index of the start current whitespace block, the end of the current whitespace block and the start of the next block,and move every element down, and then tracking these shifts (most complex, least moves required, and still more computational expensive than needed).
Or.. you could allocate a new string. Sometimes simplicity is powerful.
For the rest, one major issue is not to panic unnecessarily, especially not from failing to open a file. Unwraps, unless you can prove they shouldn't occur, are not good for production code. Specifically, the following line might induce a panic.
```
let f = BufReader::new(file().unwrap());
```
Better to replace that function with:
```
pub fn parse() -> io::Result<Vec<Vec<String>>> {
let f = BufReader::new(file()?);
f.lines()
.map(|line| {
line.map(|x| {
x
.split_whitespace()
.map(|x| x.to_string())
.collect()
})
})
.collect()
}
```
This way, the caller of `parse` can appropriately handle any errors, both during BufReader creation and any errors that occur during `lines()`.
|
I believe the `.to_string()` is necessary. But I would change it for clarity.
The `.lines()` function returns an iterator with a `String`. But the function [split\_whitespace](https://doc.rust-lang.org/std/string/struct.String.html#method.split_whitespace) returns a `SplitWhiteSpace` struct.
If you look in the source code at [line 4213](https://doc.rust-lang.org/src/core/str/mod.rs.html#4212), then you see that's iterating with `str`.
Because your function returns a `String` and not an `str`, you need to convert it to a `String`. That can be accomplished by the `.to_string()` function, but I think it'd be cleaner if you were to use `String::from()`.
The result would be:
```
.map(|x| String::from(x))
```
This step is not only necessary for the type, but also for lifetimes. The `str`'s you get back have the same lifetime as the `SplitWhiteSpace` struct. The conversion to `String` copies the values which allows them to have a different lifetime.
(Take that explanation with a grain of salt, this is still quite new for me too)
|
9,136,527 |
I am creating a library in AS3. Inside the library I make use of a bunch of classes/packages that need not be exposed to the end user of my lib. I want to only expose one of these classes.
I guess my questions are:
1) How are libraries commonly distributed in AS3?
2) Is there a .jar equivalent in AS3 that developers can include, but will only have access/knowledge of the classes I've declared as public?
Thanks!
|
2012/02/03
|
[
"https://Stackoverflow.com/questions/9136527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396077/"
] |
AS3 libraries are called SWCs. Like JARs they are just ZIP archives with some metadata included. You can build libraries either using Flash Builder library projects or mxmlc compiler in Flex SDK which is described for example [here](http://talsma.tv/post.cfm/ant-mxmlc-and-swc-files).
Good practice is to distribute SWC or source code. With docs or readme file of course.
|
>
> Is it possible to create a SWC file without using the Flex framework?
> I just want bare-bone AS3.
>
>
>
Yes we are not forced into using flex, in fact Adobe doesn't even support Flex as their product officially anymore as it is now an open-source apache project. <http://blogs.apache.org/flex/>
The compiler itself for flash is open-source and free to use, that is why there are many third party IDEs and development tools that can also produce SWC libraries. The compiler just requires a special xml file in a zip in order to make a swc. So if you want to avoid doing this manually to the spec its just a matter of choosing a gui way to do this.
One of the most popular one open-source gui ways atm I believe is Flash Develop <http://www.flashdevelop.org/> which has a plugin to do what you want. <http://www.flashdevelop.org/community/viewtopic.php?f=4&t=2987>
This IDE is highly recommended but if you need something more cross platform, I recommend Intellij Idea which is a great as3 and java ide, since you know what jar files are.
>
> "only have access/knowledge of the classes I've declared as public?"
>
>
>
The classes in your swc will be no different to being part of your main project so if you create a swc with public or private it will be public or private the same way. To be honest though most code shared by blogs and repositories in the community are just raw \*.as files, swc is handy however for shared libraries in a team and can make this more organised.
|
37,576,880 |
How can I set `scrolling = "no"` at the iframe podio-webform-frame?
Unfortunately it's possible in fully-conforming HTML5 with just HTML and CSS properties
[view the automatic iframe generated by podio](http://i.stack.imgur.com/hvzV0.png)
|
2016/06/01
|
[
"https://Stackoverflow.com/questions/37576880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2624457/"
] |
You can do this pretty easily using WPF:
1. Find a nice World Map in SVG format. I used [this one](https://commons.wikimedia.org/wiki/File:World_map_-_low_resolution.svg) from Wikipedia:
[](https://i.stack.imgur.com/lAaNI.png)
2. Download and install [Inkscape](https://inkscape.org/en/download/) then open the SVG you've just downloaded. Inkscape has a nice feature that makes it possible to save an SVG as a XAML.
[](https://i.stack.imgur.com/eurWu.png)
3. Import the `ViewBox` from the XAML file into your WPF window/etc:
[](https://i.stack.imgur.com/Nb42z.png)
4. For each `Path` in the XAML you can add a `MouseEnter`/`MouseLeave` event handler or you can use the same one for all the `Path`s
Sample code:
```
private void CountryMouseEnter(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Aqua);
}
}
private void Country_MouseLeave(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Black);
}
}
```
5. Now it's just a matter of changing colors/showing `MessageBox`es etc.
[](https://i.stack.imgur.com/Rae4y.gif)
[GitHub](https://github.com/0xffffabcd/WorldMapViewer)
|
My first thought: You could bind a command to the view that will be triggered by a click on a position. If you're using WPF you can bind command parameters to the command to get the x and y of your click...
After that you have to handle the content of your messagebox and the highlighting of the borders depending on the position xy.
have fun :D
|
37,576,880 |
How can I set `scrolling = "no"` at the iframe podio-webform-frame?
Unfortunately it's possible in fully-conforming HTML5 with just HTML and CSS properties
[view the automatic iframe generated by podio](http://i.stack.imgur.com/hvzV0.png)
|
2016/06/01
|
[
"https://Stackoverflow.com/questions/37576880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2624457/"
] |
You can do this pretty easily using WPF:
1. Find a nice World Map in SVG format. I used [this one](https://commons.wikimedia.org/wiki/File:World_map_-_low_resolution.svg) from Wikipedia:
[](https://i.stack.imgur.com/lAaNI.png)
2. Download and install [Inkscape](https://inkscape.org/en/download/) then open the SVG you've just downloaded. Inkscape has a nice feature that makes it possible to save an SVG as a XAML.
[](https://i.stack.imgur.com/eurWu.png)
3. Import the `ViewBox` from the XAML file into your WPF window/etc:
[](https://i.stack.imgur.com/Nb42z.png)
4. For each `Path` in the XAML you can add a `MouseEnter`/`MouseLeave` event handler or you can use the same one for all the `Path`s
Sample code:
```
private void CountryMouseEnter(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Aqua);
}
}
private void Country_MouseLeave(object sender, MouseEventArgs e)
{
var path = sender as Path;
if (path != null)
{
path.Fill = new SolidColorBrush(Colors.Black);
}
}
```
5. Now it's just a matter of changing colors/showing `MessageBox`es etc.
[](https://i.stack.imgur.com/Rae4y.gif)
[GitHub](https://github.com/0xffffabcd/WorldMapViewer)
|
**Option 1**
There is a project on Code Project that someone created that defines hotspots that are clickable with events. You could use that to overlay your map and define the hotspots where you need them.
[C# Windows Forms ImageMap Control](http://www.codeproject.com/Articles/2820/C-Windows-Forms-ImageMap-Control)
**Option 2**
You could bind to the `MouseUp` Event on the Image and use the following to see if it is in a `Rectangle`
```
private void mapMouseUp(object sender, MouseEventArgs e) {
Rectangle rect1 = new Rectangle(0, 0, 100, 100);
Rectangle rect2 = new Rectangle(0, 100, 100, 100);
if (rect1.Contains(e.Location)) {
// Do your stuff
} else if (rect2.Contains(e.Location)) {
// Do your stuff
}
}
```
|
22,947 |
i want a vf page that will render all the records through controller and the results will be render as html how please help me with some code and example for custom object.
Class:
```
public with sharing class Active {
public Active(ApexPages.StandardController controller) {
}
public List<Property__c> po { get; set; }
public Active(){
po = [SELECT Acceptance_Date__c, Payment_Type__c, Date_Sold__c, Deposit_Manager_Approved__c,
HardMoneyLoanMax__c, Buyer_Name_on_Contract__c ,Address__c, Property_Source__c,
Sales_Agent__c
FROM Property__c
WHERE Property__c.Property_Status__c = 'Active'];
}
}
```
VF page:
```
<apex:page renderas="html" standardController="Property__c"
extensions="Active" showHeader="false" sidebar="false">
<apex:form >
<apex:pageblock id="Property__c" title="PropertyDetails" >
<apex:pageblockTable value="{!Property__c}" var="a">
<apex:column value="{!a.County__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.HardMoneyLoanMax__c}"/>
<apex:column value="{!a.Notes__c}"/>
<apex:column value="{!a.Property_Source__c}"/>
<apex:column value="{!a.Sales_Agent__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.Full_Bonus__c}"/>
<apex:column value="{!a.Acceptance_Date__c}"/>
<apex:column value="{!a.Deposit_Manager_Approved__c}"/>
<apex:column value="{!a.Address__c}"/>
</apex:pageblockTable>
</apex:pageblock>
</apex:form>
</apex:page>
```
|
2013/12/24
|
[
"https://salesforce.stackexchange.com/questions/22947",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/4955/"
] |
While reading data from the `Property__c` object you don't need to reference this objects name if the WHERE clause:
```
po = [ SELECT Acceptance_Date__c, ...
FROM Property__c
WHERE Property_Status__c = 'Active' ];
```
Then at the visualforce page you want to show all records from the `po` list? You need to use `value="{!po}"` in the pageBlockTable then:
```
<apex:pageblockTable value="{!po}" var="p">
<apex:column value="{!p.County__c}"/>
<apex:column value="{!p.Date_Sold__c}"/>
<apex:column value="{!p.HardMoneyLoanMax__c}"/>
...
```
|
Replace the below line this
```
<apex:pageblockTable value="{!Property__c}" var="a">
```
with this line
```
<apex:pageblockTable value="{!po}" var="a">
```
remove this construtor from class
```
public Active(ApexPages.StandardController controller) {
}
```
and standard controller attribute from visual force page and as below:
controller="Active" showHeader="false" sidebar="false">
Now you can get the records
|
22,947 |
i want a vf page that will render all the records through controller and the results will be render as html how please help me with some code and example for custom object.
Class:
```
public with sharing class Active {
public Active(ApexPages.StandardController controller) {
}
public List<Property__c> po { get; set; }
public Active(){
po = [SELECT Acceptance_Date__c, Payment_Type__c, Date_Sold__c, Deposit_Manager_Approved__c,
HardMoneyLoanMax__c, Buyer_Name_on_Contract__c ,Address__c, Property_Source__c,
Sales_Agent__c
FROM Property__c
WHERE Property__c.Property_Status__c = 'Active'];
}
}
```
VF page:
```
<apex:page renderas="html" standardController="Property__c"
extensions="Active" showHeader="false" sidebar="false">
<apex:form >
<apex:pageblock id="Property__c" title="PropertyDetails" >
<apex:pageblockTable value="{!Property__c}" var="a">
<apex:column value="{!a.County__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.HardMoneyLoanMax__c}"/>
<apex:column value="{!a.Notes__c}"/>
<apex:column value="{!a.Property_Source__c}"/>
<apex:column value="{!a.Sales_Agent__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.Full_Bonus__c}"/>
<apex:column value="{!a.Acceptance_Date__c}"/>
<apex:column value="{!a.Deposit_Manager_Approved__c}"/>
<apex:column value="{!a.Address__c}"/>
</apex:pageblockTable>
</apex:pageblock>
</apex:form>
</apex:page>
```
|
2013/12/24
|
[
"https://salesforce.stackexchange.com/questions/22947",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/4955/"
] |
While reading data from the `Property__c` object you don't need to reference this objects name if the WHERE clause:
```
po = [ SELECT Acceptance_Date__c, ...
FROM Property__c
WHERE Property_Status__c = 'Active' ];
```
Then at the visualforce page you want to show all records from the `po` list? You need to use `value="{!po}"` in the pageBlockTable then:
```
<apex:pageblockTable value="{!po}" var="p">
<apex:column value="{!p.County__c}"/>
<apex:column value="{!p.Date_Sold__c}"/>
<apex:column value="{!p.HardMoneyLoanMax__c}"/>
...
```
|
My VF Page:
```
<apex:page standardController="Order__c" recordSetVar="display" cache="false" extensions="AllOrders" >
<apex:form >
<apex:pageBlock title="All Orders in Application">
<apex:outputPanel id="mypanel">
<apex:pageBlockTable value="{!display}" var="r">
<apex:column headerValue="Name">
<apex:outputLink value="/{!r.Id}">{!r.Name}</apex:outputLink>
</apex:column>
<apex:column headerValue="Vendor" styleClass="ratingClass">
<apex:outputText value="{!r.VendorDetail__c}" escape="false" />
</apex:column>
<apex:column headerValue="Location">
<apex:outputText value="{!r.Location__c}" escape="false" /> </apex:column>
<apex:column headerValue="Area">
<apex:outputText value="{!r.Area__c}" escape="false" /> </apex:column>
<apex:column headerValue="Photoprint">
<apex:outputText value="{!r.Photoprint__c}" escape="false" /> </apex:column>
<apex:column headerValue="Quantity">
<apex:outputText value="{!r.Quantity__c}" escape="false" /> </apex:column>
<apex:column headervalue="Document print">
<apex:outputText value="{!r.Docprint__c}" escape="false" /> </apex:column>
<apex:column headerValue="Quantity">
<apex:outputText value="{!r.DocQuantity__c}" escape="false" /> </apex:column>
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
```
My Apex Class:
```
public with sharing class AllOrders {
private ApexPages.StandardSetController controller;
public AllOrders(ApexPages.StandardSetController controller) {
this.controller=controller;
}
public List<Order__c> display()
{
List<Order__c> po=[select Name,VendorDetail__c,Location__c,Area__c,Photoprint__c,Quantity__c,Docprint__c,DocQuantity__c from Order__c where Location__c = 'Hyderabad' ];
return po;
}
}
```
I can't get the records the way i am expecting, they are not filtered. The page is displaying all the rows. I dodnt understand where i made a mistake...please help me..in this.
|
22,947 |
i want a vf page that will render all the records through controller and the results will be render as html how please help me with some code and example for custom object.
Class:
```
public with sharing class Active {
public Active(ApexPages.StandardController controller) {
}
public List<Property__c> po { get; set; }
public Active(){
po = [SELECT Acceptance_Date__c, Payment_Type__c, Date_Sold__c, Deposit_Manager_Approved__c,
HardMoneyLoanMax__c, Buyer_Name_on_Contract__c ,Address__c, Property_Source__c,
Sales_Agent__c
FROM Property__c
WHERE Property__c.Property_Status__c = 'Active'];
}
}
```
VF page:
```
<apex:page renderas="html" standardController="Property__c"
extensions="Active" showHeader="false" sidebar="false">
<apex:form >
<apex:pageblock id="Property__c" title="PropertyDetails" >
<apex:pageblockTable value="{!Property__c}" var="a">
<apex:column value="{!a.County__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.HardMoneyLoanMax__c}"/>
<apex:column value="{!a.Notes__c}"/>
<apex:column value="{!a.Property_Source__c}"/>
<apex:column value="{!a.Sales_Agent__c}"/>
<apex:column value="{!a.Date_Sold__c}"/>
<apex:column value="{!a.Full_Bonus__c}"/>
<apex:column value="{!a.Acceptance_Date__c}"/>
<apex:column value="{!a.Deposit_Manager_Approved__c}"/>
<apex:column value="{!a.Address__c}"/>
</apex:pageblockTable>
</apex:pageblock>
</apex:form>
</apex:page>
```
|
2013/12/24
|
[
"https://salesforce.stackexchange.com/questions/22947",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/4955/"
] |
Replace the below line this
```
<apex:pageblockTable value="{!Property__c}" var="a">
```
with this line
```
<apex:pageblockTable value="{!po}" var="a">
```
remove this construtor from class
```
public Active(ApexPages.StandardController controller) {
}
```
and standard controller attribute from visual force page and as below:
controller="Active" showHeader="false" sidebar="false">
Now you can get the records
|
My VF Page:
```
<apex:page standardController="Order__c" recordSetVar="display" cache="false" extensions="AllOrders" >
<apex:form >
<apex:pageBlock title="All Orders in Application">
<apex:outputPanel id="mypanel">
<apex:pageBlockTable value="{!display}" var="r">
<apex:column headerValue="Name">
<apex:outputLink value="/{!r.Id}">{!r.Name}</apex:outputLink>
</apex:column>
<apex:column headerValue="Vendor" styleClass="ratingClass">
<apex:outputText value="{!r.VendorDetail__c}" escape="false" />
</apex:column>
<apex:column headerValue="Location">
<apex:outputText value="{!r.Location__c}" escape="false" /> </apex:column>
<apex:column headerValue="Area">
<apex:outputText value="{!r.Area__c}" escape="false" /> </apex:column>
<apex:column headerValue="Photoprint">
<apex:outputText value="{!r.Photoprint__c}" escape="false" /> </apex:column>
<apex:column headerValue="Quantity">
<apex:outputText value="{!r.Quantity__c}" escape="false" /> </apex:column>
<apex:column headervalue="Document print">
<apex:outputText value="{!r.Docprint__c}" escape="false" /> </apex:column>
<apex:column headerValue="Quantity">
<apex:outputText value="{!r.DocQuantity__c}" escape="false" /> </apex:column>
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
```
My Apex Class:
```
public with sharing class AllOrders {
private ApexPages.StandardSetController controller;
public AllOrders(ApexPages.StandardSetController controller) {
this.controller=controller;
}
public List<Order__c> display()
{
List<Order__c> po=[select Name,VendorDetail__c,Location__c,Area__c,Photoprint__c,Quantity__c,Docprint__c,DocQuantity__c from Order__c where Location__c = 'Hyderabad' ];
return po;
}
}
```
I can't get the records the way i am expecting, they are not filtered. The page is displaying all the rows. I dodnt understand where i made a mistake...please help me..in this.
|
51,701,662 |
Below is the function in `__init__.py` file which means this part of code always run when code is executed
```
import logging
def log_setup():
logging.TRACE = 5
logging.addLevelName(5, 'TRACE')
def trace(obj, message, *args, **kws):
obj.log(logging.TRACE, message, *args, **kws)
logging.Logger.trace = trace
logging.trace = trace
root = logging.getLogger("TEST")
root.setLevel(5)
ch = logging.StreamHandler()
ch.setFormatter(f)
ch.setLevel(5)
root.handlers = []
root.addHandler(ch)
```
I am having below code in one of the library say xyz.py
```
import logging
log = logging.getLogger("TEST."+__name__)
if log.trace:
print("***ELLO***", log.getEffectiveLevel())
print("***ELLO***", log.isEnabledFor(logging.DEBUG))
print("***ELLO***", log.isEnabledFor(logging.TRACE))
log.trace("Hey Statement printed")
```
When I am calling via script, I am not able to get the log.trace printed. Interestingly, For log.isEnabledFor(logging.TRACE) is always returning False.
Not sure what i am missing here
Below is the output
```
***ELLO*** 10
***ELLO*** True
***ELLO*** False
```
|
2018/08/06
|
[
"https://Stackoverflow.com/questions/51701662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336962/"
] |
The problem is you are adding same `editButton` in all the cell, you need to create new `UIButton` for all the cell.
So change line
```
editButton.frame = CGRect(x:63, y:0, width:20,height:20)
```
With
```
//Create new button instance every time
let editButton = UIButton(frame: CGRect(x:63, y:0, width:20,height:20))
```
Also `cellForItemAt` will reuse the cell so instead of creating new `UIButton` each time you can try like this.
```
let editButton: UIButton
if let btn = cell.viewWithTag(101) as? UIButton {
editButton = btn
}
else {
editButton = UIButton(frame: CGRect(x:63, y:0, width:20,height:20))
}
editButton.layer.cornerRadius = 10
editButton.backgroundColor = UIColor.lightGray
editButton.layer.setValue(indexPath.item, forKey: "index")
editButton.setImage(UIImage(named: "CloseScan"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
//Set tag for reuse
editButton.tag = 101
cell.addSubview(editButton)
```
You can get indexPath of cell in button action like this.
```
@objc func deleteCell(_ sender: UIButton) {
let point = sender.superview?.convert(sender.center, to: self.collectionView) ?? .zero
guard let indexPath = self.collectionView.indexPathForItem(at: point) else { return }
//Use indexPath here
}
```
**Edit:** If you want to hide or show the button than its better that you just add button in your design and create one outlet of in your CustomCollectionViewCell after that in `cellForItemAt` just hide and show button on basis of condition. From your code you need to show the delete button if selected index of segment is 1. So make your `cellForItem` like this.
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellCard
cell.CardView.backgroundColor = ColorArray[indexPath.row]
cell.ColorName.text = ColorName[indexPath.row]
//Add delete button in the xib or storyboard collectionViewCell
//Now hide this button if EditButton title is not "Edit"
cell.editButton.isHidden = EditButton.currentTitle != "Edit"
//Add action of button
cell.editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
return cell
}
```
After that in your edit button action reload the collectionView after you set the button title.
```
if EditButton.currentTitle == "Edit" {
EditButton.setTitle("Cancel", for: .normal)
} else if EditButton.currentTitle == "Cancel" {
EditButton.setTitle("Edit", for: .normal)
}
//Reload your collectionView
self.collectionView.reloadData()
```
|
I think you could move the line:
```
var editButton = UIButton()
```
To func *cellForItemAt* :
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellCard
switch ColorSegment.selectedSegmentIndex {
case 0:
cell.CardView.backgroundColor = ColorArray[indexPath.row]
cell.ColorName.text = ColorName[indexPath.row]
case 1:
cell.CardView.backgroundColor = CustomColorArray[indexPath.row]
cell.ColorName.text = CustomColorName[indexPath.row]
// create editButton in here
var editButton = UIButton()
editButton.frame = CGRect(x:63, y:0, width:20,height:20)
editButton.layer.cornerRadius = 10
editButton.backgroundColor = UIColor.lightGray
editButton.layer.setValue(indexPath.item, forKey: "index")
editButton.setImage(UIImage(named: "CloseScan"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
cell.addSubview(editButton)
default: print("error with switch statement for cell data")
}
return cell
}
```
|
51,701,662 |
Below is the function in `__init__.py` file which means this part of code always run when code is executed
```
import logging
def log_setup():
logging.TRACE = 5
logging.addLevelName(5, 'TRACE')
def trace(obj, message, *args, **kws):
obj.log(logging.TRACE, message, *args, **kws)
logging.Logger.trace = trace
logging.trace = trace
root = logging.getLogger("TEST")
root.setLevel(5)
ch = logging.StreamHandler()
ch.setFormatter(f)
ch.setLevel(5)
root.handlers = []
root.addHandler(ch)
```
I am having below code in one of the library say xyz.py
```
import logging
log = logging.getLogger("TEST."+__name__)
if log.trace:
print("***ELLO***", log.getEffectiveLevel())
print("***ELLO***", log.isEnabledFor(logging.DEBUG))
print("***ELLO***", log.isEnabledFor(logging.TRACE))
log.trace("Hey Statement printed")
```
When I am calling via script, I am not able to get the log.trace printed. Interestingly, For log.isEnabledFor(logging.TRACE) is always returning False.
Not sure what i am missing here
Below is the output
```
***ELLO*** 10
***ELLO*** True
***ELLO*** False
```
|
2018/08/06
|
[
"https://Stackoverflow.com/questions/51701662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336962/"
] |
The problem is you are adding same `editButton` in all the cell, you need to create new `UIButton` for all the cell.
So change line
```
editButton.frame = CGRect(x:63, y:0, width:20,height:20)
```
With
```
//Create new button instance every time
let editButton = UIButton(frame: CGRect(x:63, y:0, width:20,height:20))
```
Also `cellForItemAt` will reuse the cell so instead of creating new `UIButton` each time you can try like this.
```
let editButton: UIButton
if let btn = cell.viewWithTag(101) as? UIButton {
editButton = btn
}
else {
editButton = UIButton(frame: CGRect(x:63, y:0, width:20,height:20))
}
editButton.layer.cornerRadius = 10
editButton.backgroundColor = UIColor.lightGray
editButton.layer.setValue(indexPath.item, forKey: "index")
editButton.setImage(UIImage(named: "CloseScan"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
//Set tag for reuse
editButton.tag = 101
cell.addSubview(editButton)
```
You can get indexPath of cell in button action like this.
```
@objc func deleteCell(_ sender: UIButton) {
let point = sender.superview?.convert(sender.center, to: self.collectionView) ?? .zero
guard let indexPath = self.collectionView.indexPathForItem(at: point) else { return }
//Use indexPath here
}
```
**Edit:** If you want to hide or show the button than its better that you just add button in your design and create one outlet of in your CustomCollectionViewCell after that in `cellForItemAt` just hide and show button on basis of condition. From your code you need to show the delete button if selected index of segment is 1. So make your `cellForItem` like this.
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellCard
cell.CardView.backgroundColor = ColorArray[indexPath.row]
cell.ColorName.text = ColorName[indexPath.row]
//Add delete button in the xib or storyboard collectionViewCell
//Now hide this button if EditButton title is not "Edit"
cell.editButton.isHidden = EditButton.currentTitle != "Edit"
//Add action of button
cell.editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
return cell
}
```
After that in your edit button action reload the collectionView after you set the button title.
```
if EditButton.currentTitle == "Edit" {
EditButton.setTitle("Cancel", for: .normal)
} else if EditButton.currentTitle == "Cancel" {
EditButton.setTitle("Edit", for: .normal)
}
//Reload your collectionView
self.collectionView.reloadData()
```
|
move your button logic outside of switch statement like this
```
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCellCard
switch ColorSegment.selectedSegmentIndex {
case 0:
cell.CardView.backgroundColor = ColorArray[indexPath.row]
cell.ColorName.text = ColorName[indexPath.row]
case 1:
cell.CardView.backgroundColor = CustomColorArray[indexPath.row]
cell.ColorName.text = CustomColorName[indexPath.row]
default: print("error with switch statement for cell data")
}
var editButton = UIButton.init(frame: CGRect.init(x: 63, y: 0, width: 20, height: 20))
editButton.layer.cornerRadius = 10
editButton.backgroundColor = UIColor.lightGray
editButton.layer.setValue(indexPath.item, forKey: "index")
editButton.setImage(UIImage(named: "CloseScan"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(deleteCell), for: UIControlEvents.touchUpInside)
cell.addSubview(editButton)
return cell
```
}
|
12,236,579 |
I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
```
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
```
1. I'm using Wing IDE
2. I get the error "if num >= 0 print "The number you entered is " + num"
3. How do I return to start if the number entered is negative?
4. What am I doing wrong?
|
2012/09/02
|
[
"https://Stackoverflow.com/questions/12236579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1618869/"
] |
Try this:
```
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
```
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the `if` condition is not satisfied. You could also easily use a `while` loop.
```
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
```
|
Try this:
```
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
```
you don't need the `else` part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)
|
23,447,451 |
I would like to ask your kind help about showing just the selected markers in Google Maps API V3.
I have a HTML select ->
```
<select onchange="appartments()" id="selectField">
<option value="appartment1">Choose one appartment...</option>
<option value="appartment2">1052 Budapest, Galamb u. 3.</option>
<option value="appartment3">1052 Budapest, Régi posta u. 11.</option>
<option value="appartment4">1052 Budapest, Régi posta u. 14.</option>
<option value="appartment5">1051 Budapest, Vörösmarty tér 2.</option>
<option value="appartment6">1066 Budapest, Ó u. 5.</option>
</select>
```
I have the API V3 and the markers ->
```
function appartments() {
var get_id = document.getElementById('selectField');
console.log(get_id);
var result = get_id.options[get_id.selectedIndex].value;
}
IF ELSE HERE!
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.5037832, 19.0575725));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4947063,19.0527723));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4968459,19.0505202));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.494265,19.0516276));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4933959,19.0515483));
marker.setMap(map);
}
```
I would like to get the marker which is selected in HTML select, for example ->
```
if (result = appartment1) {
var marker...
} else if (result = appartment2) {
var marker..
} and so..
```
Could anybody help me giving me a simple way for solving this?
Thanks a lot in advance,
Tibor
|
2014/05/03
|
[
"https://Stackoverflow.com/questions/23447451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3599604/"
] |
Maybe use PayPal's buy now buttons (<https://www.paypal.com/cgi-bin/webscr?cmd=_singleitem-intro-outside>) or some other simple purchase system's button. Maybe Strip has some good options too.
Once you get to needing a real cart. You should just use a real application first and simple content management second.
|
[EvilText](http://eviltext.com) (open source static site generator similar to Jekyll) have eCommerce plugin, see [sample shop](http://shop-example.eviltext.com).
|
23,447,451 |
I would like to ask your kind help about showing just the selected markers in Google Maps API V3.
I have a HTML select ->
```
<select onchange="appartments()" id="selectField">
<option value="appartment1">Choose one appartment...</option>
<option value="appartment2">1052 Budapest, Galamb u. 3.</option>
<option value="appartment3">1052 Budapest, Régi posta u. 11.</option>
<option value="appartment4">1052 Budapest, Régi posta u. 14.</option>
<option value="appartment5">1051 Budapest, Vörösmarty tér 2.</option>
<option value="appartment6">1066 Budapest, Ó u. 5.</option>
</select>
```
I have the API V3 and the markers ->
```
function appartments() {
var get_id = document.getElementById('selectField');
console.log(get_id);
var result = get_id.options[get_id.selectedIndex].value;
}
IF ELSE HERE!
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.5037832, 19.0575725));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4947063,19.0527723));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4968459,19.0505202));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.494265,19.0516276));
marker.setMap(map);
var marker = new google.maps.Marker();
marker.setPosition(new google.maps.LatLng(47.4933959,19.0515483));
marker.setMap(map);
}
```
I would like to get the marker which is selected in HTML select, for example ->
```
if (result = appartment1) {
var marker...
} else if (result = appartment2) {
var marker..
} and so..
```
Could anybody help me giving me a simple way for solving this?
Thanks a lot in advance,
Tibor
|
2014/05/03
|
[
"https://Stackoverflow.com/questions/23447451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3599604/"
] |
You could use [snipcart](http://www.snipcart.com). There is a [blog post](https://snipcart.com/blog/static-site-e-commerce-part-2-integrating-snipcart-with-jekyll) and a [demo site](http://snipcart.github.io/snipcart-jekyll-integration/) that will get you up an running.
There is also [Jekyll-store](http://www.jekyll-store.com/) that has the benefit of keeping all the data stored on the webpage, and, unlike snipcart, is free.
|
[EvilText](http://eviltext.com) (open source static site generator similar to Jekyll) have eCommerce plugin, see [sample shop](http://shop-example.eviltext.com).
|
31,293,008 |
I am gathering an `NSNumber` from my plist and I want to print that in a `String`:
```
let tijd = String(self.sortedHighscores[indexPath.row]["Tijd"]!)
cell.detailTextLabel?.text = "\(tijd) seconden"
```
But in Simulator I'm seeing printed: `Optional(120) seconden` for example.
How do I solve this? I've tried unwrapping `tijd`, but that would result in errors in the compiler telling me to delete the `!`.
|
2015/07/08
|
[
"https://Stackoverflow.com/questions/31293008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444642/"
] |
Try this:
```
var highscore : NSNumber = self.sortedHighscores[indexPath.row]["Tijd"] as! NSNumber
var a : String = String(format:"%d",highscore.integerValue)
cell.detailTextLabel.text = a
```
|
`tijd` being an optional, you need to unwrap it, but you should check whether it has a value, too.
```
if let foo = tijd {
cell.detailTextLabel?.text = "\(foo) seconden"
}
```
If you know it will always have a value, `"\(tijd!) seconden"` should work also.
|
22,084 |
Which one is more correct:
>
> My hobby is to play basketball.
>
>
>
or
>
> My hobby is playing basketball?
>
>
>
|
2014/04/24
|
[
"https://ell.stackexchange.com/questions/22084",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/5369/"
] |
I’d say **my hobby is playing basketball** because it’s taking place now in the present, has been for some time in the past and may be in future.
|
I agree with Lucian Sava that
>
> My hobby is playing basketball?
>
>
>
is the better choice, as a statement, or a question if someone asked you. As for
>
> My hobby is to play basketball.
>
>
>
This wording seems to indicate a future goal, but seems strange written here. You could similarly say:
>
> "The hobby *I am interested in* is to play basketball."
>
>
>
which shows that "is to play" is referring to a future event. Also you could say:
>
> My *goal* is to play basketball.
>
>
>
which also refers to a future event.
|
9,612,862 |
I'm trying to install Forever to use with Node.js. I'm installing it using 'npm install forever -g'. It seems to install fine, but when I run the command 'forever' it's not found.
Maybe I'm not installing it in the right location? Where should it be installed to?
Any help would be great! Thank you!
|
2012/03/08
|
[
"https://Stackoverflow.com/questions/9612862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245076/"
] |
That should work, but check 'npm bin -g' to make sure that directory is on your path.
|
You have to run forever install using sudo:
```
sudo npm install forever -g
```
|
20,379,509 |
I add some gem to my gemfile.
Then i type :
`$ bundle install`
It will install the newly add gems in general , But it install the all gems, and it very slowly.
This is my terminal output:
```
Fetching gem metadata from http://rubygems.org/.........
Fetching gem metadata from http://rubygems.org/..
Resolving dependencies...
Enter your password to install the bundled RubyGems to your system:
Using rake (10.1.0)
Using i18n (0.6.5)
...
```
So:
How to make the `bundle install` fast, and i don't want it always install all gems
|
2013/12/04
|
[
"https://Stackoverflow.com/questions/20379509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3060257/"
] |
If you see `Using gemname (version)`, it means the gem is already installed and Bundler doesn't reinstall it.
|
You need to bundle install all of your gems as there are dependency requirements between them. Bundler doesn't reinstall the gem's which state `Using rake (10.1.0)`, but just confirms it's version to ensure gem dependency and prevent your application from producing runtime errors.
You can find out more information here:
<http://bundler.io/>
|
4,057 |
I recently flagged an answer which I think wasn't an answer. To my surprise, the flag was somehow declined. The screenshots below show the question and the flag declination.
When flagging, I added a comment indicating why I flagged it as NAA. [In the low-quality queue](https://politics.stackexchange.com/review/low-quality-posts/27387), two users also voted to delete the answer and the answer has no up votes.
Am I missing something, or should this flag have led to post deletion?
This might seem like a non-issue, but this has been happening somewhat regularly. I flag for low-quality or NAA, the flag gets declined and hours later the post is deleted anyway. In many cases I get that upvotes dispute the flag, but in this case that doesn't seem to have occurred.
[](https://i.stack.imgur.com/EQUNJ.png)
[](https://i.stack.imgur.com/GZcn8.png)
|
2019/10/02
|
[
"https://politics.meta.stackexchange.com/questions/4057",
"https://politics.meta.stackexchange.com",
"https://politics.meta.stackexchange.com/users/18862/"
] |
To be fair, the question was relatively low quality in itself (-2 score as of now):
>
> Is there a general consensus that Britain should continue to be a permanent member of the UN security council ? Other countries such as Japan or India have larger economies and/or militaries.
>
>
>
The now-deleted answer harped on the [distinction](http://mentalfloss.com/article/85686/whats-difference-between-great-britain-and-uk) between the UK and Britain. Whether the answer was facetious or really misunderstood the question is going to turn into a similar debate as the one we recently had on trolling from new accounts.
I think it's not worth the meta-effort to debate these to such an extent. Like I said on another occasion, low-quality questions invite whimsical if not outright low-quality answers. The best way to prevent this is to fix questions, possibly closing them as a first step if the OP doesn't respond to comments for clarification.
|
This debate tends to repeat itself every once in a while. The gist of the problem is that when you flag an answer which apparently misinterpreted the question, there is a chance that you misinterpreted the question yourself, while the answer did not. Or that the answer, while not answering the literal question, still provides useful information on the topic. Or that the answer could have been written in good faith even if it looks like it wasn't, and good faith shall be assumed regardless. Therefore it was decided that such answers should be allowed to stay and dealt with by voting, not by flags.
Bringing such answers to meta helps getting them deleted by mod power, or sometimes forcing the author to delete it by subjecting them to tarring and feathering. What it won't do is changing how such flags are handled in general: if you keep flagging extremely poor or bad-faith-looking answers as NAA, some of your flags will be declined.
|
65,217 |
Since I'm British, I'm used to biscuits that are crisp, dry and crunchy all the way through, with no soft chewy centre. Most chocolate chip cookie recipes are trying to do the exact opposite. How can I bake chocolate chip cookies with a more British texture? Essentially, I want the exact opposite to the answers to [this question](https://cooking.stackexchange.com/questions/1/how-can-i-get-chewy-chocolate-chip-cookies).
|
2016/01/09
|
[
"https://cooking.stackexchange.com/questions/65217",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/9607/"
] |
The best way to achieve what you are looking for is to lower the temp and lengthen the baking time. Lowering the temp will slow the edges from getting burned while the center is allowed to continue to cook.
Allow the top of the cookie to brown before removing from the oven. For soft cookies, the moment it starts to turn brown is the moment you are just a little too late for the cookies to stay soft after they've cooled. If you let the cookie brown just a touch, the cookie will harden on the cooling rack.
|
It shouldn't be too hard to find a crispy chocolate chip cookie recipe if you want one, but if you're interested in experimenting with an existing recipe, here are a few ideas for things to change:
Mix in **melted butter** instead of creamed soft butter. That will greatly reduce the amount of air trapped in the dough. The dough will not loft while baking; it will spread out, allowing for more evaporation. (**Not chilling the dough** is a related tip: the faster it melts in the oven, the more it will spread.)
Cool them entirely **on the baking sheet** instead of transferring them to a rack. This has a strong effect on the finished cookies' crispness.
Use **white sugar instead of brown**. Brown sugar is used in baked goods when you want them to be soft, because it is even more hygroscopic -- pulling water from the air and holding onto it -- than white sugar.
Change the **egg ratio to decrease the amount of yolk**. While the whites contain a lot of water, they also contain much more protein than fat. The fat in yolks will diminish gluten formation and increase tenderness and "fudginess".
|
65,217 |
Since I'm British, I'm used to biscuits that are crisp, dry and crunchy all the way through, with no soft chewy centre. Most chocolate chip cookie recipes are trying to do the exact opposite. How can I bake chocolate chip cookies with a more British texture? Essentially, I want the exact opposite to the answers to [this question](https://cooking.stackexchange.com/questions/1/how-can-i-get-chewy-chocolate-chip-cookies).
|
2016/01/09
|
[
"https://cooking.stackexchange.com/questions/65217",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/9607/"
] |
The best way to achieve what you are looking for is to lower the temp and lengthen the baking time. Lowering the temp will slow the edges from getting burned while the center is allowed to continue to cook.
Allow the top of the cookie to brown before removing from the oven. For soft cookies, the moment it starts to turn brown is the moment you are just a little too late for the cookies to stay soft after they've cooled. If you let the cookie brown just a touch, the cookie will harden on the cooling rack.
|
If what you want is a classic crunchy cookie with some chocolate chips thrown in, use your favorite crunchy cookie recipe and throw a few chocolate chips in. As you said yourself, the American "chocolate chip cookie" is a totally different thing, characterized by a soft texture. It makes no sense to use a recipe for that type of cookie if you don't like it.
|
65,217 |
Since I'm British, I'm used to biscuits that are crisp, dry and crunchy all the way through, with no soft chewy centre. Most chocolate chip cookie recipes are trying to do the exact opposite. How can I bake chocolate chip cookies with a more British texture? Essentially, I want the exact opposite to the answers to [this question](https://cooking.stackexchange.com/questions/1/how-can-i-get-chewy-chocolate-chip-cookies).
|
2016/01/09
|
[
"https://cooking.stackexchange.com/questions/65217",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/9607/"
] |
The best way to achieve what you are looking for is to lower the temp and lengthen the baking time. Lowering the temp will slow the edges from getting burned while the center is allowed to continue to cook.
Allow the top of the cookie to brown before removing from the oven. For soft cookies, the moment it starts to turn brown is the moment you are just a little too late for the cookies to stay soft after they've cooled. If you let the cookie brown just a touch, the cookie will harden on the cooling rack.
|
**Melted butter** (or browned butter better yet!) will make a crispy cookie. Obviously, **omitting all leaveners** will help as well, but you can get an even flatter cookie by adding **extra leavener**, which will over expand and then collapse the dough.
|
19,140,772 |
I have a query that I used pull data from several different tables each night and this pull goes into an upsert table that is loaded to our cloud server. I am trying to set some type of unique identifer/primary key for each row, but I am having issues with it.
`SELECT SUBSTRING(CAST(NEWID() AS varchar(38)), 1, 16)`
Whenever I rerun the query, it changes the value of the `NEWID()` each time, so it's loading duplicates into my table every night instead of updating the records. Is there anyway I can keep `newid()` as static value every time I run the query?
Thanks,
Rachel
|
2013/10/02
|
[
"https://Stackoverflow.com/questions/19140772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839262/"
] |
`NEWID()` is by design returning unique (to your computer) GUID values. Whenever you run
```
SELECT NEWID()
```
You will see a different value.
It sounds like your UPSERT code needs to combine data from the source tables into a primary key that you can reliably use in future to determine if the given row needs to be inserted or updated.
|
NEWID() returns a unique value everytime it is called. It isn't the best choice for a primary key and most data professionals perfer using an int identity for the clustered, primary key if possible.
In your case neither solution will work perfectly since both identities and NEWID() return new values. What you need to do is figure out what columns determine if a row is a duplicate and needs to be updated instead of inserted. To do this use the [merge](http://msdn.microsoft.com/en-us/library/bb510625.aspx) statement.
|
24,475,696 |
my image is not appearing on my site when my page loads, in any browser. My HTML code is
```
<HTML>
<img class="header-img" src="images/headerbanner.png" alt="App Image" />
</HTML>
```
The size and width of the div holding this are set in a css file. The images folder is located in the same directory as the file making this img tag call. However, whenever my page loads, the image appears with an icon in the middle, with no image showing, and only the alternate text. I cannot figure out the problem, and any help is appreciated!
EDIT: The width of the image is 1000px, and the height is 300px. The css code sets the width of this tag in the header-img class.
To clarify, I have double checked the image name, and it is headerbanner.png, located in an images folder, which is in the same folder as the file with the image tag. The image div tag is larger than the image, but I don't think that would be a problem. This is a wordpress site running off of a local MAMP server.
|
2014/06/29
|
[
"https://Stackoverflow.com/questions/24475696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2622366/"
] |
PayPal will send notifications every month to your IPN Listener that should be specified and enabled in `Profile > My Selling Tools > Instant payment notifications`
Every recurring payment notification will contain `txn_type=subscr_payment`
|
In order to get IPN's for future transactions on recurring payments profile you'll need to make sure you have IPN configured in the PayPal account profile. It will **not** continually use the original NotifyURL value.
|
24,475,696 |
my image is not appearing on my site when my page loads, in any browser. My HTML code is
```
<HTML>
<img class="header-img" src="images/headerbanner.png" alt="App Image" />
</HTML>
```
The size and width of the div holding this are set in a css file. The images folder is located in the same directory as the file making this img tag call. However, whenever my page loads, the image appears with an icon in the middle, with no image showing, and only the alternate text. I cannot figure out the problem, and any help is appreciated!
EDIT: The width of the image is 1000px, and the height is 300px. The css code sets the width of this tag in the header-img class.
To clarify, I have double checked the image name, and it is headerbanner.png, located in an images folder, which is in the same folder as the file with the image tag. The image div tag is larger than the image, but I don't think that would be a problem. This is a wordpress site running off of a local MAMP server.
|
2014/06/29
|
[
"https://Stackoverflow.com/questions/24475696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2622366/"
] |
PayPal will send notifications every month to your IPN Listener that should be specified and enabled in `Profile > My Selling Tools > Instant payment notifications`
Every recurring payment notification will contain `txn_type=subscr_payment`
|
In my current testing with PayPal I see the following txn\_types;
txn\_type => recurring\_payment\_profile\_created
For the first time ONLY its created plus and then each recurring time, this notification for each payment cycle;
txn\_type => recurring\_payment
Plus as others have stated it will use the IPN URL specified in the PayPal profile.
When you first create the payment profile you will receive back a tracking code Profile ID and this is also sent at each notification. Look for [recurring\_payment\_id] and match against this in your database to keep track of what is happening to the subscription (changes/user cancellations etc).
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
Integer range is: –2,147,483,648 to 2,147,483,647
You are like way above it.
|
It is caused because you are using `int` for storing such big number.
As a result, the i [wraps](http://en.wikipedia.org/wiki/Integer_overflow) around itself, and never reaches the termination condition of the for loop.
When you exceed the limit for the data types in C/C++, funny things can happen.
The compiler can detect these things at compile time, and therefore, generates the code for infinite loop in assembly language.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
This happens because the maximum value of an `int` on your architecture can never reach 10000000000. It will overflow at some point before reaching that value. Thus, the condition `i < 10000000000` will always evaluate as true, meaning this is an infinite loop.
The compiler is able to deduct this at compile time, which is why it generates appropriate assembly for an infinite loop.
The compiler is able to warn you about this. For that to happen, you can enable the "extra" warning level with:
```
gcc -Wextra
```
GCC 4.8.2 for example will tell you:
```
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for (i = 0; i < 10000000000; ++i);
^
```
And it even tells you the specific warning option that exactly controls this type of warning (Wtype-limits).
|
It is caused because you are using `int` for storing such big number.
As a result, the i [wraps](http://en.wikipedia.org/wiki/Integer_overflow) around itself, and never reaches the termination condition of the for loop.
When you exceed the limit for the data types in C/C++, funny things can happen.
The compiler can detect these things at compile time, and therefore, generates the code for infinite loop in assembly language.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
This happens because the maximum value of an `int` on your architecture can never reach 10000000000. It will overflow at some point before reaching that value. Thus, the condition `i < 10000000000` will always evaluate as true, meaning this is an infinite loop.
The compiler is able to deduct this at compile time, which is why it generates appropriate assembly for an infinite loop.
The compiler is able to warn you about this. For that to happen, you can enable the "extra" warning level with:
```
gcc -Wextra
```
GCC 4.8.2 for example will tell you:
```
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for (i = 0; i < 10000000000; ++i);
^
```
And it even tells you the specific warning option that exactly controls this type of warning (Wtype-limits).
|
Integer range is: –2,147,483,648 to 2,147,483,647
You are like way above it.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
Integer range is: –2,147,483,648 to 2,147,483,647
You are like way above it.
|
Problem is:
You can't store such a large number in "i".
Look <https://en.wikipedia.org/wiki/Integer_%28computer_science%29> for more information.
"i" (the variable) can't reach 10000000000, thus the loop evaluates true always and runs infinite times.
You can either use a smaller number or another container for i, such as the multiprecision library of Boost:
<http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/intro.html>
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
Integer range is: –2,147,483,648 to 2,147,483,647
You are like way above it.
|
If 10000000000 is outside the range of int, but inside the range of long or long long, for your compiler, then i < 10000000000 casts i to long or long long before making the comparison.
Realising it will always be false, the compiler then removes the redundant comparison.
I should hope there'd been some sort of compiler warning.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
Integer range is: –2,147,483,648 to 2,147,483,647
You are like way above it.
|
This happens because the compiler sees that you are using a condition that can never be false, so the condition is simply never evaluated.
An `int` can never hold a value that is as large as `10000000000`, so the value will always be lower than that. When the variable reaches its maximum value and you try to increase it further, it will wrap around and start from its lowest possible value.
The same removal of the condition happens if you use a literal value of `true`:
```
for (i = 0; true; ++i);
```
The compiler will just make it a loop without a condition, it won't actually evaluate the `true` value on each iteration to see if it is still true.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
This happens because the maximum value of an `int` on your architecture can never reach 10000000000. It will overflow at some point before reaching that value. Thus, the condition `i < 10000000000` will always evaluate as true, meaning this is an infinite loop.
The compiler is able to deduct this at compile time, which is why it generates appropriate assembly for an infinite loop.
The compiler is able to warn you about this. For that to happen, you can enable the "extra" warning level with:
```
gcc -Wextra
```
GCC 4.8.2 for example will tell you:
```
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for (i = 0; i < 10000000000; ++i);
^
```
And it even tells you the specific warning option that exactly controls this type of warning (Wtype-limits).
|
Problem is:
You can't store such a large number in "i".
Look <https://en.wikipedia.org/wiki/Integer_%28computer_science%29> for more information.
"i" (the variable) can't reach 10000000000, thus the loop evaluates true always and runs infinite times.
You can either use a smaller number or another container for i, such as the multiprecision library of Boost:
<http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/intro.html>
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
This happens because the maximum value of an `int` on your architecture can never reach 10000000000. It will overflow at some point before reaching that value. Thus, the condition `i < 10000000000` will always evaluate as true, meaning this is an infinite loop.
The compiler is able to deduct this at compile time, which is why it generates appropriate assembly for an infinite loop.
The compiler is able to warn you about this. For that to happen, you can enable the "extra" warning level with:
```
gcc -Wextra
```
GCC 4.8.2 for example will tell you:
```
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for (i = 0; i < 10000000000; ++i);
^
```
And it even tells you the specific warning option that exactly controls this type of warning (Wtype-limits).
|
If 10000000000 is outside the range of int, but inside the range of long or long long, for your compiler, then i < 10000000000 casts i to long or long long before making the comparison.
Realising it will always be false, the compiler then removes the redundant comparison.
I should hope there'd been some sort of compiler warning.
|
21,217,886 |
I was running some tests to see how ++i and i++ translated to asm. I wrote a simple for :
```
int main()
{
int i;
for(i=0;i<1000000;++i);
return 0;
}
```
compiled it with **gcc test.c -O0 -o test**, and checked the asm with **objdump -d test**:
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) // i=0;
4004f7: eb 04 jmp 4004fd <main+0x11>
4004f9: 83 45 fc 01 addl $0x1,-0x4(%rbp) // ++i;
4004fd: 81 7d fc 3f 42 0f 00 cmpl $0xf423f,-0x4(%rbp) //
400504: 7e f3 jle 4004f9 <main+0xd> //i<1000000;
400506: b8 00 00 00 00 mov $0x0,%eax
40050b: 5d pop %rbp
40050c: c3 retq
```
so far so good. The weird thing (if i understand asm code correctly) was when instead of i<1000000 i wrote i<10000000000. Exactly same for loop with stopping condition i<10000000000 translated to following assembler code :
```
4004ed: 48 89 e5 mov %rsp,%rbp
4004f0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp)
4004f7: 83 45 fc 01 addl $0x1,-0x4(%rbp)
4004fb: eb fa jmp 4004f7 <main+0xb>
```
which is endless loop per my understanding, cause exactly same asm was generated for :
```
for(i=0;;++i);
```
The question is, is it really possible that it is compiled to endless loop? Why?
I'm using Ubuntu 13.04, x86\_64.
Thanks.
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21217886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2549281/"
] |
This happens because the maximum value of an `int` on your architecture can never reach 10000000000. It will overflow at some point before reaching that value. Thus, the condition `i < 10000000000` will always evaluate as true, meaning this is an infinite loop.
The compiler is able to deduct this at compile time, which is why it generates appropriate assembly for an infinite loop.
The compiler is able to warn you about this. For that to happen, you can enable the "extra" warning level with:
```
gcc -Wextra
```
GCC 4.8.2 for example will tell you:
```
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for (i = 0; i < 10000000000; ++i);
^
```
And it even tells you the specific warning option that exactly controls this type of warning (Wtype-limits).
|
This happens because the compiler sees that you are using a condition that can never be false, so the condition is simply never evaluated.
An `int` can never hold a value that is as large as `10000000000`, so the value will always be lower than that. When the variable reaches its maximum value and you try to increase it further, it will wrap around and start from its lowest possible value.
The same removal of the condition happens if you use a literal value of `true`:
```
for (i = 0; true; ++i);
```
The compiler will just make it a loop without a condition, it won't actually evaluate the `true` value on each iteration to see if it is still true.
|
64,269,724 |
i need to format this date on the template because comes from the database on a dictionary.
I got this date displayed on my template:
```
1996-08-22
```
And i want to be like this:
```
22-08-1996
```
here is my code for it :
```
{{date['Fundação'] }}
```
I try to use with strftime but i got an error:
```
{{date['Fundação']|strftime('%d-%m-%Y')}}
```
The error:
```
jinja2.exceptions.TemplateAssertionError: no filter named 'strftime'
```
|
2020/10/08
|
[
"https://Stackoverflow.com/questions/64269724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14067494/"
] |
Do you mean something like below?
```
aggregate(
cbind(value, cluster) ~ .,
do.call(rbind, lapply(list.files(pattern = "*.csv"), read.csv)),
sum
)
```
|
An option with `tidyverse` would be to read the csv files with `read_csv` from `readr`, row bind (`_dfr`), grouped by 'x', 'y' columns, get the `sum` of the numeric columns
```
library(purrr)
library(readr)
library(dplyr)
files <- list.files(pattern = "\\.csv$")
map_dfr(files, read_csv) %>%
group_by(x, y) %>%
summarise(across(where(is.numeric), sum, na.rm = TRUE))
```
---
If we want to do this in parallel, use `future.apply`
```
library(future.apply)
future::plan(multiprocess, workers = length(files))
options(future.globals.maxSize= +Inf)
out <- future.apply::future_Map(files, read_csv)
future::plan(sequential)
bind_rows(out) %>%
group_by(x, y) %>%
summarise(across(where(is.numeric), sum, na.rm = TRUE))
```
---
Or make use of `parallel`
```
ncores <- min(parallel::detectCores(), length(files))
cl <- parallel::makeCluster(ncores, type = "SOCK")
doSNOW::registerDoSNOW(cl)
out2 <- foreach(i = seq_along(files),
.packages = c("data.table")) %dopar% {
fread(files[i])
}
parallel::stopCluster(cl)
library(data.table_
rbindlist(out2)[, lapply(.SD, sum, na.rm = TRUE), .(x, y)]
```
|
13,640,099 |
I got this error for some reason:
```
{
"error": {
"message": "(#4) Application request limit reached",
"type": "OAuthException",
"code": 4
}
}
```
From my investigation, daily request limit seem to be 100m requests. The Insights -> Developer -> Activity and Errors does not update in realtime (lagging by 4 days), there isn't any restrictions/throttling/errors to speak of. The highest request rate I had was on 21st, and it is 500k and I don't think i got any request limits reached errors (error highest was 1000 errors that day).
Any idea what I could be doing to resolve this? Or at least find out what limits are to my app?
|
2012/11/30
|
[
"https://Stackoverflow.com/questions/13640099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60893/"
] |
I have same error.
I think there is a facebook bug: <https://developers.facebook.com/bugs/442544732471951?browse=search_50bc5133cf13d5c74557627>
Please subscribe to this error to solve it quickly...
|
Quote from here: [Facebook Application Request limit reached](https://stackoverflow.com/questions/9272391/facebook-application-request-limit-reached)
>
> There is a limit, but it's pretty high, it should be difficult to hit unless they're using the same access tokens for all calls and not caching results, etc. **It's 600 calls per 600 seconds per access token.**
>
>
>
|
3,080 |
I have a post written in Microsoft Word with images, text and some formating. Is there some easy way to import this document into WordPress? Either a plugin for Word og perhaps a plugin inside WordPress?
I'm looking for something simple that also converts images.
|
2010/10/20
|
[
"https://wordpress.stackexchange.com/questions/3080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88/"
] |
There are 3 ways you can import content from Word:
Paste from Word
---------------
There's a button in the editor that allows you to paste content directly from Word. This removes the special formatting Word uses to lay content out on the page and will make things work well on your site. (The button is in the "Kitchen Sink" on the Visual editor and is circled in the image below.)

**Drawback:** you'll have to manually upload and re-add your images.
HTML Editor
-----------
You can also copy-paste your text into the HTML mode of the editor and it will automatically strip out the special formatting Word uses.
**Drawback:** you'll have to manually upload and re-add your images, and you might lose some paragraph spacing in the transfer.
[Windows Live Writer](http://explore.live.com/windows-live-writer)
------------------------------------------------------------------
The *best* option would be to use the **free** [Live Writer](http://explore.live.com/windows-live-writer) application from Windows. This is a standalone desktop application that will take in content from Word almost perfectly (including images), allow you to tag, categorize, and set up your post, then remotely publish it on your site. Live Writer will also upload your images for you and automatically position them in the content just the way you had them laid out in the editor.
**Drawback:** Live Writer only runs on Windows ... so if you're an Apple fan, you're out of luck :-(
|
There is a "Paste from Word" button in the editor but in my experience, it has been buggy. If you want clean code, your best bet is to just re-create your content within the editor. On the flip side, if you paste from Word, you'll end up editing and fixing its code so much that you'll have wished you just rewrote it in the first place.
|
3,080 |
I have a post written in Microsoft Word with images, text and some formating. Is there some easy way to import this document into WordPress? Either a plugin for Word og perhaps a plugin inside WordPress?
I'm looking for something simple that also converts images.
|
2010/10/20
|
[
"https://wordpress.stackexchange.com/questions/3080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88/"
] |
There are 3 ways you can import content from Word:
Paste from Word
---------------
There's a button in the editor that allows you to paste content directly from Word. This removes the special formatting Word uses to lay content out on the page and will make things work well on your site. (The button is in the "Kitchen Sink" on the Visual editor and is circled in the image below.)

**Drawback:** you'll have to manually upload and re-add your images.
HTML Editor
-----------
You can also copy-paste your text into the HTML mode of the editor and it will automatically strip out the special formatting Word uses.
**Drawback:** you'll have to manually upload and re-add your images, and you might lose some paragraph spacing in the transfer.
[Windows Live Writer](http://explore.live.com/windows-live-writer)
------------------------------------------------------------------
The *best* option would be to use the **free** [Live Writer](http://explore.live.com/windows-live-writer) application from Windows. This is a standalone desktop application that will take in content from Word almost perfectly (including images), allow you to tag, categorize, and set up your post, then remotely publish it on your site. Live Writer will also upload your images for you and automatically position them in the content just the way you had them laid out in the editor.
**Drawback:** Live Writer only runs on Windows ... so if you're an Apple fan, you're out of luck :-(
|
What about when we have images and formatted content? For advance importing of documents into WordPress Editor, there is a plugin called "Document Importer by Plugmatter" which allows you to import the entire content along with it images, bold & italic words, underlines, etc. It retains all your formatting and does its job in seconds.
|
3,378,166 |
I have designed a Class for Parent Child relationship
```
class Category
{
public string CatName;
public string CatId;
public IList<Category> childCategory = new List<Category>();
public void addChildCat(Category childCat)
{
this.childCategory.Add(childCat);
}
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
}
```
Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories
1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
2. Is my class design GOOD?
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3378166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922388/"
] |
You can use the [SortedList](http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx) to keep track of the child categories instead.
|
If I understand this, we have a tree structure right? And what is the result you are expecting, the sorted children of the topmost parent (root)?
|
3,378,166 |
I have designed a Class for Parent Child relationship
```
class Category
{
public string CatName;
public string CatId;
public IList<Category> childCategory = new List<Category>();
public void addChildCat(Category childCat)
{
this.childCategory.Add(childCat);
}
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
}
```
Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories
1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
2. Is my class design GOOD?
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3378166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922388/"
] |
You can't because you have not a reference to the parent. You have to add a field:
```
public Category Parent { get; set; }
```
and modify the add method to set the parent:
```
public void addChildCat(Category childCat)
{
childCat.Parent = this;
this.childCategory.Add(childCat);
}
```
You need the parent to get the root:
```
public static Category SortedCategory(Category cat)
{
// get the root
var root = cat;
while(root.Parent != null) root = root.Parent;
return root.GetSorted();
}
private Category GetSorted()
{
var sortedChildren = new List<Category>(childCategories).ConvertAll(c => c.GetSorted());
sortedChildren.Sort((c1, c2) => c1.CatName.CompareTo(c2.Catname));
return new Category { CatName = root.CatName,
Catid = root.CatId,
childCategories = sortedChildren; }
}
```
|
You can use the [SortedList](http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx) to keep track of the child categories instead.
|
3,378,166 |
I have designed a Class for Parent Child relationship
```
class Category
{
public string CatName;
public string CatId;
public IList<Category> childCategory = new List<Category>();
public void addChildCat(Category childCat)
{
this.childCategory.Add(childCat);
}
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
}
```
Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories
1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
2. Is my class design GOOD?
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3378166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922388/"
] |
You can use the [SortedList](http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx) to keep track of the child categories instead.
|
Instead of :
```
public string CatName;
public string CatId;
```
I would do:
```
class Cat
{
public string Name { get; set; }
public string Id { get; set; }
}
```
And instead of:
```
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
```
I would do:
```
var category = new List<Cat>
{
new Cat() {Name = "cat1", Id = "123"},
new Cat() {Name = "cat2", Id = "124"},
new Cat() {Name = "cat3", Id = "125"},
new Cat() {Name = "cat4", Id = "126"}
};
category.Sort(( cat1, cat2) => ((Convert.ToInt32(cat1.Id) > Convert.ToInt32(cat2.Id)) ? 1 : 0) );
```
|
3,378,166 |
I have designed a Class for Parent Child relationship
```
class Category
{
public string CatName;
public string CatId;
public IList<Category> childCategory = new List<Category>();
public void addChildCat(Category childCat)
{
this.childCategory.Add(childCat);
}
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
}
```
Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories
1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
2. Is my class design GOOD?
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3378166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922388/"
] |
You can't because you have not a reference to the parent. You have to add a field:
```
public Category Parent { get; set; }
```
and modify the add method to set the parent:
```
public void addChildCat(Category childCat)
{
childCat.Parent = this;
this.childCategory.Add(childCat);
}
```
You need the parent to get the root:
```
public static Category SortedCategory(Category cat)
{
// get the root
var root = cat;
while(root.Parent != null) root = root.Parent;
return root.GetSorted();
}
private Category GetSorted()
{
var sortedChildren = new List<Category>(childCategories).ConvertAll(c => c.GetSorted());
sortedChildren.Sort((c1, c2) => c1.CatName.CompareTo(c2.Catname));
return new Category { CatName = root.CatName,
Catid = root.CatId,
childCategories = sortedChildren; }
}
```
|
If I understand this, we have a tree structure right? And what is the result you are expecting, the sorted children of the topmost parent (root)?
|
3,378,166 |
I have designed a Class for Parent Child relationship
```
class Category
{
public string CatName;
public string CatId;
public IList<Category> childCategory = new List<Category>();
public void addChildCat(Category childCat)
{
this.childCategory.Add(childCat);
}
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
}
```
Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories
1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
2. Is my class design GOOD?
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3378166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922388/"
] |
You can't because you have not a reference to the parent. You have to add a field:
```
public Category Parent { get; set; }
```
and modify the add method to set the parent:
```
public void addChildCat(Category childCat)
{
childCat.Parent = this;
this.childCategory.Add(childCat);
}
```
You need the parent to get the root:
```
public static Category SortedCategory(Category cat)
{
// get the root
var root = cat;
while(root.Parent != null) root = root.Parent;
return root.GetSorted();
}
private Category GetSorted()
{
var sortedChildren = new List<Category>(childCategories).ConvertAll(c => c.GetSorted());
sortedChildren.Sort((c1, c2) => c1.CatName.CompareTo(c2.Catname));
return new Category { CatName = root.CatName,
Catid = root.CatId,
childCategories = sortedChildren; }
}
```
|
Instead of :
```
public string CatName;
public string CatId;
```
I would do:
```
class Cat
{
public string Name { get; set; }
public string Id { get; set; }
}
```
And instead of:
```
public Category SortedCategory(Category cat)
{
// Should return the sorted cat i.e topmost parent
}
```
I would do:
```
var category = new List<Cat>
{
new Cat() {Name = "cat1", Id = "123"},
new Cat() {Name = "cat2", Id = "124"},
new Cat() {Name = "cat3", Id = "125"},
new Cat() {Name = "cat4", Id = "126"}
};
category.Sort(( cat1, cat2) => ((Convert.ToInt32(cat1.Id) > Convert.ToInt32(cat2.Id)) ? 1 : 0) );
```
|
64,522,740 |
I read a lot about switchmap and its purpose but I did not see a lot of examples when it comes to subscribing to the new data.
So I use a nested subscription in my Angular project and I wanted to ask you how to use switchmap properly in my example to understand the concept better.
Here my nested subscription:
```
this.sharedSrv.postDetail.subscribe(async post => {
if(post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
this.userSrv.getUserAsObservable().subscribe(user => {
if(user){
if(this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id).subscribe(interaction => {
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
});
console.log(user);
this.isLoggedIn = true
} else {
this.isLoggedIn = false;
}
})
})
```
How would I use switchmap correctly here?
Any help is appreciated.
|
2020/10/25
|
[
"https://Stackoverflow.com/questions/64522740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14306879/"
] |
There are multiple things to notice here
1. Looks like the outer observable `this.sharedSrv.postDetail` and `this.userSrv.getUserAsObservable()` are unrelated. In that case you could also use RxJS `forkJoin` to trigger the observables in parallel. Since you've asked for `switchMap`, you could try the following
```js
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
this.sharedSrv.postDetail.pipe(
switchMap(post => {
if (post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable();
}),
switchMap(user => {
if (user) {
if (this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
console.log(user);
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id);
}
return of(null); // <-- emit `null` if `user` is undefined
})
).subscribe(
interaction => {
if(!!interaction) { // <-- only proceed if `interaction` is defined
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
this.isLoggedIn = true;
} else { // <-- set `isLoggedIn` to false if `user` was undefined
this.isLoggedIn = false;
}
}
);
```
2. I assume you're converting the observable to a promise using `async`. First I'd recommend you not to mix observables and promises unless absolutely necessary. Second you could use RxJS `from` function to convert an observable to a promise.
```js
import { from, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
const obs$ = this.sharedSrv.postDetail.pipe(
switchMap(post => {
if (post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable();
}),
switchMap(user => {
if (user) {
if (this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
console.log(user);
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id);
}
return of(null); // <-- emit `null` if `user` is undefined
})
);
from(obs$).then(
interaction => {
...
}
);
```
|
Looks like what you want:
```
this.sharedSrv.postDetail.pipe(
switchMap(post => {
if (post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable();
}),
swtichMap(user => {
this.isLoggedIn = false;
if (user) {
if (this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
this.isLoggedIn = true;
console.log(user);
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id);
} else {
return of(null);
}
}).subscribe(interaction => {
if (!interaction) return;
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
})
);
```
|
64,522,740 |
I read a lot about switchmap and its purpose but I did not see a lot of examples when it comes to subscribing to the new data.
So I use a nested subscription in my Angular project and I wanted to ask you how to use switchmap properly in my example to understand the concept better.
Here my nested subscription:
```
this.sharedSrv.postDetail.subscribe(async post => {
if(post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
this.userSrv.getUserAsObservable().subscribe(user => {
if(user){
if(this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id).subscribe(interaction => {
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
});
console.log(user);
this.isLoggedIn = true
} else {
this.isLoggedIn = false;
}
})
})
```
How would I use switchmap correctly here?
Any help is appreciated.
|
2020/10/25
|
[
"https://Stackoverflow.com/questions/64522740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14306879/"
] |
There are multiple things to notice here
1. Looks like the outer observable `this.sharedSrv.postDetail` and `this.userSrv.getUserAsObservable()` are unrelated. In that case you could also use RxJS `forkJoin` to trigger the observables in parallel. Since you've asked for `switchMap`, you could try the following
```js
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
this.sharedSrv.postDetail.pipe(
switchMap(post => {
if (post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable();
}),
switchMap(user => {
if (user) {
if (this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
console.log(user);
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id);
}
return of(null); // <-- emit `null` if `user` is undefined
})
).subscribe(
interaction => {
if(!!interaction) { // <-- only proceed if `interaction` is defined
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
this.isLoggedIn = true;
} else { // <-- set `isLoggedIn` to false if `user` was undefined
this.isLoggedIn = false;
}
}
);
```
2. I assume you're converting the observable to a promise using `async`. First I'd recommend you not to mix observables and promises unless absolutely necessary. Second you could use RxJS `from` function to convert an observable to a promise.
```js
import { from, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
const obs$ = this.sharedSrv.postDetail.pipe(
switchMap(post => {
if (post) {
this.hasPost = true;
this.post = post;
}
console.log(post);
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable();
}),
switchMap(user => {
if (user) {
if (this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
console.log(user);
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id);
}
return of(null); // <-- emit `null` if `user` is undefined
})
);
from(obs$).then(
interaction => {
...
}
);
```
|
To transform `Observables` you need to use `piping` i.e call the `pipe()` method on the observable and pass in the an `rxjs` transformation operator
Example we can transform your code to
```typescript
this.sharedSrv.postDetail.pipe(
switchMap(post => {
if(post) {
this.hasPost = true;
this.post = post;
}
this.viewedMainComment = null;
this.viewedSubComments = [];
return this.userSrv.getUserAsObservable())
}),
switchMap(
user => {
if(user) {
if(this.post.user.id == user.id) this.isOwnPost = true;
this.user = user;
return this.postsSrv.getPostInteraction(this.user.id, this.post.id, this.post.user.id)
} else {
this.isLoggedIn = false;
return of (null) // You need import { of } from 'rxjs'
}
}
)),
tap( interaction => {
if(interaction) {
this.hasSubscribed = interaction["hasSubscribed"];
this.wasLiked = interaction["wasLiked"];
this.wasDisliked = interaction["wasDisliked"];
this.hasSaved = interaction["hasSaved"];
}
})
).subscribe()
```
|
17,614,720 |
I read an [interesting post](http://csswizardry.com/2013/05/hashed-classes-in-css/) on using a css classname instead of the id attribute for identifying modules or widgets. The css classname could be prefixed with a hash or underscore, to indicate that the classname is used as an id. The reason for this being, that ids can only be used once per webpage whereas a module or widget could appear multiple times.
**Simple Example**
Instead of using ids such as
```
<div id="currencyConverter1" class="foo">EUR/USD</div>
<div id="currencyConverter2" class="foo">GB/USD</div>
```
prefixed classnames are used
```
<div class="#currencyConverter foo">EUR/USD</div>
<div class="#currencyConverter foo">GB/USD</div>
```
In the [article](http://csswizardry.com/2013/05/hashed-classes-in-css/) it suggests, that an underscore could be used instead of a hash, because hashes need to be escaped.
I quite like this idea, but I'm not sure if this is good practice or has any drawbacks. What is the general opinion on this?
|
2013/07/12
|
[
"https://Stackoverflow.com/questions/17614720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315260/"
] |
It doesn't get simpler than this: **does it uniquely identify an element within a document tree now and forever? Use an ID. If not, use a class name.**
Remember that IDs and classes are properties pertaining to *each element*, not a group of elements collectively. Using "identifier" to mean "identifying a *group* of elements" is futile; that's why you have class names instead, to *classify* those elements as being related in some manner.
If you're "identifying" elements that are *members of a specific widget or module*, you have free reign to add a class name to each element representing that widget or module, and select it in addition to the element's class:
```
<div class="my-module foo">.my-module.foo</div>
<div class="my-module bar">.my-module.bar</div>
```
Or, if specificity is such a huge issue that you can't even afford to stack another class selector to your rules, prefix the element's class name with the name of that module and select it.
```
<div class="my-module-foo">.my-module-foo</div>
<div class="my-module-bar">.my-module-bar</div>
```
If that's the question, then yes, it's perfectly legitimate — as I've mentioned, that's the whole *point* of class names and selectors.
But there are no legitimate benefits to making a class selector "look like" an ID selector without functioning like one. What it does cause, on the other hand, is needless confusion, especially for other authors who may not know better. If you want to avoid ID selectors like the plague, *fine*, leave them alone; nobody's forcing you to use them. But if you want to *uniquely identify* singular elements, then you may want to remember that CSS already provides a feature for that to complement the `id` attribute in HTML, known as the [ID selector](http://www.w3.org/TR/selectors/#id-selectors). There's no need to hack other parts of the selector syntax to emulate some other feature that's already readily available to you and has been since [the very beginning](http://www.w3.org/TR/CSS1/#id-as-selector).
Incidentally, if you're running into specificity issues with your CSS rules, then it's your CSS rules that need refactoring, not your markup. Hacking your markup to accommodate your style rules only leads to further trouble, at least in my experience. (I understand the irony in saying this given that hashes are allowed in identifiers starting with HTML5.)
|
Its mostly driven by your own, personal taste. there are a lot of opinions and articles on this topic, even complete books were written.
I suggest the following:
[SMACSS](http://smacss.com/)
[OOCSS](http://oocss.org/)
[MVCSS](http://mvcss.github.io/styleguide/naming/)
All of them are mentioning a more-or-less similiar naming convention for CSS, while also saying that these are just rules of thumb, not dogmas.
personally, i follow that approach:
```
.modName // module
.modName__sub // an object or sub-module
.modName__sub--modifier // a modifier
```
A similiar structure is used for example by InuitCSS
If you want to use classnames as unique identifiers, than just do it, there is nothing wrong about that. Further, it is future proof in case that you wish to use it as a "standard" class. However, i would shirk that hash for obvious reasons.
|
17,614,720 |
I read an [interesting post](http://csswizardry.com/2013/05/hashed-classes-in-css/) on using a css classname instead of the id attribute for identifying modules or widgets. The css classname could be prefixed with a hash or underscore, to indicate that the classname is used as an id. The reason for this being, that ids can only be used once per webpage whereas a module or widget could appear multiple times.
**Simple Example**
Instead of using ids such as
```
<div id="currencyConverter1" class="foo">EUR/USD</div>
<div id="currencyConverter2" class="foo">GB/USD</div>
```
prefixed classnames are used
```
<div class="#currencyConverter foo">EUR/USD</div>
<div class="#currencyConverter foo">GB/USD</div>
```
In the [article](http://csswizardry.com/2013/05/hashed-classes-in-css/) it suggests, that an underscore could be used instead of a hash, because hashes need to be escaped.
I quite like this idea, but I'm not sure if this is good practice or has any drawbacks. What is the general opinion on this?
|
2013/07/12
|
[
"https://Stackoverflow.com/questions/17614720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315260/"
] |
It doesn't get simpler than this: **does it uniquely identify an element within a document tree now and forever? Use an ID. If not, use a class name.**
Remember that IDs and classes are properties pertaining to *each element*, not a group of elements collectively. Using "identifier" to mean "identifying a *group* of elements" is futile; that's why you have class names instead, to *classify* those elements as being related in some manner.
If you're "identifying" elements that are *members of a specific widget or module*, you have free reign to add a class name to each element representing that widget or module, and select it in addition to the element's class:
```
<div class="my-module foo">.my-module.foo</div>
<div class="my-module bar">.my-module.bar</div>
```
Or, if specificity is such a huge issue that you can't even afford to stack another class selector to your rules, prefix the element's class name with the name of that module and select it.
```
<div class="my-module-foo">.my-module-foo</div>
<div class="my-module-bar">.my-module-bar</div>
```
If that's the question, then yes, it's perfectly legitimate — as I've mentioned, that's the whole *point* of class names and selectors.
But there are no legitimate benefits to making a class selector "look like" an ID selector without functioning like one. What it does cause, on the other hand, is needless confusion, especially for other authors who may not know better. If you want to avoid ID selectors like the plague, *fine*, leave them alone; nobody's forcing you to use them. But if you want to *uniquely identify* singular elements, then you may want to remember that CSS already provides a feature for that to complement the `id` attribute in HTML, known as the [ID selector](http://www.w3.org/TR/selectors/#id-selectors). There's no need to hack other parts of the selector syntax to emulate some other feature that's already readily available to you and has been since [the very beginning](http://www.w3.org/TR/CSS1/#id-as-selector).
Incidentally, if you're running into specificity issues with your CSS rules, then it's your CSS rules that need refactoring, not your markup. Hacking your markup to accommodate your style rules only leads to further trouble, at least in my experience. (I understand the irony in saying this given that hashes are allowed in identifiers starting with HTML5.)
|
Not sure what your modules or widgets are for (wordpress?) but the methodology I choose to use when coding is this:
1: If it is DOM element that has a specific function that I know will only appear once on the page, then I use an ID (things like #main\_navigation, #global\_header).
2: The DOM element is used for styling purposes (CSS) then I use class names. I keep class names as descriptive of what the DOM element is doing as I can. I don't use vauge names like .blue\_text (explained below).
3: I need to attach some sort of information to the DOM element that is kind of awkward and doesn't fit this scheme, then I use custom HTML data attributes. For example, if I create a backend for a site and a user can pick a background color for a div, instead of putting `.user_selected_background_color_class` as a class in the div I will instead write `data="user_selected_color"`. This is a kind of lame example, but I just built something where a user can select a bunch of images to be in gallery mode or slideshow mode and I used data attributes to determine how the container div should be styled.
|
29,609,845 |
I am working on Jasper Report. I need to ask from a user where to save the generated report. For that, I need to open a "Save As" dialog box. I tried it using `JFileChooser` and `FileDialog`.
But, during execution of my code, when execution reaches the point where the code for the Save As dialog box is written, the code remains stuck there. One thing I noticed is that if you run the `JFileChooser` and `FileDialog` code for an open dialog box in a separate java class with its own PSVM, it works well.
But when it is invoked by some other function, execution remain stuck there.
Is there any plugin or jar I need to add to use JFileChooser and FileDialog? Or something else I am missing?
I am using eclipse Java EE kepler and Spring MVC.
|
2015/04/13
|
[
"https://Stackoverflow.com/questions/29609845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4783729/"
] |
It works now. You just need delete playSound() from onCreate() and put it to onResume() since onResume() is always called before Activity get to the foreground.
Reference: <http://developer.android.com/reference/android/app/Activity.html>
|
`04-13 14:55:29.934 32338 32338 E AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.PowerManager$WakeLock.isHeld()' on a null object reference`
If you read carefully here you can see that the problem is on `isHeld()`
Just add a check on your `wl` just like you did on `mp`.
Something like
```
if(wl != null){
if(wl.isHeld()){
wl.release();
}
}
```
|
29,609,845 |
I am working on Jasper Report. I need to ask from a user where to save the generated report. For that, I need to open a "Save As" dialog box. I tried it using `JFileChooser` and `FileDialog`.
But, during execution of my code, when execution reaches the point where the code for the Save As dialog box is written, the code remains stuck there. One thing I noticed is that if you run the `JFileChooser` and `FileDialog` code for an open dialog box in a separate java class with its own PSVM, it works well.
But when it is invoked by some other function, execution remain stuck there.
Is there any plugin or jar I need to add to use JFileChooser and FileDialog? Or something else I am missing?
I am using eclipse Java EE kepler and Spring MVC.
|
2015/04/13
|
[
"https://Stackoverflow.com/questions/29609845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4783729/"
] |
It works now. You just need delete playSound() from onCreate() and put it to onResume() since onResume() is always called before Activity get to the foreground.
Reference: <http://developer.android.com/reference/android/app/Activity.html>
|
Quick answer:
```
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
//stop music
mediaPlayer.stop();
mediaPlayer.reset();
}
```
|
55,749,867 |
I have two classes. I want to access `type` property of Parent from instance:
```js
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
```
I know how to solve it and access `type`, but...
```js
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
```
...but why it doesn't work in the first example? Is it possible to achieve it without using `Animal.apply`?
|
2019/04/18
|
[
"https://Stackoverflow.com/questions/55749867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114926/"
] |
Try this:
```
your_find_command | tail -n 1
```
|
There could be multiple ways to achieve this -
**Using the 'tail' command** (as suggested by @Roadowl)
find branches -name alex\* | tail -n1
**Using the 'awk' command**
find branches -name alex\* | awk 'END{print}'
**Using the 'sed' command**
find branches -name alex\* | sed -e '$!d'
Other possible options are to use a bash script, perl or any other language. You best bet would be the one that you find is more convenient.
|
55,749,867 |
I have two classes. I want to access `type` property of Parent from instance:
```js
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
```
I know how to solve it and access `type`, but...
```js
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
```
...but why it doesn't work in the first example? Is it possible to achieve it without using `Animal.apply`?
|
2019/04/18
|
[
"https://Stackoverflow.com/questions/55749867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114926/"
] |
Try this:
```
your_find_command | tail -n 1
```
|
Since you want the file name sorted by the highest version, you can try as follows
```
$ ls
alex20_0 alex20_1 alex20_2 alex20_3
$ find . -iname "*alex*" -print | sort | tail -n 1
./alex20_3
```
|
55,749,867 |
I have two classes. I want to access `type` property of Parent from instance:
```js
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
```
I know how to solve it and access `type`, but...
```js
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
```
...but why it doesn't work in the first example? Is it possible to achieve it without using `Animal.apply`?
|
2019/04/18
|
[
"https://Stackoverflow.com/questions/55749867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114926/"
] |
Try this:
```
your_find_command | tail -n 1
```
|
`find` can list your files in any order. To extract the latest version you have to sort the output of `find`. The safest way to do this is
```
find . -maxdepth 1 -name "string" -print0 | sort -zV | tail -zn1
```
If your implementation of `sort` or `tail` does not support `-z` and you are sure that the filenames are free of line-breaks you can also use
```
find . -maxdepth 1 -name "string" -print | sort -V | tail -n1
```
|
55,749,867 |
I have two classes. I want to access `type` property of Parent from instance:
```js
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
```
I know how to solve it and access `type`, but...
```js
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
```
...but why it doesn't work in the first example? Is it possible to achieve it without using `Animal.apply`?
|
2019/04/18
|
[
"https://Stackoverflow.com/questions/55749867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114926/"
] |
`find` can list your files in any order. To extract the latest version you have to sort the output of `find`. The safest way to do this is
```
find . -maxdepth 1 -name "string" -print0 | sort -zV | tail -zn1
```
If your implementation of `sort` or `tail` does not support `-z` and you are sure that the filenames are free of line-breaks you can also use
```
find . -maxdepth 1 -name "string" -print | sort -V | tail -n1
```
|
There could be multiple ways to achieve this -
**Using the 'tail' command** (as suggested by @Roadowl)
find branches -name alex\* | tail -n1
**Using the 'awk' command**
find branches -name alex\* | awk 'END{print}'
**Using the 'sed' command**
find branches -name alex\* | sed -e '$!d'
Other possible options are to use a bash script, perl or any other language. You best bet would be the one that you find is more convenient.
|
55,749,867 |
I have two classes. I want to access `type` property of Parent from instance:
```js
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
```
I know how to solve it and access `type`, but...
```js
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
```
...but why it doesn't work in the first example? Is it possible to achieve it without using `Animal.apply`?
|
2019/04/18
|
[
"https://Stackoverflow.com/questions/55749867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114926/"
] |
`find` can list your files in any order. To extract the latest version you have to sort the output of `find`. The safest way to do this is
```
find . -maxdepth 1 -name "string" -print0 | sort -zV | tail -zn1
```
If your implementation of `sort` or `tail` does not support `-z` and you are sure that the filenames are free of line-breaks you can also use
```
find . -maxdepth 1 -name "string" -print | sort -V | tail -n1
```
|
Since you want the file name sorted by the highest version, you can try as follows
```
$ ls
alex20_0 alex20_1 alex20_2 alex20_3
$ find . -iname "*alex*" -print | sort | tail -n 1
./alex20_3
```
|
33,468,687 |
I need to seperate the inputs of the address, zip and city. Now I would like to know how I can gelocate. At the Google Devleloper [documentation](https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple) there is only one input field. Does anybody know how I can geolocate with three input fields?
|
2015/11/01
|
[
"https://Stackoverflow.com/questions/33468687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4944595/"
] |
you just need to use the same function to change the colour back to the original(or a new colour)
```
$pdf->SetFont($pdfFont, 'B', 10);
$pdf->SetFillColor(59,78,135);
$pdf->SetTextColor(0,0,0);
$pdf->Cell(50, 6, strtoupper(Lang::trans('supportticketsclient')), 0, 1, 'L', true);
$pdf->SetTextColor(255,255,255);//change back to black
```
|
I have the same problem on changing the text in a cell to Upper-Case..
What I did was convert it on my query
```
$appName = $row['appFname']." ".$row['appMname']. " ".$row['appLname'];
$appNameUPPER = strtoupper($appName);
```
then I used that variable on my cell
```
$pdf->Cell(179,26,''.$appNameUPPER.'', 'B','', 'C', '','','','','','B');
```
then it works! Try converting it on your query~
It's my first time to answer here hope it works on you (^\_^)/
|
29,829,279 |
I have this error:
>
> The specified child already has a parent. You must call removeView()
> on the child's parent first.
>
>
>
When I clicked `buildNot.setPosiviteButton`.
Help me please, thanks guys!
This is my Java source code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
alertDers.show();
}
});
}
```
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29829279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4784098/"
] |
Use extended regex flag in grep.
For example:
```
grep -E abc_source.?_201501.csv
```
would source out both lines in your example. You can think of other regex patterns that would suit your data more.
|
You can use Bash [globbing](http://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm) to grep in several files at once.
For example, to grep for the string "hello" in all files with a filename that starts with abc\_source and ends with 201501.csv, issue this command:
```
grep hello abc_source*201501.csv
```
You can also use the -r flag, to recursively grep in all files below a given folder - for example the current folder (.).
```
grep -r hello .
```
|
29,829,279 |
I have this error:
>
> The specified child already has a parent. You must call removeView()
> on the child's parent first.
>
>
>
When I clicked `buildNot.setPosiviteButton`.
Help me please, thanks guys!
This is my Java source code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
alertDers.show();
}
});
}
```
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29829279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4784098/"
] |
Use extended regex flag in grep.
For example:
```
grep -E abc_source.?_201501.csv
```
would source out both lines in your example. You can think of other regex patterns that would suit your data more.
|
If you are asking about patterns for file name matching in the shell, the [extended globbing](http://mywiki.wooledge.org/glob#extglob) facility in Bash lets you say
```
shopt -s extglob
grep stuff abc_source@(|2)_201501.csv
```
to search through both files with a single glob expression.
|
29,829,279 |
I have this error:
>
> The specified child already has a parent. You must call removeView()
> on the child's parent first.
>
>
>
When I clicked `buildNot.setPosiviteButton`.
Help me please, thanks guys!
This is my Java source code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
alertDers.show();
}
});
}
```
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29829279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4784098/"
] |
Use extended regex flag in grep.
For example:
```
grep -E abc_source.?_201501.csv
```
would source out both lines in your example. You can think of other regex patterns that would suit your data more.
|
The simplest possibility is to use brace expansion:
```
grep pattern abc_{source,source2}_201501.csv
```
That's exactly the same as:
```
grep pattern abc_source{,2}_201501.csv
```
You can use several brace patterns in a single word:
```
grep pattern abc_source{,2}_2015{01..04}.csv
```
expands to
```
grep pattern abc_source_201501.csv abc_source_201502.csv \
abc_source_201503.csv abc_source_201504.csv \
abc_source2_201501.csv abc_source2_201502.csv \
abc_source2_201503.csv abc_source2_201504.csv
```
|
7,452,489 |
I love an Emacs feature to copy selection to clipboard automatically. Is it possible to do the same on Eclipse?
Environment: Windows XP, Helios
|
2011/09/17
|
[
"https://Stackoverflow.com/questions/7452489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/949869/"
] |
To copy a String from Eclipse to the clipboard, you can use
```
void copyToClipboard (String toClipboard, Display display){
String toClipboard = "my String";
Clipboard clipboard = new Clipboard(display);
TextTransfer [] textTransfer = {TextTransfer.getInstance()};
clipboard.setContents(new Object [] {toClipboard}, textTransfer);
clipboard.dispose();
}
```
Then you can call this method from a `MouseAdapter` or `KeyAdapter`, depending on where you want to get your String from. In your case it could be `MouseAdapter`, which listens to doubleclicks, gets the current cursor position of the text, marks the word and then adds the String to the clipboard.
edit to answer a question: You can set up your own `MouseAdapater` and attach it to buttons, text fields or whateer you like. Here's an example for a button:
```
Button btnGo1 = new Button(parent, SWT.NONE);
btnGo1.setText("Go");
btnGo1.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
//do what you want to do in here
}
});
```
If you want to implement mouseUp and mouseDown events, too, you can just add `MouseListener`instead of the Adapter. The only advantage of the Adapter is, that you don't have to override the other methods of the interface.
Since the original question was to automatically get the selection of the text of an editor: the way to get the selection from an editor is explained [here](https://stackoverflow.com/questions/2395928/grab-selected-text-from-eclipse-java-editor).
|
You can try this [plugin](https://github.com/chandrayya/chandrayya-eclipse-plugins). Along with auto copy points mentioned in [Eclipse show number of lines and/or file size](https://stackoverflow.com/questions/26390560/eclipse-show-number-of-lines-and-or-file-size) also addressed.
|
8,035,876 |
I am currently developing a game for iPad & iPhone using Cocos2d with Box2d.
It would have been majorly cool to achieve a lighting effect like the one in this video:
<http://www.youtube.com/watch?v=Elnpm-gNI04>
and on this link:
<http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/>
I could have a go at trying to replicate the effect with Cocos2d and Box2d from the description in the link, but I am unsure if I would be able to get very far. It looks pretty advanced and heavy.
How can I achieve this in an "easy" way? Does anyone know of a Cocos2d-version of something like this, or do anyone have some pointers to point me in the right direction?
|
2011/11/07
|
[
"https://Stackoverflow.com/questions/8035876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685523/"
] |
<http://code.google.com/p/box2dlights/>
I have succesfully made dynamic light library that use box2d geometry and rayCasting. My library work under gles1.0 and gles2.0 and use libgdx as framework. This is peformant enough for giving dynamic real time lights to 2d games for mobile devices. I can help with porting that to Cocos2D. Basics are darn simple. It was under 100 lines when I first hacked it working for my own game.
Example:
Point light shoot from center n number of rays around it and record the closest collision points. These collision points are used for mesh that is colored with gradient and drawed with additive blending.
|
Try to look at this link.
<http://www.cocos2d-iphone.org/forum/topic/27856>
He successfully added simple dynamic light using cocos2d + chipmunk following the technique that Catalin Zima used.
Please note if you download his project and try to compile iOS build, then remove "Run Script" build phase as you may experience script didn't found error. More info to remove such phase can be seen [here](https://stackoverflow.com/a/253283/571227).
|
36,573,269 |
I would like to add a div to my current website.
The div i would like to add should show some json data using angularjs.
My problem is that it does not look like angularjs is working like its supose to when adding html after the page is rendered.
Here is my test:
```
<html >
<head>
<meta charset="utf-8">
<title>Angular test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<script>
var featureInfoMainDivId = 'FeatureInfoMaster';
function initAngularDataFeatureInfo() {
var s = document.createElement('script');
s.type = "text/javascript";
s.textContent =
'var app = angular.module("featureInfoApp", []); ' +
'app.controller("featureInfoCtrl", function ($scope) { ' +
'$scope.firstName = "John" '+
'$scope.lastName = "Doe" ' +
'});';
document.getElementById(featureInfoMainDivId).appendChild(s);
}
function addFeatureInfoDiv() {
var divMain = document.createElement('div');
divMain.setAttribute('id', featureInfoMainDivId);
divMain.setAttribute('ng-app', "featureInfoApp");
divMain.setAttribute('ng-controller', "featureInfoCtrl");
divMain.innerHTML ='<div> {{ firstName + " " + lastName }}</div>';
document.getElementById('appdiv').appendChild(divMain);
initAngularDataFeatureInfo();
}
</script>
<body >
<div id="appdiv"></div>
<button id="btn_load_grid" onclick="addFeatureInfoDiv();">loaddata</button>
</body>
</html>
```
|
2016/04/12
|
[
"https://Stackoverflow.com/questions/36573269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6193253/"
] |
You are missing two semicolons in
```
$scope.firstName = "John";
$scope.lastName = "Doe";
```
If you load the Angular script it looks for ng-app and bootstraps itself. Since you add Angular specific code after the script is loaded, you need to bootstrap Angular manually with:
```
//after initAngularDataFeatureInfo();
angular.element(document).ready(function() {
angular.bootstrap(document, ['featureInfoApp']);
});
```
Please remove this line:
```
divMain.setAttribute('ng-app', "featureInfoApp");
```
It is not needed if you bootstrap Angular manually. For further bootstrapping info, see: [Angular bootstrapping documentation](https://code.angularjs.org/1.2.26/docs/guide/bootstrap).
Also: Is there a reason why you are using Angular version 1.2.26? Version 1.5.3 is the latest stable build.
|
Try using Angular directives. you can create a customer directive which will then feed a template of your liking
|
2,125,105 |
I'm trying to make modal window for my website, I have a problem with overlay or modal div I'm not sure what is the problem.
The thing is everything except modal window shouldn't be clickable, but for some reason my navigation `<ul><li>` tags are visible and clickable. Here is css of my modal window :
```
element.style {
display:block;
left:50%;
margin-left:-210px; //generated with javascript
margin-top:-85px; //generated with javascript
position:fixed;
top:50%;
width:450px;
z-index:100;
}
```
Here is the css of my background overlay :
```
element.style {
height:1436px; //generated with javascript
left:0;
opacity:.75;
position:absolute;
top:0;
width:100%;
z-index:105;
}
```
What am I doing wrong ? thank you
|
2010/01/23
|
[
"https://Stackoverflow.com/questions/2125105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190623/"
] |
Check the `z-index` property of your `li` tags (or the underlying `ul`) and either set it below 100, or set the z-index of your modal window and overlay so it's higher than that of the `li`s.
|
It appears you have the values of your z-index backwards. The higher the number, the closer it is. Your background is set to 105 but the elements on top are set to 100.
|
634,504 |
Note: I am not talking about a circuit breaker where a spring is used to counter the repulsive force generated by current passing through a small contact area.
This question is about switches designed for high currents (kA to MA range). The current pulse is DC, rising from zero to peak in milliseconds upon closing the circuit.
Generally, switches use a spring to open and close the circuit as fast as possible to avoid arcing. The spring force is also used to minimize bouncing of conductors when they strike each other. In short, a spring is used in a switch to create a toggle mechanism. This is my current understanding.
However, a contact force is also required to conduct a large current. This is from "Marshall's law" as applied to high amperage circuits ([see here](https://ieeexplore.ieee.org/document/4072969)).
What is the exact role of a spring in a switch? What are the actual rules followed to design high-current switches? Any design codes or guidelines?
Suppose I want to conduct 100 kA of current through a conductor-conductor junction, what minimum contact force should be applied at the junction so that the current passes properly? (Please don't cite formula for blow-off force here.)
|
2022/09/12
|
[
"https://electronics.stackexchange.com/questions/634504",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/321749/"
] |
I will give you a small introduction to the way of thinking for high current, I have small experience from high voltage applications.
essentially a switch has to be able to completely stop the current and not be destroyed in the process or damage other components, so avoiding spikes and other phenomena as best you can, both have to be repeatable.
in the range you specify, there is actually no way to avoid an arc, you basically design around it and try your best to actually interrupt the arc itself
I know you mentioned DC, but I will give you an example first with AC power lines so you understand how the difficulty ramps up.
so you disconnect a power line, when you physically separate the contacts an arc will form, this circuit has enough energy to keep the arc alive, but you have one big things working to your advantage, AC signals pass through 0 so if you can keep the contacts separated until that happens, you basically got a shot.. on top the arc itself warms the air and pulls the arc up making it longer and requiring more energy to mantain, this also works in your favor. [Probably have seen a video like this](https://youtu.be/9GeXkussHfw)
When you connect the opposite happens, when you get the contacts close enough an arc will form and when you get the two in contact, the arc will disappear.
Now you mentioned a DC case, here you have no guaranteed passes through 0 so when closing or opening the switch you need to do something about the arc, in some cases you have a gas that has good isolation capabilities in a controlled chamber... or a vacuum, example for [opening](https://www.jstage.jst.go.jp/article/ieejpes/125/11/125_11_1070/_pdf), it can also be a liquid.
The big reason you want to suppress the arc as much as possible is that you wish the contacts to survive as many operations as possible, most of these high current switches have a set amount of times they can switch.
So to sum up this very brief introduction:
In very high currents for mechanical switches an arc will happen, you do your best to suppress it.
There are many designs and methods, if this [book](https://books.google.co.jp/books?id=hnD1BwAAQBAJ&pg=PA270&lpg=PA270&dq=Arc%20Interruption%20closing%20switch&source=bl&ots=WcKjfE3sJ4&sig=ACfU3U3ufN2EJNPpbZYAv2nFzh_u9EbuTA&hl=en&sa=X&ved=2ahUKEwjO4ryDuo76AhU3mVYBHarxDZsQ6AF6BAgQEAM#v=onepage&q&f=false) link works for you then great, you can familiarize yourself with more principles as you advance.
As for your contact force question, you can basically model the contact as a resistor, the better contact you achieve the more you can lower the resistance of the load circuit and the more current you can get.
I am not even gonna pretend I gave you all the answers to cover this topic, it is just a very simple introduction, it is a very difficult and long topic.
|
The spring does two things:
1. reduces the risk of bouncing when closing - as that can cause arcs to damage the contacts,
2. the cam and spring combine to open the contacts quickly again due to the issue of arcing.
So design of switches is very complicated and you can research further but this gives you an idea.
|
340,432 |
I'm stuck trying to do the remote SSH with WP-CLI.
I have installed WP-CLI on my **Webfaction server** and tested it's working
```
# This is in server
$ wp --info
OS: Linux web561.webfaction.com 3.10.0-862.14.4.el7.x86_64 #1 SMP Wed Sep 26 15:12:11 UTC 2018 x86_64
Shell: /bin/bash
PHP binary: /usr/local/bin/php56
PHP version: 5.6.40
php.ini used: /usr/local/lib/php56/php.ini
```
But whenever I tried to do remote access (I'm on Windows10 using GitBash), I get this error:
```
# This is in my local comp
$ wp @staging --info
[email protected]'s password:
bash: wp: command not found
```
I'm sure there's nothing wrong with the @staging alias.
Path is definitely correct too because when I change it to non-existent directory, it gives `No such file or directory` error.
Have anyone experienced this problem before?
Thanks
|
2019/06/13
|
[
"https://wordpress.stackexchange.com/questions/340432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33361/"
] |
Found a solution here <https://github.com/hrsetyono/wordpress/wiki/WP-CLI-on-Webfaction>
.
This seems to be Webfaction specific issue
You simply need to open FTP and append this line in `/home/yourname/.bashrc`
```
export PATH=$PATH:$HOME/bin
```
|
I know this might be trivial, - but it was my solution. I simply hadn't installed WP-CLI on my machine. So I followed the install instructions here: [wp-cli](https://wp-cli.org/) - and then it worked for me.
|
23,426,305 |
I have a very strange behaviour of "not()" css selector.
Here my simplified code:
```
<div id="mapDiv" class="mapDiv mapDiv1">
pippo
<div class="gm-style">pluto</div>
</div>
<div id="mapDiv2" class="mapDiv mapDiv2">
pippo
<div class="gm-style">pluto</div>
</div>
```
and my css:
```
.mapDiv1,.mapDiv2
{
width:300px;
height:100px;
border:solid 1px red;
}
.mapDiv div
{
width:200px;
height:50px;
border:solid 1px blue;
}
:not(.mapDiv1) div
{
color:green;
}
```
a jsFiddle is provided [**here**](http://jsfiddle.net/7zMuP/1/).
I would think that color:green will be applied only to second box texts, due to not() selector.... instead it is applied to both.
Can you explain me why?
|
2014/05/02
|
[
"https://Stackoverflow.com/questions/23426305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384685/"
] |
If you use MAMP, It's because of XCache.
Please try to disable it in the MAMP preference.
|
It may be solved by updating yii2 framework.
`yii.db.Query` uses `yii.db.QueryTrait` in which `indexBy` method is implemented.
Please compare your `Query.php`, `QueryTrait.php` and `QueryInterface.php` with
<https://github.com/yiisoft/yii2/blob/master/framework/db/Query.php>
<https://github.com/yiisoft/yii2/blob/master/framework/db/QueryTrait.php>
<https://github.com/yiisoft/yii2/blob/master/framework/db/QueryInterface.php>
|
11,740,788 |
I have created a custom `CursorAdapter` which binds some view items (a `TextView` and a `RatingBar`) in a `ListView` to some columns in a `SQL` `database` via `bindView()`, i.e:
```
public class MyCursorAdapter extends CursorAdapter {
...
public void bindView(View view, Context context, final Cursor cursor) {
TextView name = (TextView)view.findViewById(R.id.name);
name.setText(cursor.getString(cursor.getColumnIndex(MyDbAdapter.KEY_NAME)));
RatingBar rating = (RatingBar)view.findViewById(R.id.life_bar_rating);
rating.setRating(cursor.getFloat(cursor.getColumnIndex(MyDbAdapter.KEY_RATING_VALUE)));
}
...
}
```
I want to get the absolute latest version of all of the `RatingBar` rating values so I can update the `database` accordingly (in one go). I was initially trying to use the `cursor` in my `CursorAdapter`, however I noticed that the `cursor` just contains the values stored in the `database` and not the latest user changes - is this expected (the documentation is a bit vague)?.
I am guessing I need to iterate through the actual views somehow - how would I iterate through my `ListView` to retrieve all of the new rating bar rating values?
|
2012/07/31
|
[
"https://Stackoverflow.com/questions/11740788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356869/"
] |
The association between Booking and Personal can be map as a [unidirectional many-to-one association](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/associations.html#assoc-intro).
Use [property-ref](http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-manytoone) attribute to specified the field other than the personal primary key to join with, in your case it`s the personalId attribute that correspond to the database column PERSONAL\_ID instead of the ID of the Personal class.
>
> **[property-ref](http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html#mapping-declaration-manytoone) (optional)**
>
>
> the name of a property of the associated
> class that is joined to this foreign key. If not specified, the
> primary key of the associated class is used.
>
>
>
See this stackoverflow question on [Hibernate - why use many-to-one to represent a one-to-one?](https://stackoverflow.com/questions/2452987/hibernate-why-use-many-to-one-to-represent-a-one-to-one)
Mapping
```
<class name="Booking" >
<id name="ID" unsaved-value="0" column="ID">
<generator class="native">
<!--<param name="sequence">GLOBALSEQUENCE</param>-->
</generator>
</id>
...
<many-to-one name="personal" column="PERSONAL_ID" property-ref="personalId" not-null="true"/>
...
</class>
<class name="Personal">
<id name="id" column="ID">
<generator class="native"/>
</id>
<property name="personalId" column="personal_id" />
<property name="name" />
<property name="surname" />
<property name="email" />
</class>
```
Java
```
public class Booking{
private Long id;
private Personal personal;
...
}
public class Personal
{
Long id;
private Long personalId;
private String name;
private String surname;
private String email;
}
```
|
how about using HQL to get list of that table objects ? TO get mapped objects, there must be FKs defined isn't it, otherwise how hibernate will be able to map columns ?
|
62,784,643 |
hello community I have a problem putting a `bind-value` and an `onchange` shows me the following error:
```
The attribute 'onchange' is used two or more times for this element. Attributes must be unique (case-insensitive). The attribute 'onchange' is used by the '@bind' directive attribute.
```
this is my `input checkbox`:
```
<div class="form-group col-md-2">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch1"
@bind-value="@ProveedorEstadoCarrito.Cotizacion.Aceptada"
@onchange="e => CheckChanged(e)">
<label class="custom-control-label" for="customSwitch1">Aceptada</label>
</div>
</div>
```
this is the event:
```
private Boolean Aceptada = false;
private async Task CheckChanged(ChangeEventArgs ev)
{
Aceptada = (Boolean)ev.Value;
ProveedorEstadoCarrito.Cotizacion.Aceptada = Aceptada;
if (Aceptada == true)
{
var httpResponse = await repositorio.Put("api/Cotizacion", ProveedorEstadoCarrito.Cotizacion);
if (httpResponse.Error)
{
await mostrarMensajes.MostrarMensajeError(await httpResponse.GetBody());
}
else
{
navigationManager.NavigateTo("/formulario-cotizacion");
}
}
}
```
I want the checkbox to be activated with the `bind` if it was clicked
|
2020/07/07
|
[
"https://Stackoverflow.com/questions/62784643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11406791/"
] |
First off, you usually don't bind to the value attribute. It remains fixed, and when present, and within a form element, it is passed as form data to the server.
What you want is the checked attribute, like the code snippet below demonstrates:
```
<input type="checkbox" checked="@selected"
@onchange="@((args) => selected = (bool) args.Value)" />
@code {
private bool selected;
}
```
The above code show how to bind to a check box element. As you can see, the above code creates a two-way data binding, from a variable to the element, and from the element to the variable. The value attribute is involved. The same usage is applicable to the radion button element. Unlike other input elements, both employ the checked attribute, not the value attribute.
You may also use this variation:
```
<input type="checkbox" @bind="selected" />
```
which is equivalent to the code above: a checked attribute + onchange event, but the version above can let you solve your issue. Here's how your code may look like:
```
<input type="checkbox" class="custom-control-input" id="customSwitch1" checked="@ProveedorEstadoCarrito.Cotizacion.Aceptada" @onchange="CheckChanged">
```
And
```
private async Task CheckChanged(ChangeEventArgs ev)
{
Aceptada = (Boolean)ev.Value;
ProveedorEstadoCarrito.Cotizacion.Aceptada = Aceptada;
if (Aceptada == true)
{
```
Hope this helps...
|
You can't. But you can set `checked=ProveedorEstadoCarrito.Cotizacion.Aceptada` to update the state of the checkbox, and for the `@onchange` event do `@onchange=CheckChanged` and in that method you can set `ProveedorEstadoCarrito.Cotizacion.Aceptada = (bool) ev.Value;`
|
3,045,913 |
Just started playing with the new AIR functions NetworkInfo and NetworkInterface, but can't build ...
This is the example I started from:
[tourdeflex](http://tourdeflex.adobe.com/AIR2samples/NetworkInfo/networkinfo.html)
But these lines cause errors:
```
var networkInfo:NetworkInfo = NetworkInfo.networkInfo;
var networkInterfaces:Vector.<NetworkInterface> = networkInfo.findInterfaces();
```
Any ideas on how to solve it?
Thanks a lot,
Frank
|
2010/06/15
|
[
"https://Stackoverflow.com/questions/3045913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278949/"
] |
Due to the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy), you will need to modify your AJAX to use JSONP instead of JSON. Check out the [jQuery Cross-Domain Ajax Guide](http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide).
|
Pointy is correct, but to solve this you need to expose an endpoint that is callable from outside the application.
I suggest you take a look at creating JSON web services using WCF.
|
173,686 |
I'm trying to solve nonlinear equations using Newton-type methods with very high accuracy using Mathematica. I found many research papers in which the numerical results are calculated with very high accuracy. e.g. To solve the equation
$$e^{-x}+\sin(x)-2=0\text{ with initial guess }x\_0=-1.$$
Many authors evaluated its functional value after some iterations up to $10^{-300}$ and less than this. But with the same function and same initial guess, I could not get the functional value better than $10^{-16}$. Why? Is there any special coding to increase the accuracy of the result.
|
2018/05/19
|
[
"https://mathematica.stackexchange.com/questions/173686",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/43942/"
] |
Try
```
FindRoot[Exp[-x] + Sin[x] - 2 == 0, {x, -1}, WorkingPrecision -> 500]
```
|
You could also use [`Solve`](http://reference.wolfram.com/language/ref/Solve) as long as you provide a domain restriction:
```
root = x /. First @ Solve[Exp[-x]+Sin[x]-2==0 && -2<x<0]
```
>
> Root[{1 - 2 E^#1 + E^#1 Sin[#1] &, -1.05412712409121289977}]
>
>
>
The nice thing about the [`Root`](http://reference.wolfram.com/language/ref/Root) representation above is that it behaves like an exact expression. Anywhere you can use an exact expression (like [`Pi`](http://reference.wolfram.com/language/ref/Pi)), you can instead use the above [`Root`](http://reference.wolfram.com/language/ref/Root) object. For example:
```
N[root]
N[root, 100]
Integrate[x^root, {x, 1, 2}]
Minimize[x^2 - 2 root x + 1, x]
```
>
> -1.05413
>
>
> -1.054127124091212899766844310942376610765302238222244358374175157259667078894540095490830534013697076
>
>
> (-1 + 2^(1 + Root[{1 + E^#1 (-2 + Sin[#1]) &, -1.05412712409121289977}]))/(1 +
> Root[{1 + E^#1 (-2 + Sin[#1]) &, -1.05412712409121289977}])
>
>
> {1 - Root[{1 - 2 E^#1 + E^#1 Sin[#1] &, -1.05412712409121289977}]^2, {x ->
> Root[{1 - 2 E^#1 + E^#1 Sin[#1] &, -1.05412712409121289977}]}}
>
>
>
|
28,873,161 |
I push in values from JSON into a several arrays using Underscore, but I want to eliminate any repeated values if there are any, either during push or after. How could I do this?
**JSON**
```
looks = [{
"id": "look1",
"products": ["hbeu50271385", "hbeu50274296", "hbeu50272359", "hbeu50272802"]
}, {
"id": "look2",
"products": [
"hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"
]
}, {
"id": "look3",
"products": [
"hbeu50272935", "hbeu50274426", "hbeu50271624", "hbeu50274762", "hbeu50275366", "hbeu50274433", "hbeu50262002", "hbeu50272364", "hbeu50272359"
]
}
.......
]
```
**JS (Underscore)**
```
var productArrays = [];
_.each(looks, function(look) {
var productArray = [];
_.each(look.products, function(product) {
productArray.push(product.replace(/_.*/, ''))
})
productArrays.push(productArray);
});
```
|
2015/03/05
|
[
"https://Stackoverflow.com/questions/28873161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1937021/"
] |
There are couple ways
1.Use [\_.uniq](http://underscorejs.org/#uniq)
```
_.uniq(productArray);
```
2.Use [\_.indexOf](http://underscorejs.org/#indexOf) before `push` to `productArray`
[Example](http://jsbin.com/gezaza/1/edit?js,console)
|
For array's content be unique, how about using \_.uniq?
Or just check existence of value before really push it.
```
function uniquePush(arr, valueToPush) {
if(arr.indexOf(valueToPush) == -1) {
arr.push(valueToPush)
}
}
```
|
5,667,802 |
How can I know the IP address of my iPhone simulator?
|
2011/04/14
|
[
"https://Stackoverflow.com/questions/5667802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/418029/"
] |
It will have the same IP addresses as the computer you’re running it on.
|
Jep, like Todd said, the same as your machines IP. You can also simply visit <http://www.whatismyip.com> with mobile Safari or your Mac's web browser ;-)
|
5,667,802 |
How can I know the IP address of my iPhone simulator?
|
2011/04/14
|
[
"https://Stackoverflow.com/questions/5667802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/418029/"
] |
It will have the same IP addresses as the computer you’re running it on.
|
I think the by visiting the website <http://www.test-ipv6.com/> is also a good choice. As the site tells you both the ipv4 and ipv6 global-unicast address
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.