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
|
---|---|---|---|---|---|
2,526,826 | I'm looking over the documentation that comes with Apache Ant version 1.8.0 and can't find where classpath, path and pathelement are documented. I've found a page that describes path like structures but it doesn't list the valid attributes or nested elements for these. Another thing I can't find in the documentation is a description of the relationships between filelist, fileset, patternset and path and how to convert them back and forth. For instance there has to be an easier way to compile only those classes in one package while removing all class dependencies on the package classes and update documentation.
```
<!-- Get list of files in which we're interested. -->
<fileset id = "java.source.set"
dir = "${src}">
<include name = "**/Package/*.java" />
</fileset>
<!-- Get a COMMA separated list of classes to compile. -->
<pathconvert property = "java.source.list"
refid = "java.source.set"
pathsep = ",">
<globmapper from = "${src}/*.@{src.extent}"
to = "*.class" />
</pathconvert>
<!-- Remove ALL dependencies on package classes. -->
<depend srcdir = "${src}"
destdir = "${build}"
includes = "${java.source.list}"
closure = "yes" />
<!-- Get a list of up to date classes. -->
<fileset id = "class.uptodate.set"
dir = "${build}">
<include name = "**/*.class" />
</fileset>
<!-- Get list of source files for up to date classes. -->
<pathconvert property = "java.uptodate.list"
refid = "class.uptodate.set"
pathsep = ",">
<globmapper from="${build}/*.class" to="*.java" />
</pathconvert>
<!-- Compile only those classes in package that are not up to date. -->
<javac srcdir = "${src}"
destdir = "${build}"
classpathref = "compile.classpath"
includes = "${java.source.list}"
excludes = "${java.uptodate.list}"/>
<!-- Get list of directories of class files for package. --:
<pathconvert property = "class.dir.list"
refid = "java.source.set"
pathsep = ",">
<globmapper from = "${src}/*.java"
to = "${build}*" />
</pathconvert>
<!-- Convert directory list to path. -->
<path id = "class.dirs.path">
<dirset dir = "${build}"
includes = "class.dir.list" />
</path>
<!-- Update package documentation. -->
<jdepend outputfile = "${docs}/jdepend-report.txt">
<classpath refid = "compile.classpath" />
<classpath location = "${build}" />
<classespath>
<path refid = "class.dirs.path" />
</classespath>
<exclude name = "java.*" />
<exclude name = "javax.*" />
</jdepend>
```
Notice there's a number of conversions between filesets, paths and comma separated list just to get the proper 'type' required for the different ant tasks. Is there a way to simplify this while still processing the fewest files in a complex directory structure? | 2010/03/26 | [
"https://Stackoverflow.com/questions/2526826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291154/"
]
| This is the closest I could find to documentation on classpath.
<http://ant.apache.org/manual/using.html#path> | [Path](https://ant.apache.org/manual-1.9.x/api/org/apache/tools/ant/types/Path.html):
>
> This object represents a path as used by CLASSPATH or PATH environment variable. A path might also be described as a collection of unique filesystem resources.
>
>
>
and [PathElement](https://ant.apache.org/manual-1.9.x/api/org/apache/tools/ant/types/Path.PathElement.html):
>
> Helper class, holds the nested `<pathelement>` values.
>
>
>
are defined directly in the JavaDoc.
`ClassPath`is an implementation of [AbstractClasspathResource](https://ant.apache.org/manual-1.9.x/api/org/apache/tools/ant/types/resources/AbstractClasspathResource.html):
>
> A Resource representation of anything that is accessed via a Java classloader. The core methods to set/resolve the classpath are provided.
>
>
>
which is a direct subclass of [Resource](https://ant.apache.org/manual-1.9.x/api/org/apache/tools/ant/types/Resource.html):
>
> Describes a "File-like" resource (File, ZipEntry, etc.). This class is meant to be used by classes needing to record path and date/time information about a file, a zip entry or some similar resource (URL, archive in a version control repository, ...).
>
>
>
[](https://i.stack.imgur.com/aVFQN.gif)
FileSet is defined as:
>
> A FileSet is a group of files. These files can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of PatternSets and Selectors.
>
>
>
Selectors is defined as:
>
> Selectors are a mechanism whereby the files that make up a `<fileset>` can be selected based on criteria other than filename as provided by the `<include>` and `<exclude>` tags.
>
>
>
PatternSet is defined as:
>
> Patterns can be grouped to sets and later be referenced by their id attribute. They are defined via a patternset element, which can appear nested into a FileSet or a directory-based task that constitutes an implicit FileSet. In addition, patternsets can be defined as a stand alone element at the same level as target — i.e., as children of project as well as as children of target.
>
>
>
FileList is defined as:
>
> FileLists are explicitly named lists of files. Whereas FileSets act as filters, returning only those files that exist in the file system and match specified patterns, FileLists are useful for specifying files that may or may not exist. Multiple files are specified as a list of files, relative to the specified directory, with no support for wildcard expansion (filenames with wildcards will be included in the list unchanged). FileLists can appear inside tasks that support this feature or as stand-alone types.
>
>
>
[](https://i.stack.imgur.com/iP0oL.gif)
In Schematron, you could validate this by the following:
```
<sch:pattern>
<sch:title>Check allowed elements</sch:title>
<sch:rule context="target/*[name() = ancestor::*/taskdef/@name]">
<sch:assert test="true()">
The target element may contain user-defined tasks.
</sch:assert>
</sch:rule>
</sch:pattern>
```
**References**
* [Types - Apache Ant Manual](https://ant.apache.org/manual/Types/)
* [AntLib](https://ant.apache.org/manual/Types/antlib.html)
* [Apache Ant/Build File Structure - Wikibooks, open books for an open world](https://en.wikibooks.org/wiki/Apache_Ant/Build_File_Structure)
* [Meeting new challenges with Ant1.7 (pdf)](http://people.apache.org/~stevel/slides/extending_ant.pdf)
* [Ant Extending Ant](https://www.tutorialspoint.com/ant/ant_extending_ant.htm)
* [Apache Ant - Apache AntUnit](http://ant.apache.org/antlibs/antunit/)
* [Validating Ant with Schematron](http://archive.oreilly.com/pub/post/validating_ant_with_schematron.html)
* [Ant Script Visualizer](http://www.nurflugel.com/webstart/AntScriptVisualizer/) |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| There are **no ventilation or cooling requirements.**
This has been verified by an RPi admin [here](http://www.raspberrypi.org/phpBB3/viewtopic.php?f=2&t=1701). | Based on my test Raspberry Pi runs relatively cool even when the CPU is 100% loaded for longer periods, so I think there shouldn't be a problem (I did not try loading the GPU though). |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| Yes, under usual circumstances it should be possible to run the Raspberry Pi in an airtight case. I have measured some temperatures confirming that there is amply thermal headroom.
For reference:
* 22°C room temperature
* 42°C idle
I ran [sysbench](http://sysbench.sourceforge.net/docs/#cpu_mode) to stress the CPU:
```
sysbench --test=cpu --cpu-max-prime=20000 run
```
* 45°C 20 s
* 46°C 2 m
* 47°C 5 m
* 48°C 12 m
Since the temperature did not seem to raise any further, I put a paper hood over the CPU to simulate the "airtight case scenario".
* 49°C 20 s
* 50°C 2 m
After another half an hour there was no further increase of the temperature. | Based on my test Raspberry Pi runs relatively cool even when the CPU is 100% loaded for longer periods, so I think there shouldn't be a problem (I did not try loading the GPU though). |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| Based on my test Raspberry Pi runs relatively cool even when the CPU is 100% loaded for longer periods, so I think there shouldn't be a problem (I did not try loading the GPU though). | According to [this test](https://www.jeffgeerling.com/blog/2019/raspberry-pi-microsd-card-performance-comparison-2019) the USB 3.0 controller on Raspberry Pi 4 cannot work at full speed if there is no fan. The slow down without a fan could be 2-3 times. In the test the maximum speed was 346 MB/s for USB 3.0 (for comparison, it was 44 MB/s for an SD card). So depending on your speed requirements and how often you need it, you may or may not need active cooling. |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| There are **no ventilation or cooling requirements.**
This has been verified by an RPi admin [here](http://www.raspberrypi.org/phpBB3/viewtopic.php?f=2&t=1701). | Yes, under usual circumstances it should be possible to run the Raspberry Pi in an airtight case. I have measured some temperatures confirming that there is amply thermal headroom.
For reference:
* 22°C room temperature
* 42°C idle
I ran [sysbench](http://sysbench.sourceforge.net/docs/#cpu_mode) to stress the CPU:
```
sysbench --test=cpu --cpu-max-prime=20000 run
```
* 45°C 20 s
* 46°C 2 m
* 47°C 5 m
* 48°C 12 m
Since the temperature did not seem to raise any further, I put a paper hood over the CPU to simulate the "airtight case scenario".
* 49°C 20 s
* 50°C 2 m
After another half an hour there was no further increase of the temperature. |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| There are **no ventilation or cooling requirements.**
This has been verified by an RPi admin [here](http://www.raspberrypi.org/phpBB3/viewtopic.php?f=2&t=1701). | According to [this test](https://www.jeffgeerling.com/blog/2019/raspberry-pi-microsd-card-performance-comparison-2019) the USB 3.0 controller on Raspberry Pi 4 cannot work at full speed if there is no fan. The slow down without a fan could be 2-3 times. In the test the maximum speed was 346 MB/s for USB 3.0 (for comparison, it was 44 MB/s for an SD card). So depending on your speed requirements and how often you need it, you may or may not need active cooling. |
105 | Is it possible to reliably run a Pi in an airtight (watertight) case or is some form of ventilation required for cooling? I'm assuming it doesn't chuck out too much heat, but am wondering whether running it indefinitely this way may cause issues. | 2012/06/12 | [
"https://raspberrypi.stackexchange.com/questions/105",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/93/"
]
| Yes, under usual circumstances it should be possible to run the Raspberry Pi in an airtight case. I have measured some temperatures confirming that there is amply thermal headroom.
For reference:
* 22°C room temperature
* 42°C idle
I ran [sysbench](http://sysbench.sourceforge.net/docs/#cpu_mode) to stress the CPU:
```
sysbench --test=cpu --cpu-max-prime=20000 run
```
* 45°C 20 s
* 46°C 2 m
* 47°C 5 m
* 48°C 12 m
Since the temperature did not seem to raise any further, I put a paper hood over the CPU to simulate the "airtight case scenario".
* 49°C 20 s
* 50°C 2 m
After another half an hour there was no further increase of the temperature. | According to [this test](https://www.jeffgeerling.com/blog/2019/raspberry-pi-microsd-card-performance-comparison-2019) the USB 3.0 controller on Raspberry Pi 4 cannot work at full speed if there is no fan. The slow down without a fan could be 2-3 times. In the test the maximum speed was 346 MB/s for USB 3.0 (for comparison, it was 44 MB/s for an SD card). So depending on your speed requirements and how often you need it, you may or may not need active cooling. |
58,074,976 | How to resolve Laravel 401 (Unauthorized) error for a particular single URL.
url is accessible directly but when request send using axios its how this error. | 2019/09/24 | [
"https://Stackoverflow.com/questions/58074976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1937521/"
]
| api\_token: this.user.api\_token
```
axios.post("http://foo",
{headers: { 'Authorization' : 'Bearer '+ api_token}})
.then(response => {
//action
})
```
link: <https://forum.vuejs.org/t/401-unauthorized-vuejs-laravel-and-passport/59770>
or
```
postComment() {
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
body: this.commentBox
})
```
but make sure that you have "user.api\_token" | Some people just assume all has been configured right out of the box; but you need to:
Follow this Laravel documentation to gain api\_token for all your users.
[Laravel api authentication](https://laravel.com/docs/6.x/api-authentication)
**NOTE:** When you register users, if users api\_token in database is still being saved as `NULL`, go to the users model and add `api_token` to fillable array
```
//Model/User.php
protected $fillable = [
...
'api_token',
...
];
```
In your view layout `app.blade.php` create a meta for your token, just like your `csrf`:
```
//views/layout/app.blade.php
<!-- APIToken -->
<meta name="api_token" content="{{ Auth::user()->api_token }}">
```
Finally in your `main.js` or `app.js`; you can include it with every sent request
```
//resources/app.js
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'Authorization': 'Bearer '+ document.querySelector('meta[name="api_token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
```
This works and would help someone after all I've been through; meanwhile Laravel Passport and Sanctum are better recommendation for api authentication |
117,025 | I used pc decrapifier to uninstall lots of programs because revo uninstaller takes a lot of your time just to uninstall a single program. Can I remove the registry keys and folders left behind by pc decrapifier using revo uninstaller?
Or do you know of any application that function like decrapifier and revo? | 2010/03/06 | [
"https://superuser.com/questions/117025",
"https://superuser.com",
"https://superuser.com/users/23950/"
]
| Yes, Revo can get rid of the registry entries. Depending on which scan mode you use, it can look into more places in the registry for a deeper scan:

[**CCleaner**](http://www.ccleaner.com/) also performs registry scanning for old entries lying around. | As I understand, OP wanted to clean the Registry after the UNINSTALL OF APPLICATION has already been made before opening Revo.
Accepted answer doesn't answer that. Unfortunately, it doesn't seem possible doable directly. However:
A) Re-install that target application and uninstall again, now with REVO.
OR
B) use CCleaner (or alike) to clean registry generally. |
298,601 | I am trying to create custom page page having error 404.
**routes.xml**
```
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="hello" frontName="hello">
<module name="SimpleMagento_Custom" />
</route>
</router>
</config>
```
**Controller :-**
```
<?php
namespace SimpleMagento\Custom\Controller\Test;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class DisplayInfo extends Action
{
protected $_pagefactory;
public function __construct(PageFactory $pagefactory,Context $context)
{
$this->_pagefactory=$pagefactory;
parent::__construct($context);
}
public function execute()
{
return $this->_pagefactory->create();
}
}
?>
```
**Layout file (hello\_test\_displayinfo):-**
```
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="SimpleMagento\Custom\Block\EmployeeData" name="new_layout1" template="SimpleMagento_Custom::Employee.phtml"/>
</referenceContainer>
</body>
</page>
```
**Block file:-**
```
<?php
namespace SimpleMagento\Custom\Block;
class EmployeeData extends \Magento\Framework\View\Element\Template
{
public function __construct(\Magento\Framework\View\Element\Template\Context $context)
{
parent::__construct($context);
}
public function getName()
{
echo "YES..!";
}
}
?>
```
**Employee.phtml:-**
```
<h1>you have created new page </h1>
<h3><?php $block->getName();?></h3>
``` | 2019/12/13 | [
"https://magento.stackexchange.com/questions/298601",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/84377/"
]
| Please correct your file path with below structure
>
> app/code/SimpleMagento/Custom/registration.php
>
>
>
Content for this file is..
```
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'SimpleMagento_Custom',
__DIR__
);
```
>
> app/code/SimpleMagento/Custom/etc/module.xml
>
>
>
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="SimpleMagento_Custom" setup_version="1.0.0" />
</config>
```
>
> app/code/SimpleMagento/Custom/etc/frontend/routes.xml
>
>
>
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="hello" frontName="hello">
<module name="SimpleMagento_Custom" />
</route>
</router>
</config>
```
>
> app/code/SimpleMagento/Custom/Controller/Test/DisplayInfo.php
>
>
>
```
<?php
namespace SimpleMagento\Custom\Controller\Test;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class DisplayInfo extends Action
{
protected $_pagefactory;
public function __construct(PageFactory $pagefactory,Context $context)
{
$this->_pagefactory=$pagefactory;
parent::__construct($context);
}
public function execute()
{
return $this->_pagefactory->create();
}
}
?>
```
>
> app/code/SimpleMagento/Custom/Block/EmployeeData.php
>
>
>
```
<?php
namespace SimpleMagento\Custom\Block;
class EmployeeData extends \Magento\Framework\View\Element\Template
{
public function __construct(\Magento\Framework\View\Element\Template\Context $context)
{
parent::__construct($context);
}
public function getName()
{
echo "YES..!";
}
}
?>
```
>
> app/code/SimpleMagento/Custom/view/frontend/layout/hello\_test\_displayinfo.xml
>
>
>
```
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="SimpleMagento\Custom\Block\EmployeeData" name="new_layout1" template="SimpleMagento_Custom::Employee.phtml"/>
</referenceContainer>
</body>
</page>
```
>
> app/code/SimpleMagento/Custom/view/frontend/templates/Employee.phtml
>
>
>
```
<h1>you have created new page </h1>
<h3><?php $block->getName();?></h3>
```
**URL :**
<http://www.example.com/hello/test/displayinfo>
**Output :**
[](https://i.stack.imgur.com/g9gEI.png)
Hope this will help you! | Calling wrong route.
call
```
hello_test_displayInfo
```
URL :
```
hello/test/displayInfo
``` |
58,040,303 | I was wasting a lot of time figuring out why an algorithm that should be more efficient than another one, however, was perfectly the same in terms of speed to the other. I did these operations: I compiled the first source code in a separate terminal window; while the second source code in another window. I simply used a:
$ cc number\_v1.c
to compile the first, and a:
$ cc number\_v2.c
for the second source code.
I'm on Mac OS X Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root: xnu-4903.271.2 ~ 2 / RELEASE\_X86\_64 x86\_64.
In response I had exactly the same timing result. Something impossible given the best algorithm of the second source code.
Then I turn everything off and try again the next day. To my surprise I finally see the differences: the second source code is completed in a much shorter time than the first.
It seems that the first time the compiler did not compile the code of the listing and indeed, perhaps still considered the old version; consider that I have tried to modify the source code several times with relative compilation, but as a result always the same.
It happened to me a while ago working on another source code (with relative loss of time).
Unfortunately, the event is not replicable and does not occur frequently.
Can anyone explain why it happened? Is there a kind of cache to be reset in these cases?
Their respective source codes follow; it's about finding the prime numbers from 2 to 1000000.
```
/* cc number_v1.c */
#include <stdio.h>
int main(void) {
int i, j, n = 1000000;
for(i = 2; i <= n; i++) {
for(j = 2; j < i && i % j != 0; j++)
;
if(j >= i) printf("%d ", j);
}
return 0;
}
/* cc number_v2.c */
#include <stdio.h>
int main(void) {
int i, j, n = 1000000;
for(i = 2; i <= n; i++) {
for(j = 2; j * j <= i && i % j != 0; j++)
;
if(j * j > i) printf("%d ", i);
}
return 0;
}
``` | 2019/09/21 | [
"https://Stackoverflow.com/questions/58040303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11736671/"
]
| You should include the measurement in your code. There is clearly something wrong with your measurement and you need to clearly show your method.
I performed the following test modified to use `uint64_t` to prevent arithmetic overflow in `alg1()`, and also replacing the `printf()` output with a volatile sink:
```
{volatile uint64_t x = i ;}
```
Measuring the performance of an algorithm containing I/O can be misleading - you may be measuring the I/O performance of your system.
```
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#define MAX 1000000 ;
void alg1( void )
{
uint64_t i, j, n = MAX;
for( i = 2; i <= n; i++ )
{
for( j = 2; j < i && i % j != 0; j++ )
;
if( j >= i ){volatile uint64_t x = i ;}
}
}
void alg2( void )
{
uint64_t i, j, n = MAX;
for( i = 2; i <= n; i++ )
{
for( j = 2; j * j <= i && i % j != 0; j++ )
;
if( j * j > i ){volatile uint64_t x = i ;}
}
}
int main()
{
clock_t start = clock() ;
alg1() ;
int alg1_clocks = clock() - start ;
start = clock() ;
alg2() ;
int alg2_clocks = clock() - start ;
printf( "\nalg1() took %f seconds", (double)(alg1_clocks) / CLOCKS_PER_SEC ) ;
printf( "\nalg2() took %f seconds", (double)(alg2_clocks) / CLOCKS_PER_SEC ) ;
return 0 ;
}
```
Result:
```
alg1() took 336.681000 seconds
alg2() took 0.621000 seconds
```
So your results cannot be reproduced so I would doubt their integrity. | First of all the output of the codes most probably aren't identical but you didn't check. `j * j` does not fit in a 32-bit int with numbers larger than 46340, so undefined behaviour is a possibility, but I do not believe that it is the reason here.
The first code executes the inner loop *O(i)* times whereas the 2nd executes the inner loop *O(i1/2*) times, hence this is the difference between *O(n²)* and *O(3n/2)*, which at 1000000 would mean 316-fold execution time for the former (my computer gives 89 s vs 0.20 which is bout ~446 fold difference which is close enough), and that with `-O3`.
That you got the same *low* times would have been impossibru, unless the compilation took 89 seconds to inline the code. I.e. you didn't run the first program then. |
71,051,218 | I have a co-worker who have a problem with posting here, he will be the one answering comments and validating answer. Here is his question:
I'm using Net5 with Microsoft.Extensions.Hosting. Instead of appsettings.json, I need to use xml files. I have App.config to specify common app settings (log4net config, etc.) and AcquisitionManagerConfiguration.xml for the settings on each installation (hardware stuff).
I went like this :
Program.cs
```
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
IHostBuilder ihb = Host.CreateDefaultBuilder(args);
ihb.ConfigureAppConfiguration((hostingContext, configuration) =>
{
//configuration.Sources.Clear();
configuration.SetBasePath(AppContext.BaseDirectory);
configuration.AddXmlFile("AcquisitionManagerConfiguration.xml", optional: false, reloadOnChange: true)
.AddXmlFile("App.config", optional: false, reloadOnChange: true);
configuration.AddEnvironmentVariables();
}).ConfigureServices((hostingContext, services) =>
{
services.AddHttpClient();
services.Configure<AcquisitionManagerConfiguration>(hostingContext.Configuration.GetSection("AcquisitionManagerConfiguration"));
services.AddTransient<AcquisitionManager.AcquisitionManager>();
services.AddTransient<IServiceClient, ServiceClient>();
services.AddHostedService<Worker>();
});
return ihb;
}
}
```
AcquisitionManager.cs
```
public AcquisitionManager(IServiceClient serviceClient, IOptions<AcquisitionManagerConfiguration> config)
{
client = serviceClient;
configuration = config.Value;
}
```
and the first xml
```
<?xml version="1.0" encoding="utf-8" ?>
<AcquisitionManagerConfiguration>
<val>1</val>
</AcquisitionManagerConfiguration>
```
AcquisitionManagerConfiguration.cs matches exactly the xml, it worked fine if I manually deserialize.
But using the hosting system, I never have anything in config.Value.
Any idea what I'm doing wrong ?
I didn't find the solution so I posted here.
Thanks for the help. | 2022/02/09 | [
"https://Stackoverflow.com/questions/71051218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10884472/"
]
| The problem come from the xml structure:
As this is application configuration the structure from this:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<AcquisitionManagerConfiguration>
<val>1</val>
</AcquisitionManagerConfiguration>
```
become this:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<AcquisitionManagerConfiguration>
<val>1</val>
</AcquisitionManagerConfiguration>
</Configuration>
``` | It looks like you are just missing the `Bind` part in your services registration.
`services.Configure<AcquisitionManagerConfiguration>(options => Configuration.GetSection("AcquisitionManagerConfiguration"));`
should be
`services.Configure<AcquisitionManagerConfiguration>(options => Configuration.GetSection("AcquisitionManagerConfiguration").Bind(options));` |
38,267,381 | I am new to TypeScript and came accross this example:
```
for (let i = 0; i < 10 ; i++) {
setTimeout(function() {console.log(i); }, 100 * i);
}
```
output: `1,2,3,4,5,6,7,8,9,10`
But
```
for (var i = 0; i < 10 ; i++) {
setTimeout(function() {console.log(i); }, 100 * i);
}
```
output : `10,10,10,10,10,10,10,10,10,10`
Can someone explain the reason please? | 2016/07/08 | [
"https://Stackoverflow.com/questions/38267381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6166984/"
]
| this is due to the scope difference
===================================
it is due the scoping difference between var and let. The first time the timeout actually can complete the console.log, i has already been changed by the loop to 10. (Essentially, you are stacking console.logs with various timeouts, they will only run when the time is done).
With let, which is `scoped` to the block, i takes the value inside console.log (because it is scoped to the block from which it called). In other words, as soon as it encountered this code, the variable became 'limited' to the function inside your timeout. This means that even though the loop changed the variable 'i' outside of it, it did not change the variable of the function. | @DylanMeeus is correct in that it's a scoping/closure issue. To help visualize this, this is what using "let" is compiled to in es5:
```
var _loop_1 = function(i) {
setTimeout(function () { console.log(i); }, 100 * i);
};
for (var i = 0; i < 10; i++) {
_loop_1(i);
}
```
Notice that the `i` in `_loop_1` is a new number instance. |
45,750,243 | I want to give storage permission for my app. My code working perfect till Marshmallow, only problem in Nougat
The below method always return false in nougat even permission granted manually from settings.
```
private boolean checkWriteExternalPermission() {
String permission = "android.permission.WRITE_EXTERNAL_STORAGE";
int res = getApplicationContext().checkCallingOrSelfPermission(
permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
```
I used this for Nougat and allow permission but above method still returns false.
```
void storagePermission(){
StorageManager sm = (StorageManager)getSystemService(Context.STORAGE_SERVICE);
StorageVolume volume = sm.getPrimaryStorageVolume();
Intent intent = volume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, 1);
}
```
Please help me to resolve this. | 2017/08/18 | [
"https://Stackoverflow.com/questions/45750243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3809936/"
]
| Assuming that you mean months ammount ( i.e for a monthly payment )
You can do it like this in your store method i.e:
```
$start_day = Carbon::parse($request->created_at); //get a carbon instance with created_at as date
$expiry_day = $start_day->addMonths($request->user_selected_months); //add X months to created_at date
``` | ```
public function store(StoreRequest $request) {
date_default_timezone_set('asia/calcutta');
$month = $request->month;
$expiry_date = Carbon::now()->addMonths($month);
$request['expiry_date'] = $expiry_date;
}
``` |
126,106 | I have created a script to start a server (my first question). Now I want it to run on the system boot and start the defined server. What should I do to get this done?
My findings tell me put this file in the `/etc/init.d` location, and it will execute when the system will boot. But I am not able to understand how the first argument on the startup will be `start`? Is this predefined somewhere to use `start` as `$1`? If I want to have a case `startall` that will start all the servers in the script, then what are the options I can manage?
My script is like this:
```
#!/bin/bash
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
$0 stop
$0 start
;;
*)
echo "usage: $0 (start|stop|restart)"
;;
esac
``` | 2010/03/31 | [
"https://superuser.com/questions/126106",
"https://superuser.com",
"https://superuser.com/users/29155/"
]
| `/etc/init.d` is the script directory, in which the executable scripts appear. However, in order to run scripts in a particular order after your system starts, you need to add files to the `/etc/rc#.d` directory. Entries that appear here tell your system in what order and at what run level scripts in `/etc/init.d` should be run. The number after the rc indicates what run level the machine is running at, according to this chart:
<http://en.wikipedia.org/wiki/Runlevel>
So if you have:
```
/etc/init.d/importantscript
```
Then you need the (empty) files:
```
/etc/rc.d/rc3.d/S20importantscript
/etc/rc.d/rc6.d/K20importantscript
```
The S means start, and the K means kill. When your machine starts, the system will say "Ah, I'm running at RunLevel 3, let's pop over to rc3.d to see what scripts in '/etc/init.d' need to be run and in what order." In this case, the system will sort by 'S' and then the number after 'S' and will execute '/etc/init.d/importantscript start'. The 20 is just for ordering purposes... your script will run behind 'S19' and in front of 'S21'. You can create these files simply by doing:
`sudo touch /etc/rc.d/rc3.d/S20importantscript`
Here's a nice summary as well: <http://www.linux.com/news/enterprise/systems-management/8116-an-introduction-to-services-runlevels-and-rcd-scripts> | The $1 is the command line argument that is passed to your script, it is one of start, stop or restart. In [openSUSE](http://en.wikipedia.org/wiki/OpenSUSE), I don't remember having an option to pass other arguments into the script when useing the runlevel editor thingy, so I think that these are probably the only ones you should use.
I don't use [CentOS](http://en.wikipedia.org/wiki/CentOS) myself, but it seems that the program to control what is started at which runlevel is [ntsysv](http://centos.org/modules/newbb/viewtopic.php?viewmode=flat&order=ASC&topic_id=12486&forum=37). |
126,106 | I have created a script to start a server (my first question). Now I want it to run on the system boot and start the defined server. What should I do to get this done?
My findings tell me put this file in the `/etc/init.d` location, and it will execute when the system will boot. But I am not able to understand how the first argument on the startup will be `start`? Is this predefined somewhere to use `start` as `$1`? If I want to have a case `startall` that will start all the servers in the script, then what are the options I can manage?
My script is like this:
```
#!/bin/bash
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
$0 stop
$0 start
;;
*)
echo "usage: $0 (start|stop|restart)"
;;
esac
``` | 2010/03/31 | [
"https://superuser.com/questions/126106",
"https://superuser.com",
"https://superuser.com/users/29155/"
]
| You don't have to --- and shouldn't --- create files in `/etc/rc.d/rcN.d/`; what you should do instead is put a comment in your init script reading
```
# chkconfig NNN A B
```
where `NNN` is the set of run-levels in which you want the script active (e.g., `345` if it's active in runlevels `3`, `4`, and `5`), and `A` and `B` are the start and stop priorities. Then `chkconfig --add foo` (assuming your script is named `foo`) will create the files in `/etc/rc.d/rcN.d/` with the appropriate names.
You can then use `service foo bar` to send the `bar` message to your script (e.g., `start`, `stop`, whatever -- that's where your `$1` comes from). | The $1 is the command line argument that is passed to your script, it is one of start, stop or restart. In [openSUSE](http://en.wikipedia.org/wiki/OpenSUSE), I don't remember having an option to pass other arguments into the script when useing the runlevel editor thingy, so I think that these are probably the only ones you should use.
I don't use [CentOS](http://en.wikipedia.org/wiki/CentOS) myself, but it seems that the program to control what is started at which runlevel is [ntsysv](http://centos.org/modules/newbb/viewtopic.php?viewmode=flat&order=ASC&topic_id=12486&forum=37). |
126,106 | I have created a script to start a server (my first question). Now I want it to run on the system boot and start the defined server. What should I do to get this done?
My findings tell me put this file in the `/etc/init.d` location, and it will execute when the system will boot. But I am not able to understand how the first argument on the startup will be `start`? Is this predefined somewhere to use `start` as `$1`? If I want to have a case `startall` that will start all the servers in the script, then what are the options I can manage?
My script is like this:
```
#!/bin/bash
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
$0 stop
$0 start
;;
*)
echo "usage: $0 (start|stop|restart)"
;;
esac
``` | 2010/03/31 | [
"https://superuser.com/questions/126106",
"https://superuser.com",
"https://superuser.com/users/29155/"
]
| `/etc/init.d` is the script directory, in which the executable scripts appear. However, in order to run scripts in a particular order after your system starts, you need to add files to the `/etc/rc#.d` directory. Entries that appear here tell your system in what order and at what run level scripts in `/etc/init.d` should be run. The number after the rc indicates what run level the machine is running at, according to this chart:
<http://en.wikipedia.org/wiki/Runlevel>
So if you have:
```
/etc/init.d/importantscript
```
Then you need the (empty) files:
```
/etc/rc.d/rc3.d/S20importantscript
/etc/rc.d/rc6.d/K20importantscript
```
The S means start, and the K means kill. When your machine starts, the system will say "Ah, I'm running at RunLevel 3, let's pop over to rc3.d to see what scripts in '/etc/init.d' need to be run and in what order." In this case, the system will sort by 'S' and then the number after 'S' and will execute '/etc/init.d/importantscript start'. The 20 is just for ordering purposes... your script will run behind 'S19' and in front of 'S21'. You can create these files simply by doing:
`sudo touch /etc/rc.d/rc3.d/S20importantscript`
Here's a nice summary as well: <http://www.linux.com/news/enterprise/systems-management/8116-an-introduction-to-services-runlevels-and-rcd-scripts> | You don't have to --- and shouldn't --- create files in `/etc/rc.d/rcN.d/`; what you should do instead is put a comment in your init script reading
```
# chkconfig NNN A B
```
where `NNN` is the set of run-levels in which you want the script active (e.g., `345` if it's active in runlevels `3`, `4`, and `5`), and `A` and `B` are the start and stop priorities. Then `chkconfig --add foo` (assuming your script is named `foo`) will create the files in `/etc/rc.d/rcN.d/` with the appropriate names.
You can then use `service foo bar` to send the `bar` message to your script (e.g., `start`, `stop`, whatever -- that's where your `$1` comes from). |
31,379,823 | Consider this case. I am writing a library and want to wrap my data in a namespace. For example:
```
//header.h
#pragma once
namespace wrapper
{
// some interface functions here..
}
```
And I want to make my namespace private. So that no one can write anything in it. For instance, we can always write something like this.
```
namespace std
{
// some data here..
}
```
So I want to prevent the last case. Is there any technique to do that besides using static functions wrapped in a class? | 2015/07/13 | [
"https://Stackoverflow.com/questions/31379823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856429/"
]
| This is not possible. If all else fails, I can always edit your header file. | No there isn't. A namespace can always be added to, unless it's an *anonymous namespace*. But they can only feasibly reside in a single compilation unit. |
31,379,823 | Consider this case. I am writing a library and want to wrap my data in a namespace. For example:
```
//header.h
#pragma once
namespace wrapper
{
// some interface functions here..
}
```
And I want to make my namespace private. So that no one can write anything in it. For instance, we can always write something like this.
```
namespace std
{
// some data here..
}
```
So I want to prevent the last case. Is there any technique to do that besides using static functions wrapped in a class? | 2015/07/13 | [
"https://Stackoverflow.com/questions/31379823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856429/"
]
| No there isn't. A namespace can always be added to, unless it's an *anonymous namespace*. But they can only feasibly reside in a single compilation unit. | A namespace cannot be made private, there is no access control (i.e. similar to a class) for a namespace. Even without attempting to edit the header file, the namespace can always be added to.
Alternatives include;
* Put the data into the cpp file, still in a namespace if desired. Thus the data is not "private" but since it is not in the header it is also not "visible" to the client.
* This is possibly better but may require more effort given the question; is to make use of the "pimpl" (or [private class data](https://en.wikipedia.org/wiki/Private_class_data_pattern)) idiom to "hide" the data in the class from the client. The [bridge pattern](https://en.wikipedia.org/wiki/Bridge_pattern) could also be used. |
31,379,823 | Consider this case. I am writing a library and want to wrap my data in a namespace. For example:
```
//header.h
#pragma once
namespace wrapper
{
// some interface functions here..
}
```
And I want to make my namespace private. So that no one can write anything in it. For instance, we can always write something like this.
```
namespace std
{
// some data here..
}
```
So I want to prevent the last case. Is there any technique to do that besides using static functions wrapped in a class? | 2015/07/13 | [
"https://Stackoverflow.com/questions/31379823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856429/"
]
| This is not possible. If all else fails, I can always edit your header file. | A namespace cannot be made private, there is no access control (i.e. similar to a class) for a namespace. Even without attempting to edit the header file, the namespace can always be added to.
Alternatives include;
* Put the data into the cpp file, still in a namespace if desired. Thus the data is not "private" but since it is not in the header it is also not "visible" to the client.
* This is possibly better but may require more effort given the question; is to make use of the "pimpl" (or [private class data](https://en.wikipedia.org/wiki/Private_class_data_pattern)) idiom to "hide" the data in the class from the client. The [bridge pattern](https://en.wikipedia.org/wiki/Bridge_pattern) could also be used. |
57,330,034 | I am trying to build a function that checks if all fields are populated, if populated then show div if not hide.
I can get this to work on one fields however i have then tried two ways of checking multiple.
**first**
if first condition met I then ran other condition checking second field nested inside the first... this done not work.
**second**
I passed in an array of ID's rather than a single... this did not work either..
I am left with a working function that only works if first filed is populated can anyone think of a solution to this or maybe i passed in my array incorrectly.
**My code**
```
var myVar = setInterval(myTimer, 10);
function myTimer() {
if(!document.getElementById('Email').value) { // I need this to pass if multiple id's
var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "hidden"; // or
divsToHide[i].style.display = "none"; // depending on what you're doing
}
}
else {
var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "visible"; // or
divsToHide[i].style.display = "block"; // depending on what you're doing
}
}
}
``` | 2019/08/02 | [
"https://Stackoverflow.com/questions/57330034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975042/"
]
| Make it so your function takes an argument of the element ID and the class Name you need to check for.
Also, never use `.getElementsByClassName()` ([read here for why](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474)). Instead, use [`.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll).
And, you can use the modern `.forEach()` API of arrays and node lists (not in IE though), which is simpler than managing traditional `for` loops with indexes.
Lastly, use pre-made CSS classes instead of inline styling.
```js
// You just need to pass the ID and Class to the following line
var myVar = setInterval(function(){ myTimer([id here],[class here]) }, 10);
function myTimer(id, class) {
// Set up these references just once and the rest of the code
// will be easier to read
var elem = document.getElementById(id);
var divsToHide = document.querySelectorAll("." + class);
// Instead of negative logic, reverse the if branches
if(elem.value) {
divsToHide.forEach(function(){
this.classList.remove("hidden"); // Much simpler than inline styling
});
} else {
divsToHide.forEach(function(){
this.classList.add("hidden");
});
}
```
```css
/* Use pre-made CSS classes instead of inline styling */
.hidden { display:none; }
``` | You can create a const of all elements that need to validate. For example,
```
const elementIdsToBeValidated = ['name', 'email'];
```
You can also create validator functions that returns true and false based on input,
```
const nameValidator = (val) => !!val;
const emailValidator = (email) => !!email;
const validators = [nameValidator, emailValidator];
```
Then you can run your timer function,
```
var myVar = setInterval(myTimer(['name', 'email']), 10);
function myTimer(ids) {
ids.forEach(id => {
const el = document.getElementById(id);
const val = el.value;
const divEl = document.getElementById('error');
const valid = validators.reduce((acc, validator) => validator(val), false);
if(valid) {
divEl.style.display = 'none';
} else {
divEl.style.display = 'block';
}
});
}
```
You can look at this stackBlitz example,
<https://stackblitz.com/edit/js-ie7ljf> |
57,330,034 | I am trying to build a function that checks if all fields are populated, if populated then show div if not hide.
I can get this to work on one fields however i have then tried two ways of checking multiple.
**first**
if first condition met I then ran other condition checking second field nested inside the first... this done not work.
**second**
I passed in an array of ID's rather than a single... this did not work either..
I am left with a working function that only works if first filed is populated can anyone think of a solution to this or maybe i passed in my array incorrectly.
**My code**
```
var myVar = setInterval(myTimer, 10);
function myTimer() {
if(!document.getElementById('Email').value) { // I need this to pass if multiple id's
var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "hidden"; // or
divsToHide[i].style.display = "none"; // depending on what you're doing
}
}
else {
var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "visible"; // or
divsToHide[i].style.display = "block"; // depending on what you're doing
}
}
}
``` | 2019/08/02 | [
"https://Stackoverflow.com/questions/57330034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975042/"
]
| If you have an array of the IDs such as
```
let idArray = ['foo', 'bar', 'baz']
```
You can iterate through an array using a `for` loop
```
for (i = 0; i > idArray.length; i++) {
if (!document.getElementById(idArray[i]).value) {
// your hide logic
} else {
// your show logic
}
}
``` | You can create a const of all elements that need to validate. For example,
```
const elementIdsToBeValidated = ['name', 'email'];
```
You can also create validator functions that returns true and false based on input,
```
const nameValidator = (val) => !!val;
const emailValidator = (email) => !!email;
const validators = [nameValidator, emailValidator];
```
Then you can run your timer function,
```
var myVar = setInterval(myTimer(['name', 'email']), 10);
function myTimer(ids) {
ids.forEach(id => {
const el = document.getElementById(id);
const val = el.value;
const divEl = document.getElementById('error');
const valid = validators.reduce((acc, validator) => validator(val), false);
if(valid) {
divEl.style.display = 'none';
} else {
divEl.style.display = 'block';
}
});
}
```
You can look at this stackBlitz example,
<https://stackblitz.com/edit/js-ie7ljf> |
71,770,276 | I created the aks cluster with azure service principal id and i provided the contributer role according to the subscription and resource group.
For each and every time when i executed the pipeline the sign-in is asking and after i authenticated it is getting the data.
Also the "kubectl get" task is taking more than 30 min and is getting "Kubectl Server Version: Could not find kubectl server version"
*To sign in, use a web browser to open the page <https://microsoft.com/devicelogin> and enter the code CRA2XssWEXUUA to authenticate*
Thanks in advance
[](https://i.stack.imgur.com/wxXk9.png) | 2022/04/06 | [
"https://Stackoverflow.com/questions/71770276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11617499/"
]
| The easiest solution may be to flatten the different split characters to a single one:
```py
with open("example.dat", "r") as fh:
lines = []
for line in fh:
lines.append( line.strip().replace("[", ",").replace("]", ",").split(",") )
``` | You can use named groups in regular expression to more properly extract the information (read more here: <https://www.regular-expressions.info/refext.html>):
```
import re
pat = r"(?P<city>[^,]*), (?P<state>[\w\W]*)\[(?P<lat>\d+),(?P<lon>\d+)\](?P<pop>\d+)"
pat = re.compile(pat, re.VERBOSE)
city = match.group("city")
state = match.group("state")
lat = float(match.group("lat"))
lon = float(match.group("lon"))
population = int(match.group("pop"))
line = [city, state, lat, lon, population)
# => ['New York City', ' NY', 40.0, 74.0, 11000000]
``` |
71,770,276 | I created the aks cluster with azure service principal id and i provided the contributer role according to the subscription and resource group.
For each and every time when i executed the pipeline the sign-in is asking and after i authenticated it is getting the data.
Also the "kubectl get" task is taking more than 30 min and is getting "Kubectl Server Version: Could not find kubectl server version"
*To sign in, use a web browser to open the page <https://microsoft.com/devicelogin> and enter the code CRA2XssWEXUUA to authenticate*
Thanks in advance
[](https://i.stack.imgur.com/wxXk9.png) | 2022/04/06 | [
"https://Stackoverflow.com/questions/71770276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11617499/"
]
| The easiest solution may be to flatten the different split characters to a single one:
```py
with open("example.dat", "r") as fh:
lines = []
for line in fh:
lines.append( line.strip().replace("[", ",").replace("]", ",").split(",") )
``` | Regex is pretty useful in such cases:
```
import re
x = 'New York City, NY[40,74]11000000'
res = re.split(', |\[|\]|,', x)
print(res)
#####
['New York City', 'NY', '40', '74', '11000000']
``` |
3,617,766 | Is there any logger to asp.net like the System.ServiceModel.MessageLogging used in WCF? | 2010/09/01 | [
"https://Stackoverflow.com/questions/3617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373433/"
]
| You could use log4net for this... [log4net Website](http://logging.apache.org/log4net/index.html) | Not sure what you are actually asking for. There is [ASP.NET tracing](http://msdn.microsoft.com/en-us/library/0x5wc973.aspx) and [trace.axd](http://msdn.microsoft.com/en-us/library/wwh16c6c.aspx) handler to browsing traces. |
3,617,766 | Is there any logger to asp.net like the System.ServiceModel.MessageLogging used in WCF? | 2010/09/01 | [
"https://Stackoverflow.com/questions/3617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373433/"
]
| There is health monitoring: <http://msdn.microsoft.com/en-us/library/ff650305.aspx>. It has a bunch of predefined events, plus you can create your own custom events for tracking purposes. | You could use log4net for this... [log4net Website](http://logging.apache.org/log4net/index.html) |
3,617,766 | Is there any logger to asp.net like the System.ServiceModel.MessageLogging used in WCF? | 2010/09/01 | [
"https://Stackoverflow.com/questions/3617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373433/"
]
| You could use log4net for this... [log4net Website](http://logging.apache.org/log4net/index.html) | After having used it myself, I'd like to suggest [ELMAH](http://code.google.com/p/elmah/):
>
> ELMAH (Error Logging Modules and
> Handlers) is an application-wide error
> logging facility that is completely
> pluggable. It can be dynamically added
> to a running ASP.NET web application,
> or even all ASP.NET web applications
> on a machine, without any need for
> re-compilation or re-deployment.
>
>
> |
3,617,766 | Is there any logger to asp.net like the System.ServiceModel.MessageLogging used in WCF? | 2010/09/01 | [
"https://Stackoverflow.com/questions/3617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373433/"
]
| There is health monitoring: <http://msdn.microsoft.com/en-us/library/ff650305.aspx>. It has a bunch of predefined events, plus you can create your own custom events for tracking purposes. | Not sure what you are actually asking for. There is [ASP.NET tracing](http://msdn.microsoft.com/en-us/library/0x5wc973.aspx) and [trace.axd](http://msdn.microsoft.com/en-us/library/wwh16c6c.aspx) handler to browsing traces. |
3,617,766 | Is there any logger to asp.net like the System.ServiceModel.MessageLogging used in WCF? | 2010/09/01 | [
"https://Stackoverflow.com/questions/3617766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373433/"
]
| There is health monitoring: <http://msdn.microsoft.com/en-us/library/ff650305.aspx>. It has a bunch of predefined events, plus you can create your own custom events for tracking purposes. | After having used it myself, I'd like to suggest [ELMAH](http://code.google.com/p/elmah/):
>
> ELMAH (Error Logging Modules and
> Handlers) is an application-wide error
> logging facility that is completely
> pluggable. It can be dynamically added
> to a running ASP.NET web application,
> or even all ASP.NET web applications
> on a machine, without any need for
> re-compilation or re-deployment.
>
>
> |
38,488,978 | Using Google Analytics [Sessions API](https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=session&jump=ga_sessions) I can get the total hits (i.e. total page views and events etc) in a session.
Is there a way to get a list of all the page views and events that took place in a session? If this data cannot be obtained using core reporting API can it be exported to BigTable if Google Analytics Premium is used? | 2016/07/20 | [
"https://Stackoverflow.com/questions/38488978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553223/"
]
| We should first locate the columns that will be adjusted. We do this according to your description as the columns from `Al` to `Zn`. Next we `sub` unnecessary characters and convert to `numeric` with the `numerize` function. I added more columns to show the complexity:
```
cols <- match("Al", names(df)):match("Zn", names(df))
numerize <- function(x) as.numeric(sub(".*?([0-9.-]+).*", "\\1", x))
#base R
df[cols] <- lapply(df[cols], numerize)
#dplyr
df %>% mutate_at(vars(Al:Zn), numerize)
#data.table
setDT(df)[, (names(df)[cols]) := lapply(.SD, numerize), .SDcols=cols][]
# columnNum Al Yw Zn Ca
# 1 G1 5 8 1 9
# 2 G2 6 6 6 10
# 3 G3 7 7 7 11
# 4 G1 4 4 4 10
# 5 G2 5 5 5 11
# 6 G3 6 6 6 12
```
**Data**
```
columnNum <- c("G1", "G2", "G3")
Al <- c("<5", 6, 7, "<4", 5, 6)
Yw <- c("<8", 6, 7, "<4", 5, 6)
Zn <- c("<1", 6, 7, "<4", 5, 6)
Ca <- c(9, 10, 11,10, 11, 12)
df <- data.frame(columnNum, Al, Yw, Zn, Ca, stringsAsFactors = FALSE)
``` | `tidyr::extract_numeric` is handy, whether in `dplyr` or not:
```
df$Al <- tidyr::extract_numeric(Al) # or df %>% mutate(Al = extract_numeric(Al))
```
which is roughly equivalent to
```
df$Al <- as.numeric(sub('.*(-?[0-9]+.?[0-9]*).*', '\\1', df$Al))
```
which for this particular case could be simplified to:
```
df$Al <- as.integer(sub('<', '', df$Al))
```
Regardless of which you use, for this data you get:
```
## columnNum Al Ca
## 1 G1 5 9
## 2 G2 6 10
## 3 G3 7 11
## 4 G1 4 10
## 5 G2 5 11
## 6 G3 6 12
``` |
57,062,428 | I am testing an spring boot application that reads/writes data to an Oracle DB. This Oracle DB has Oracle packages and in those packages procedures. At some point, the spring boot application calls this procedure via a Entity Repository as follows
```java
@Repository
public interface StudentRepository extends JpaRepository<Student, String> {
@Modifying
@Query(value = "begin sch1.STUDENT_PACKAGE.Set_Grades_To_A('A'); end;", nativeQuery = true)
public void setStudentGradeToA();
}
```
So, it uses a native query to make the call to to a procedure `Set_GradesToA` in the `STUDENT_PACKAGE` package of the `sch1` schema.
I am currently testing the functionality of the Spring Boot application and **NOT** the integration between it and the Oracle database. Therefore, I have decided to use an in-memory database (H2) (with the Oracle compatibility option) to replace the Oracle DB for now. **BUT how can I fake out these java package procedures?**
I have tried creating an alias in my schema.sql (or data.sql) as follows:
```sql
CREATE SCHEMA if not exists sch1;
CREATE ALIAS sch1.STUDENT_PACKAGE AS $$ void Set_Grades_To_A(String s) { new String(s); } $$;
```
I really don't care what is inside the `Set_Grades_To_A` procedure what I care about is how to define it.
When I create the alias as above, I'm still getting a Syntax Error.
```
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "BEGIN SCH1[*].STUDENT_PACKAGE.Set_Grades_To_A('A'); END; "; SQL statement:
begin sch1.STUDENT_PACKAGE.Set_Grades_To_A('A'); end; [42000-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.message.DbException.getSyntaxError(DbException.java:203)
```
I guess I have two questions:
1. How can I fake out a stored procedure inside an Oracle package in the schema sch1?
2. Why am I getting the Syntax Error above? | 2019/07/16 | [
"https://Stackoverflow.com/questions/57062428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8032106/"
]
| Here is what I did.
**Question #2:** To answer this question I had to change the native query as follows
```java
@Repository
public interface StudentRepository extends JpaRepository<Student, String> {
@Modifying
@Query(value = "call sch1.STUDENT_PACKAGE.Set_Grades_To_A('A')", nativeQuery = true)
public void setStudentGradeToA();
}
```
**Question #1:** Three things are involved to answer this. Now that I had changed the native query as above I got a different error:
```
Caused by: org.h2.jdbc.JdbcSQLException: Database "sch1" not found; SQL statement:
call sch1.STUDENT_PACKAGE.Set_Grades_To_A('A') [90013-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
```
It was looking for a database called `sch1`. It seems like the pattern used to call a stored procedure in H2 is `database.schema.procedure_name`. Since I don't care what that procedure actually does I was able to fake this out by creating a database called `sch1` a schema called `STUDENT_PACKAGE` and the procedure name `Set_Grades_To_A`
To create the in memory database, you have to set the following property `spring.datasource.url` in the `application.properties` file.
1. Create the `sch1` database as follows `spring.datasource.url=jdbc:h2:mem:sch1;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=CREATE SCHEMA IF NOT EXISTS first_schema`. Notice the database name is `sch1`
2. Create the `STUDENT_PACKAGE` schema by adding this `\\;CREATE SCHEMA IF NOT EXISTS STUDENT_PACKAGE` to the end of the `spring.datasource.url`. This adds a second schema called `STUDENT_PACKAGE`. The property should look like this `spring.datasource.url=jdbc:h2:mem:sch1;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=CREATE SCHEMA IF NOT EXISTS first_schema\\;CREATE SCHEMA IF NOT EXISTS STUDENT_PACKAGE`
3. Create a the `Set_Grades_To_A` stored procedure by adding this to your schema.sql `CREATE ALIAS STUDENT_PACKAGE.Set_Grades_To_A AS $$ void setGradesToA(String s) { new StringBuilder(s).reverse().toString(); } $$;` | I was able to fix the issue by adding `IGNORE_CATALOGS=TRUE`
```
spring.datasource.url = jdbc:h2:mem:testdb;MODE=Oracle;IGNORE_CATALOGS=TRUE
```
This will ignore the database name |
16,651,031 | I stored the data bytes in an Array. Now, in the program I used getBytes:range:NSmakeRange(position, length). When I printed my received bytes I think their position got swapped and my answer was 0x0292 instead of 0x9202 (check my program below).
Now, I am confused on which one is the correct answer. Is it really necessary for me to always swap the bytes that I received. Please explain to me this concept so that I can understand in a clear way.
Here is my code!! Thank you.
```
const Byte dataBytesArray[] = {
0x92, 0x02, 0x13, 0x14 //in Hex
};
NSData *myDataArray = [[NSData alloc]initWithBytes:dataBytesArray length:4];
uint16_t ef;
[myDataArray getBytes:&ef range:NSMakeRange(0, 2)];
NSLog(@"dataByteArray is %@ ",[NSNumber numberWithUnsignedInteger:ef]);//the answer I got is 658 in decimal format which is 0x0292
uint16_t swapping = CFSwapInt16BigToHost(ef); //swapping the bytes
NSLog(@"swap is %@ ",[NSNumber numberWithUnsignedInteger:swapping]); //after swapping I got 37378 which is 0x9202
``` | 2013/05/20 | [
"https://Stackoverflow.com/questions/16651031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029446/"
]
| Whether you make use of functions like `CFSwapInt16BigToHost` depends on what you are dealing with on both ends.
If your "host" (the machine this code is running on) could vary, then using one of the many `CFSwap...ToHost` functions is a really good idea. For example, Intel Macs and ARM iOS devices use different byte ordering. PowerPC Macs and Intel Macs use different byte ordering (I think that is true). To make your code safe to run in these different environments, it is wise to use the proper "toHost" function.
Even if your code is currently meant to only run on one type of device, it is still wise to use these to avoid any confusion in the proper order for the host.
So the key decision is to know what byte ordering is used in the received data. If you know for a fact that the received data is in big-endian byte order then use the proper "BigToHost" functions. If you know for a fact that the received data is in little-endian bye order then use the proper "LittleToHost" functions. If you don't know then you must find out.
Another thing to consider is sending data from your app. You should use the proper "HostTo" functions. This is really important in iOS apps for example. Your iOS app may be run on an ARM iOS device or it may run in the Simulator on an Intel Mac. If you just send host bytes then the order will vary depending on where the app is run. This is bad. So the app should pick an order and then use the proper "HostTo" functions to convert data to the chosen order. Then any code that needs to read that data can specify that same order in its use of the "ToHost" functions. | It's all about endianness. If you receive your data form the network, it will be big endian. Your machine is little endian, so in that case you need to swap the bytes.
See: <http://en.wikipedia.org/wiki/Endianness> |
217,415 | Can I see how many duplicates there are of a post? I.e. how many posts have been labelled as duplicate because of this post? If so, how? And can I also get a list of these duplicated posts? | 2014/01/24 | [
"https://meta.stackexchange.com/questions/217415",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/227229/"
]
| The most reliable way to do this is to [use the Data Explorer:](https://data.stackexchange.com/stackoverflow/query/162748/duplicates-for-a-given-post?OriginalPostId=8028957)
```sql
select PostId as [Post Link]
from PostLinks
where RelatedPostId=##OriginalPostId##
and LinkTypeId=3 -- duplicate
```
This will give you both a total count for questions closed as duplicates of a given original post, *and* links to all of the ones that haven't been deleted yet. | There is a record of all *linked* questions, both linked from the given question to others and vice versa. You can see the full list by directly browsing to this URL: `https://meta.stackexchange.com/questions/linked/[question id]`
For example: <https://meta.stackexchange.com/questions/linked/194476>
>
> 
>
>
>
Questions marked `[duplicate]` may be duplicates of the question having the ID in the URL.
If you're already in a question page there is "Linked" section when there are any linked posts:
>
> 
>
>
>
And "see more linked questions…" when there are more than 10. (leading to the above page) |
14,011,093 | ```
sLine = sLine.replaceAll("&&", "&");
sLine = sLine.replaceAll(((char)245)+"", "ő");
sLine = sLine.replaceAll(((char)213)+"", "Ő");
sLine = sLine.replaceAll(((char)361)+"", "ű");
sLine = sLine.replaceAll(((char)251)+"", "ű");
```
Is there a way to to this only one line? This is very slow on big strings. | 2012/12/23 | [
"https://Stackoverflow.com/questions/14011093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472537/"
]
| Consider converting the string to a `char[]` and then iterating over the array manually.
Avoid string concatenation such as `((char)245)+""`. Use a character constant.
But it looks like you are trying to *fix the encoding of strings* manually? That is a *really bad idea*. Because next week, you will have a user with the `ü` character. And then, someone will use a `€` currency value. And then a spanish user will want to use the `¿` character. How many `replaceAll` are you willing to add?!?
Look at how to **encode/decode/recode strings**.
Maybe use the following constructor instead:
```
String(byte[] bytes, Charset charset)
```
and look at the Java Charset classes:
* [java.nio.charset.Charset](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html)
* [java.nio.charset.CharsetDecoder](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetDecoder.html)
* [java.nio.charset.CharsetEncoder](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html) | You can improve performance by using precompiled regular expressions. Under the hood `String.replaceAll` is going to compile and apply a regular expression for you anyway. As compilation of the regexp is *relatively* computationally intensive, this should improve performance when executing this code frequently.
```
private static final Pattern PATTERN_1 = Pattern.compile("\u00f5");
private static final Pattern PATTERN_2 = Pattern.compile(Character.toString((char) 241));
String original = new String("A" + (char) 245 + "\u00f1" + "D");
String replaced2 = PATTERN_1.matcher(original).replaceAll("B");
replaced2 = PATTERN_2.matcher(replaced2).replaceAll("C");
System.out.println(original + " -> " + replaced2);
```
Will print out:
>
> A??D -> ABCD
>
>
>
When working with a very very long `String` this probably won't offer much performance over what you proposed.
**As an aside:**
Using non UTF-8 characters in code will cause you (and your colleagues) pain down the road. You should use [Unicode characters](http://oreilly.com/actionscript/excerpts/as3-cookbook/appendix.html) or, as you were, character decimal representations at all times. |
14,011,093 | ```
sLine = sLine.replaceAll("&&", "&");
sLine = sLine.replaceAll(((char)245)+"", "ő");
sLine = sLine.replaceAll(((char)213)+"", "Ő");
sLine = sLine.replaceAll(((char)361)+"", "ű");
sLine = sLine.replaceAll(((char)251)+"", "ű");
```
Is there a way to to this only one line? This is very slow on big strings. | 2012/12/23 | [
"https://Stackoverflow.com/questions/14011093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472537/"
]
| Consider converting the string to a `char[]` and then iterating over the array manually.
Avoid string concatenation such as `((char)245)+""`. Use a character constant.
But it looks like you are trying to *fix the encoding of strings* manually? That is a *really bad idea*. Because next week, you will have a user with the `ü` character. And then, someone will use a `€` currency value. And then a spanish user will want to use the `¿` character. How many `replaceAll` are you willing to add?!?
Look at how to **encode/decode/recode strings**.
Maybe use the following constructor instead:
```
String(byte[] bytes, Charset charset)
```
and look at the Java Charset classes:
* [java.nio.charset.Charset](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html)
* [java.nio.charset.CharsetDecoder](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetDecoder.html)
* [java.nio.charset.CharsetEncoder](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html) | ```
private static final String char1 = Character.toString((char) 245);
private static final String char2 = Character.toString((char) 213);
private static final String char3 = Character.toString((char) 361);
private static final String char4 = Character.toString((char) 251);
private static final Pattern PATTERN_1 = Pattern.compile(char1);
private static final Pattern PATTERN_2 = Pattern.compile(char2);
private static final Pattern PATTERN_3 = Pattern.compile(char3);
private static final Pattern PATTERN_4 = Pattern.compile(char4);
public static String replaceAccents(String sLine) {
String replaced=sLine;
if (replaced.contains(char1)) replaced = PATTERN_1.matcher(replaced).replaceAll("ő");
if (replaced.contains(char2)) replaced = PATTERN_2.matcher(replaced).replaceAll("Ő");
if (replaced.contains(char3)) replaced = PATTERN_3.matcher(replaced).replaceAll("Ű");
if (replaced.contains(char4)) replaced = PATTERN_4.matcher(replaced).replaceAll("ű");
return replaced;
}
```
Here is the final and fast code for that, thanks to Sean. |
14,011,093 | ```
sLine = sLine.replaceAll("&&", "&");
sLine = sLine.replaceAll(((char)245)+"", "ő");
sLine = sLine.replaceAll(((char)213)+"", "Ő");
sLine = sLine.replaceAll(((char)361)+"", "ű");
sLine = sLine.replaceAll(((char)251)+"", "ű");
```
Is there a way to to this only one line? This is very slow on big strings. | 2012/12/23 | [
"https://Stackoverflow.com/questions/14011093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472537/"
]
| You can improve performance by using precompiled regular expressions. Under the hood `String.replaceAll` is going to compile and apply a regular expression for you anyway. As compilation of the regexp is *relatively* computationally intensive, this should improve performance when executing this code frequently.
```
private static final Pattern PATTERN_1 = Pattern.compile("\u00f5");
private static final Pattern PATTERN_2 = Pattern.compile(Character.toString((char) 241));
String original = new String("A" + (char) 245 + "\u00f1" + "D");
String replaced2 = PATTERN_1.matcher(original).replaceAll("B");
replaced2 = PATTERN_2.matcher(replaced2).replaceAll("C");
System.out.println(original + " -> " + replaced2);
```
Will print out:
>
> A??D -> ABCD
>
>
>
When working with a very very long `String` this probably won't offer much performance over what you proposed.
**As an aside:**
Using non UTF-8 characters in code will cause you (and your colleagues) pain down the road. You should use [Unicode characters](http://oreilly.com/actionscript/excerpts/as3-cookbook/appendix.html) or, as you were, character decimal representations at all times. | ```
private static final String char1 = Character.toString((char) 245);
private static final String char2 = Character.toString((char) 213);
private static final String char3 = Character.toString((char) 361);
private static final String char4 = Character.toString((char) 251);
private static final Pattern PATTERN_1 = Pattern.compile(char1);
private static final Pattern PATTERN_2 = Pattern.compile(char2);
private static final Pattern PATTERN_3 = Pattern.compile(char3);
private static final Pattern PATTERN_4 = Pattern.compile(char4);
public static String replaceAccents(String sLine) {
String replaced=sLine;
if (replaced.contains(char1)) replaced = PATTERN_1.matcher(replaced).replaceAll("ő");
if (replaced.contains(char2)) replaced = PATTERN_2.matcher(replaced).replaceAll("Ő");
if (replaced.contains(char3)) replaced = PATTERN_3.matcher(replaced).replaceAll("Ű");
if (replaced.contains(char4)) replaced = PATTERN_4.matcher(replaced).replaceAll("ű");
return replaced;
}
```
Here is the final and fast code for that, thanks to Sean. |
19,557,139 | I am parsing a file, and every odd line gives me a "letter" (A, B, C, etc), and every even line gives me a "binary sequence" (0101, 1111, 0001, etc).
I would like to create a hash of arrays (but if you think another datatype is more suitable, please let me know) to keep all lines organized.
I know the has of arrays could look like:
```
%HoA = (
A => [ "0001", "1010" ],
B => [ "0011", "1111", "0111" ],
C => [ "0000"],
);
```
and I know how to *access* information from this data type.
However, I am having trouble *creating* this data type.
For instance, I am able to correctly obtain the "letter" ($letter) and "binary sequence" ($seq) for the file, using something like:
```
while (<INPUT>) {
s/[\n\r]//mg;
if ( /^>/) {
$letter = substr($_, 7, 1);
}
if ( /^[01]/) {
$seq = $_;
}
}
```
But I am unsure how to:
1. create the hash of arrays,
2. check first whether or not that "letter" exists already as a key in the hash
3. if the "letter" does not exist as a key, then how to create it as a new key
4. after either determining the "letter" already exists or creating it if it does not, how to add the "seq" as a value to the "letter".
If such a datatype cannot be created in Perl, then I would appreciate any advice on what sort of data type to turn to! I need to keep each "letter" attached to all its "sequences".
Any help would be much appreciated! | 2013/10/24 | [
"https://Stackoverflow.com/questions/19557139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| To create the hash, just put `my %HoA;` at the beginning of your code. Given a `$letter` and `$seq`, you can accomplish steps 2-4 at once by just doing `push @{$HoA{$letter}}, $seq;`, and Perl takes care of the details. | Check [perl data structures cookbook](http://perldoc.perl.org/perldsc.html#HASHES-OF-ARRAYS).
```
my %HoA;
my $letter;
while (<INPUT>) {
s/[\n\r]//g;
if ( /^>/) {
$letter = substr($_, 7, 1);
}
if ( /^[01]/) {
# $seq = $_;
push @{ $HoA{$letter} }, $_;
}
}
``` |
19,557,139 | I am parsing a file, and every odd line gives me a "letter" (A, B, C, etc), and every even line gives me a "binary sequence" (0101, 1111, 0001, etc).
I would like to create a hash of arrays (but if you think another datatype is more suitable, please let me know) to keep all lines organized.
I know the has of arrays could look like:
```
%HoA = (
A => [ "0001", "1010" ],
B => [ "0011", "1111", "0111" ],
C => [ "0000"],
);
```
and I know how to *access* information from this data type.
However, I am having trouble *creating* this data type.
For instance, I am able to correctly obtain the "letter" ($letter) and "binary sequence" ($seq) for the file, using something like:
```
while (<INPUT>) {
s/[\n\r]//mg;
if ( /^>/) {
$letter = substr($_, 7, 1);
}
if ( /^[01]/) {
$seq = $_;
}
}
```
But I am unsure how to:
1. create the hash of arrays,
2. check first whether or not that "letter" exists already as a key in the hash
3. if the "letter" does not exist as a key, then how to create it as a new key
4. after either determining the "letter" already exists or creating it if it does not, how to add the "seq" as a value to the "letter".
If such a datatype cannot be created in Perl, then I would appreciate any advice on what sort of data type to turn to! I need to keep each "letter" attached to all its "sequences".
Any help would be much appreciated! | 2013/10/24 | [
"https://Stackoverflow.com/questions/19557139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| To create the hash, just put `my %HoA;` at the beginning of your code. Given a `$letter` and `$seq`, you can accomplish steps 2-4 at once by just doing `push @{$HoA{$letter}}, $seq;`, and Perl takes care of the details. | Assuming your data is infallible.
```
#!/usr/bin/perl
use strict;
use warnings FATAL => qw/all/;
use Data::Dumper;
$/ = "\r\n";
my %HoA;
while (<DATA>)
{
my $letter = substr($_, 7, 1);
chomp(my $seq = <DATA>);
push @{$HoA{$letter}}, $seq;
}
print Dumper \%HoA;
__DATA__
> A
0001
> A
1010
> B
0011
> B
1111
> B
0111
> C
0000
``` |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I'm going to pick on @jmort253's answer, because I disagree.
ROI initiatives aren't the only kinds of project, nor should they be. Chris Matts (the analyst behind BDD, Feature Injection and Real Options) found that 80% of one of his CIO's projects were concerned with protecting existing customer revenue, rather than trying to increase it - essentially, stopping their customers leaving for a competitor.
A lot of projects also simply provide *options* for the future. These are often very hard to price, but very, very expensive if they're not done.
Most technical initiatives are done for this reason; to provide the business with options to change in the future. Some of them have more direct business concerns which are more easily phrased, like increasing current system performance to cope with growing demand. Others may be relevant to different parts of the business - changing from Fortran to Python to attract better talent and make it easier to recruit - but in the long run, that's still about having options in the future.
**Technical Debt is, and should be, a PM's concern**
Chris Matts and Steve Freeman [came up with a lovely analogy](http://www.higherorderlogic.com/2010/07/bad-code-isnt-technical-debt-its-an-unhedged-call-option/). "It's not like a credit card. It's like an unhedged call option. It's like you've promised to sell all these chocolate Santas at Christmas, and then suddenly one year the price of chocolate is really high, and you have to sell the Santas anyway because you made that commitment, and now you're bust." As long as nobody makes the call, technical debt doesn't matter.
The problem is that every project has something new about it, or that project wouldn't be happening (see ["Waltzing with Bears"](http://rads.stackoverflow.com/amzn/click/0932633609)). So every project has changes that get made as discoveries happen as a result of feedback from the new thing (see [the complex domain in Cynefi](http://lizkeogh.com/2012/03/11/cynefin-for-devs/)n). And every project is therefore seriously at risk from being called.
(Every project is also difficult to estimate for this reason; you can't estimate something you've never done before.)
**The option to change is usually an unstated a business goal**
I worked with one company that had a single class of 10,000 lines that took Visual Studio 5 minutes to load. When the business found out what poor quality code had been produced, they said, "Why would you ever do that? We expected you to push back if we were making you do that!"
This unstated goal is also, usually, the *core goal* of most projects which are replacing legacy systems. The legacy systems have become too unwieldy, and can't be changed to meet new requirements and architectural demand, so a new system is created. If I had a shiny English pound for every time I've seen a replacement system team abandon the core goal in order to meet some arbitrary deadline, I wouldn't need to work again.
By calling out this unstated goal as an explicit one, everyone involved on the project can talk about it rather than assuming it's happening.
**Educate the business about the cost of technical debt**
Technical debt only happens in the face of time pressure (or as a result of bad habit or lack of skill, which are a different problem, solved by having time to learn how to do the job well... so, time pressure).
By keeping track of the growing cost of the debt and making the business aware of it, you can help to show them the value of the options they're losing. This could include things like your best developers leaving, and the cost of re-hiring; how much extra time the devs reckon it took to create a new feature as a result of technical debt; how much more effective the team is when they're given the chance to take pride in their work instead of bowing to business pressure.
Also educate them about [the alignment trap](http://www.ebizq.net/blogs/agile_enterprise/2009/11/dont-fall-in-the-alignment-trap.php). "Companies in which IT was highly aligned with business but not effective were considerably worse off than companies in which IT was less aligned and merely kept the systems running."
**Pay back technical debt one piece at a time**
In this place I agree with @jmort253. It's even better if you can avoid falling into debt in the first place, but usually there are different skill sets on a team, people learning to code well, etc. - so having the ability to refactor as you go and help educate other developers is more important than getting it right up-front.
If the team feel pressured to churn out new features, though, they'll very quickly abandon the technical debt. It can't be seen or measured easily, and as such is usually the first victim of any pressure.
A PM's responsibility in this situation is to push back, educate, and help the business cut scope instead. | Fascinating discussion, and very relevant to me. I believe that technical debt is a PM's concern.
One could argue that a project is a coordinated effort to produce a specific outcome/change; if the project produces the outcome, the project is successful, and technical debt doesn't enter into the equation. But I think that is shortsighted; at a minimum, the PM is obliged during the closeout procedures to document lessons learned and update the corporate process assets. Technical debt should fall into that category. Beyond that, the PM has an ethical obligation to do the best for the company within the constraints, and leaving a company saddled with unknown, undocumented technical debt is unconscionable.
Alternatively we could consider that technical debit is a quality control problem. Technical debt is a aberration that falls within control limits, but if it can be eliminated, the quality (and presumably value) of the product rises.
Multiple ways to look at the problem, but each of them convinces me that although the PM can ignore technical debt, prudence dictates that the PM estimate, document and manage technical debt.
I think the key challenge is establishing the value of technical debt. I think that companies/industries/teams should establish reference values and refine as they go. Just as the PM is obliged to assess & estimate the impact of every proposed change on schedule/scope/quality, the PM should assess & estimate the impact of technical debt. I think that an interesting corrallary to @Jmort253's question is "Change proposals go to the CCB. Who is accountable for changes that are intrinsically outside the scope of the project?"
As I said, excellent, thought provoking question. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I tend to disagree with the basic assumption that technical initiatives are not business initiatives. They may be different from rolling out a new product or an advertising campaign, but:
* They have a business benefits... be it regulatory compliance, improving efficiencies, making the customer experience better, etc
* They have business costs... training, systems development, etc
* They have business risks... what if stakeholders don't like the changes, what if their costs are more than expected, what if their benefits are less, etc
Where technical initiatives tend to have problems is that they aren't easily understood by decision makers who tend to come from the marketing/sales/"business" side of the house. Basically they aren't as "sexy" as a new marketing campaign or partnership.
The best approach to getting a better focus on "technical debt" is to do a thorough business case for addressing it. How much will addressing the debt cost in time, money and effort? What is the payback period given the expected labor savings, increased sales, increased customer retention, increased market share, etc once the initiative is implemented? How does this compare to the costs and benefits of maintaining the status quo? Getting this information together will take some time and effort, but if it is done well it should be obvious to you whether or not the technical debt needs to be paid *now* or if payment can be deferred. | I know there's an answer for this and I mostly agree with @Lunivore and @jmort253 answers but I thought I would chime in on how I have seen and heard technical debt handled?
In our company we recently started trying to allocate dedicated week-long sprints that we focus on technical debt. Unfortunately this hasn't worked super well when there are certain features that go over the course of multiple sprints, in which case it's impossible to prioritize low-priority fixes vs features that need to ship.
Kind of building on above, I believe **it's important to show and communicate communicate how technical debt is affecting the team's velocity**. This naturally starts with being able to know what your team's velocity is, and then showing it is simply a matter of process.
Recently we have started costing out all issues with [story points](https://agilefaq.wordpress.com/2007/11/13/what-is-a-story-point/) (whether it be features and the small tasks associated with features, or just nitpicky bug fixes) everything is costed out with a certain value. After a period of time, our manager is now able to give a ballpark range of how much bandwidth each engineer has and how much time they can allocate to fixing certain bugs. When we first started this, it was naturally really bumpy because we would forget that there was more to a task so its generally better to overestimate than underestimate.
After some time though, we were able to give a good sense of what we can fit into the sprint and what we can't and we have been given dedicated time to fix bugs that makes sense (hey you have this feature but from what was costed out you seem to have time for some small bugs?). I think we are still working on a good rhythm and we have juggled between alternating people to fix bugs or just dedicating time for the entire team (especially useful if you have new devs) -- maybe I'll chime in again when we have narrowed that down but we have definitely seen an improvement in how fast we do things when given the time to fix the things that no one sees and it's nice that everyone can "see" it too now.
In regards to responsibility, I don't necessarily think it's the PM's responsibility? Our **engineering manager and tech lead drives managing technical debt** while our PM drives the projects and timeline of features. That being said, **it's important there is dedicated time for the PM and the manager to coordinate and set expectations**. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I'm going to pick on @jmort253's answer, because I disagree.
ROI initiatives aren't the only kinds of project, nor should they be. Chris Matts (the analyst behind BDD, Feature Injection and Real Options) found that 80% of one of his CIO's projects were concerned with protecting existing customer revenue, rather than trying to increase it - essentially, stopping their customers leaving for a competitor.
A lot of projects also simply provide *options* for the future. These are often very hard to price, but very, very expensive if they're not done.
Most technical initiatives are done for this reason; to provide the business with options to change in the future. Some of them have more direct business concerns which are more easily phrased, like increasing current system performance to cope with growing demand. Others may be relevant to different parts of the business - changing from Fortran to Python to attract better talent and make it easier to recruit - but in the long run, that's still about having options in the future.
**Technical Debt is, and should be, a PM's concern**
Chris Matts and Steve Freeman [came up with a lovely analogy](http://www.higherorderlogic.com/2010/07/bad-code-isnt-technical-debt-its-an-unhedged-call-option/). "It's not like a credit card. It's like an unhedged call option. It's like you've promised to sell all these chocolate Santas at Christmas, and then suddenly one year the price of chocolate is really high, and you have to sell the Santas anyway because you made that commitment, and now you're bust." As long as nobody makes the call, technical debt doesn't matter.
The problem is that every project has something new about it, or that project wouldn't be happening (see ["Waltzing with Bears"](http://rads.stackoverflow.com/amzn/click/0932633609)). So every project has changes that get made as discoveries happen as a result of feedback from the new thing (see [the complex domain in Cynefi](http://lizkeogh.com/2012/03/11/cynefin-for-devs/)n). And every project is therefore seriously at risk from being called.
(Every project is also difficult to estimate for this reason; you can't estimate something you've never done before.)
**The option to change is usually an unstated a business goal**
I worked with one company that had a single class of 10,000 lines that took Visual Studio 5 minutes to load. When the business found out what poor quality code had been produced, they said, "Why would you ever do that? We expected you to push back if we were making you do that!"
This unstated goal is also, usually, the *core goal* of most projects which are replacing legacy systems. The legacy systems have become too unwieldy, and can't be changed to meet new requirements and architectural demand, so a new system is created. If I had a shiny English pound for every time I've seen a replacement system team abandon the core goal in order to meet some arbitrary deadline, I wouldn't need to work again.
By calling out this unstated goal as an explicit one, everyone involved on the project can talk about it rather than assuming it's happening.
**Educate the business about the cost of technical debt**
Technical debt only happens in the face of time pressure (or as a result of bad habit or lack of skill, which are a different problem, solved by having time to learn how to do the job well... so, time pressure).
By keeping track of the growing cost of the debt and making the business aware of it, you can help to show them the value of the options they're losing. This could include things like your best developers leaving, and the cost of re-hiring; how much extra time the devs reckon it took to create a new feature as a result of technical debt; how much more effective the team is when they're given the chance to take pride in their work instead of bowing to business pressure.
Also educate them about [the alignment trap](http://www.ebizq.net/blogs/agile_enterprise/2009/11/dont-fall-in-the-alignment-trap.php). "Companies in which IT was highly aligned with business but not effective were considerably worse off than companies in which IT was less aligned and merely kept the systems running."
**Pay back technical debt one piece at a time**
In this place I agree with @jmort253. It's even better if you can avoid falling into debt in the first place, but usually there are different skill sets on a team, people learning to code well, etc. - so having the ability to refactor as you go and help educate other developers is more important than getting it right up-front.
If the team feel pressured to churn out new features, though, they'll very quickly abandon the technical debt. It can't be seen or measured easily, and as such is usually the first victim of any pressure.
A PM's responsibility in this situation is to push back, educate, and help the business cut scope instead. | I would start by **Identifying the ROI that the technical debt delivers** and discussing this with the business. If you can describe both value work and what John Seddon calls 'Failure Demand' in the same terms and using the same metrics then you can agree how to split your capacity across them.
**Example - Architectural Refactoring**
We have a piece of configuration information which is baked into an app (I know, I know...). This config can go unchanged for weeks and then suddenly need changing.
If the config doesn't get changed then ads stop appearing in an application and we stop making revenue from it.
The quick and dirty solution is to change the config in the code and redeploy. This is repetitive and error prone and ultimately not sustainable.
The sustainable solution would be to factor our the config from the code and provide a mechanism for changing it independently from the code. This will take longer the first time round but will then make future config changes much quicker and less error prone.
Guess which one we have done twice already? That's right the quick and dirty. This is because the ROI on the feature is immediately visible or rather, the Cost of Delay were the work not to be done is very high.
The sell we have to make to the business is, let us spend time refactoring this to address the technical debt. That way, next time we need to change the config it will be quicker than it currently is, so quicker ROI in the future, but we will need to take some capacity away now to address the technical debt. It is deferred ROI.
**Example - Architectural Refactoring as complexity increases**
Sometimes it is hard to describe the technical debt to the business, to them it is just an implementation detail or something you should not have accrued in the first place.
For example, as something grows in complexity it requires refactoring. In this case I do one of two things.
I either cover the cost of the refactoring in the delivery of the feature which has required us to go back and look at the code in question. I always call this out to the business either to tell them that the feature will take longer to deliver than similar features have in the past, because we have reached a point where we need to refactor.
Again I describe this to them as deferred ROI. There will be a greater upfront cost but by doing the refactoring now, future work in this area will be cheaper.
The other approach I take is to treat the development team as a customer of itself and reserve a percentage of capacity, agreed with the business, in each iteration for reduction of technical debt.
**Example - Platform Upgrade**
For the example you give of upgrading to a newer platform I would again look at how you can describe this in terms of ROI, or impact on ROI.
If the existing platform is no longer supported by the vendor then the business is exposed to the risk of defects discovered in that version of the platform not getting fixed and so impacting on business functionality which depends on it.
This impact will be an increase in failure demand, that is, customers will be less able to get value out of what you as a business provide as problems with the underlying platform are getting in the way. This can be articulated as lost revenue, or potential lost revenue so the ROI is to upgrade the underlying platform.
Prioritising such an upgrade can again be done by looking at the Cost of Delay. If you were not to upgrade the platform would there be any impact on your existing products and services? Would it prevent you from launching new ones?
If problems in the existing platform are generating failure demand now then the Cost of Delay is high and you have a compelling ROI based argument for doing the work sooner rather than later.
If you are currently unaffected by problems in the existing platform but need to upgrade in order to add new functionality then the ROI of the new functionality will determine the ROI of upgrading the platform. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I'm going to pick on @jmort253's answer, because I disagree.
ROI initiatives aren't the only kinds of project, nor should they be. Chris Matts (the analyst behind BDD, Feature Injection and Real Options) found that 80% of one of his CIO's projects were concerned with protecting existing customer revenue, rather than trying to increase it - essentially, stopping their customers leaving for a competitor.
A lot of projects also simply provide *options* for the future. These are often very hard to price, but very, very expensive if they're not done.
Most technical initiatives are done for this reason; to provide the business with options to change in the future. Some of them have more direct business concerns which are more easily phrased, like increasing current system performance to cope with growing demand. Others may be relevant to different parts of the business - changing from Fortran to Python to attract better talent and make it easier to recruit - but in the long run, that's still about having options in the future.
**Technical Debt is, and should be, a PM's concern**
Chris Matts and Steve Freeman [came up with a lovely analogy](http://www.higherorderlogic.com/2010/07/bad-code-isnt-technical-debt-its-an-unhedged-call-option/). "It's not like a credit card. It's like an unhedged call option. It's like you've promised to sell all these chocolate Santas at Christmas, and then suddenly one year the price of chocolate is really high, and you have to sell the Santas anyway because you made that commitment, and now you're bust." As long as nobody makes the call, technical debt doesn't matter.
The problem is that every project has something new about it, or that project wouldn't be happening (see ["Waltzing with Bears"](http://rads.stackoverflow.com/amzn/click/0932633609)). So every project has changes that get made as discoveries happen as a result of feedback from the new thing (see [the complex domain in Cynefi](http://lizkeogh.com/2012/03/11/cynefin-for-devs/)n). And every project is therefore seriously at risk from being called.
(Every project is also difficult to estimate for this reason; you can't estimate something you've never done before.)
**The option to change is usually an unstated a business goal**
I worked with one company that had a single class of 10,000 lines that took Visual Studio 5 minutes to load. When the business found out what poor quality code had been produced, they said, "Why would you ever do that? We expected you to push back if we were making you do that!"
This unstated goal is also, usually, the *core goal* of most projects which are replacing legacy systems. The legacy systems have become too unwieldy, and can't be changed to meet new requirements and architectural demand, so a new system is created. If I had a shiny English pound for every time I've seen a replacement system team abandon the core goal in order to meet some arbitrary deadline, I wouldn't need to work again.
By calling out this unstated goal as an explicit one, everyone involved on the project can talk about it rather than assuming it's happening.
**Educate the business about the cost of technical debt**
Technical debt only happens in the face of time pressure (or as a result of bad habit or lack of skill, which are a different problem, solved by having time to learn how to do the job well... so, time pressure).
By keeping track of the growing cost of the debt and making the business aware of it, you can help to show them the value of the options they're losing. This could include things like your best developers leaving, and the cost of re-hiring; how much extra time the devs reckon it took to create a new feature as a result of technical debt; how much more effective the team is when they're given the chance to take pride in their work instead of bowing to business pressure.
Also educate them about [the alignment trap](http://www.ebizq.net/blogs/agile_enterprise/2009/11/dont-fall-in-the-alignment-trap.php). "Companies in which IT was highly aligned with business but not effective were considerably worse off than companies in which IT was less aligned and merely kept the systems running."
**Pay back technical debt one piece at a time**
In this place I agree with @jmort253. It's even better if you can avoid falling into debt in the first place, but usually there are different skill sets on a team, people learning to code well, etc. - so having the ability to refactor as you go and help educate other developers is more important than getting it right up-front.
If the team feel pressured to churn out new features, though, they'll very quickly abandon the technical debt. It can't be seen or measured easily, and as such is usually the first victim of any pressure.
A PM's responsibility in this situation is to push back, educate, and help the business cut scope instead. | I tend to disagree with the basic assumption that technical initiatives are not business initiatives. They may be different from rolling out a new product or an advertising campaign, but:
* They have a business benefits... be it regulatory compliance, improving efficiencies, making the customer experience better, etc
* They have business costs... training, systems development, etc
* They have business risks... what if stakeholders don't like the changes, what if their costs are more than expected, what if their benefits are less, etc
Where technical initiatives tend to have problems is that they aren't easily understood by decision makers who tend to come from the marketing/sales/"business" side of the house. Basically they aren't as "sexy" as a new marketing campaign or partnership.
The best approach to getting a better focus on "technical debt" is to do a thorough business case for addressing it. How much will addressing the debt cost in time, money and effort? What is the payback period given the expected labor savings, increased sales, increased customer retention, increased market share, etc once the initiative is implemented? How does this compare to the costs and benefits of maintaining the status quo? Getting this information together will take some time and effort, but if it is done well it should be obvious to you whether or not the technical debt needs to be paid *now* or if payment can be deferred. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| **Technical Debt isn't a PM's Responsibility:**
-----------------------------------------------
As a project manager, the short answer is, you don't. This is really a job for the technical team, which includes functional managers and the actual developers working on the project. If you're doing project management correctly, then you should be getting all of your estimates from the developers themselves.
However, if it becomes a noticeable detriment to productivity, it may become a project management issue.
**Focus Primarily on Business Goals:**
--------------------------------------
However, here is where this can get tricky and why sometimes it is helpful for a project manager to have enough experience in the subject matter to know the difference between a good estimate and a bad estimate. New developers, fresh out of college and eager to apply their newfound knowledge, will sometimes be the first to suggest a complete rewrite to the database layer because it's a cluttered mess.
Sure, the job may have been to write a feature that lets the customer service team sort customer data by creation date, something that helps the team improve retention efforts, but this eager dev attempts to take the issue scope to another level. By prioritizing technical debt the wrong way, the actual feature being developed is removed from focus, and management is justified in stopping this in its tracks. If revenue isn't being generated from a development operation, then there's a problem with the balance.
**Pay Back Technical Debt One Piece at a Time:**
------------------------------------------------
As a developer, I've worked with some code that I've had a pretty strong opinion about. When I told my project manager about it, he said he didn't care. He didn't want to think about it, and that it was my job to include this in the estimates in a way that didn't conflict with business goals. I've been doing that ever since, and I manage my own technical debt while still keeping management happy with the progress. In many cases, it actually makes the development faster because the impediments that would normally slow me down are removed.
Ultimately, the solution to managing technical debt and balancing it with company initiatives is to break it up into manageable, bite-sized chunks. If the database layer needs a rewrite, start with the new feature. Add it in a manner that scales, and then next time a new feature is added fix a little bit more. You should only commit to paying back a small portion of technical debt so that it doesn't stand out as a red flag to management, similar to how you should only pay down enough of your debt to where you can still pay your rent and eat your meals. ;)
In short, the way to balance technical debt against business goals and initiatives is to [refactor as you go](http://www.codinghorror.com/blog/2009/02/paying-down-your-technical-debt.html). The code will never be perfect, and that isn't the goal. Instead, the goal is to manage the technical debt to keep it from becoming an impediment, because when it impedes progress and becomes a threat to the project, then it *is* a project management issue. | Fascinating discussion, and very relevant to me. I believe that technical debt is a PM's concern.
One could argue that a project is a coordinated effort to produce a specific outcome/change; if the project produces the outcome, the project is successful, and technical debt doesn't enter into the equation. But I think that is shortsighted; at a minimum, the PM is obliged during the closeout procedures to document lessons learned and update the corporate process assets. Technical debt should fall into that category. Beyond that, the PM has an ethical obligation to do the best for the company within the constraints, and leaving a company saddled with unknown, undocumented technical debt is unconscionable.
Alternatively we could consider that technical debit is a quality control problem. Technical debt is a aberration that falls within control limits, but if it can be eliminated, the quality (and presumably value) of the product rises.
Multiple ways to look at the problem, but each of them convinces me that although the PM can ignore technical debt, prudence dictates that the PM estimate, document and manage technical debt.
I think the key challenge is establishing the value of technical debt. I think that companies/industries/teams should establish reference values and refine as they go. Just as the PM is obliged to assess & estimate the impact of every proposed change on schedule/scope/quality, the PM should assess & estimate the impact of technical debt. I think that an interesting corrallary to @Jmort253's question is "Change proposals go to the CCB. Who is accountable for changes that are intrinsically outside the scope of the project?"
As I said, excellent, thought provoking question. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| **Technical Debt isn't a PM's Responsibility:**
-----------------------------------------------
As a project manager, the short answer is, you don't. This is really a job for the technical team, which includes functional managers and the actual developers working on the project. If you're doing project management correctly, then you should be getting all of your estimates from the developers themselves.
However, if it becomes a noticeable detriment to productivity, it may become a project management issue.
**Focus Primarily on Business Goals:**
--------------------------------------
However, here is where this can get tricky and why sometimes it is helpful for a project manager to have enough experience in the subject matter to know the difference between a good estimate and a bad estimate. New developers, fresh out of college and eager to apply their newfound knowledge, will sometimes be the first to suggest a complete rewrite to the database layer because it's a cluttered mess.
Sure, the job may have been to write a feature that lets the customer service team sort customer data by creation date, something that helps the team improve retention efforts, but this eager dev attempts to take the issue scope to another level. By prioritizing technical debt the wrong way, the actual feature being developed is removed from focus, and management is justified in stopping this in its tracks. If revenue isn't being generated from a development operation, then there's a problem with the balance.
**Pay Back Technical Debt One Piece at a Time:**
------------------------------------------------
As a developer, I've worked with some code that I've had a pretty strong opinion about. When I told my project manager about it, he said he didn't care. He didn't want to think about it, and that it was my job to include this in the estimates in a way that didn't conflict with business goals. I've been doing that ever since, and I manage my own technical debt while still keeping management happy with the progress. In many cases, it actually makes the development faster because the impediments that would normally slow me down are removed.
Ultimately, the solution to managing technical debt and balancing it with company initiatives is to break it up into manageable, bite-sized chunks. If the database layer needs a rewrite, start with the new feature. Add it in a manner that scales, and then next time a new feature is added fix a little bit more. You should only commit to paying back a small portion of technical debt so that it doesn't stand out as a red flag to management, similar to how you should only pay down enough of your debt to where you can still pay your rent and eat your meals. ;)
In short, the way to balance technical debt against business goals and initiatives is to [refactor as you go](http://www.codinghorror.com/blog/2009/02/paying-down-your-technical-debt.html). The code will never be perfect, and that isn't the goal. Instead, the goal is to manage the technical debt to keep it from becoming an impediment, because when it impedes progress and becomes a threat to the project, then it *is* a project management issue. | I know there's an answer for this and I mostly agree with @Lunivore and @jmort253 answers but I thought I would chime in on how I have seen and heard technical debt handled?
In our company we recently started trying to allocate dedicated week-long sprints that we focus on technical debt. Unfortunately this hasn't worked super well when there are certain features that go over the course of multiple sprints, in which case it's impossible to prioritize low-priority fixes vs features that need to ship.
Kind of building on above, I believe **it's important to show and communicate communicate how technical debt is affecting the team's velocity**. This naturally starts with being able to know what your team's velocity is, and then showing it is simply a matter of process.
Recently we have started costing out all issues with [story points](https://agilefaq.wordpress.com/2007/11/13/what-is-a-story-point/) (whether it be features and the small tasks associated with features, or just nitpicky bug fixes) everything is costed out with a certain value. After a period of time, our manager is now able to give a ballpark range of how much bandwidth each engineer has and how much time they can allocate to fixing certain bugs. When we first started this, it was naturally really bumpy because we would forget that there was more to a task so its generally better to overestimate than underestimate.
After some time though, we were able to give a good sense of what we can fit into the sprint and what we can't and we have been given dedicated time to fix bugs that makes sense (hey you have this feature but from what was costed out you seem to have time for some small bugs?). I think we are still working on a good rhythm and we have juggled between alternating people to fix bugs or just dedicating time for the entire team (especially useful if you have new devs) -- maybe I'll chime in again when we have narrowed that down but we have definitely seen an improvement in how fast we do things when given the time to fix the things that no one sees and it's nice that everyone can "see" it too now.
In regards to responsibility, I don't necessarily think it's the PM's responsibility? Our **engineering manager and tech lead drives managing technical debt** while our PM drives the projects and timeline of features. That being said, **it's important there is dedicated time for the PM and the manager to coordinate and set expectations**. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I'm going to pick on @jmort253's answer, because I disagree.
ROI initiatives aren't the only kinds of project, nor should they be. Chris Matts (the analyst behind BDD, Feature Injection and Real Options) found that 80% of one of his CIO's projects were concerned with protecting existing customer revenue, rather than trying to increase it - essentially, stopping their customers leaving for a competitor.
A lot of projects also simply provide *options* for the future. These are often very hard to price, but very, very expensive if they're not done.
Most technical initiatives are done for this reason; to provide the business with options to change in the future. Some of them have more direct business concerns which are more easily phrased, like increasing current system performance to cope with growing demand. Others may be relevant to different parts of the business - changing from Fortran to Python to attract better talent and make it easier to recruit - but in the long run, that's still about having options in the future.
**Technical Debt is, and should be, a PM's concern**
Chris Matts and Steve Freeman [came up with a lovely analogy](http://www.higherorderlogic.com/2010/07/bad-code-isnt-technical-debt-its-an-unhedged-call-option/). "It's not like a credit card. It's like an unhedged call option. It's like you've promised to sell all these chocolate Santas at Christmas, and then suddenly one year the price of chocolate is really high, and you have to sell the Santas anyway because you made that commitment, and now you're bust." As long as nobody makes the call, technical debt doesn't matter.
The problem is that every project has something new about it, or that project wouldn't be happening (see ["Waltzing with Bears"](http://rads.stackoverflow.com/amzn/click/0932633609)). So every project has changes that get made as discoveries happen as a result of feedback from the new thing (see [the complex domain in Cynefi](http://lizkeogh.com/2012/03/11/cynefin-for-devs/)n). And every project is therefore seriously at risk from being called.
(Every project is also difficult to estimate for this reason; you can't estimate something you've never done before.)
**The option to change is usually an unstated a business goal**
I worked with one company that had a single class of 10,000 lines that took Visual Studio 5 minutes to load. When the business found out what poor quality code had been produced, they said, "Why would you ever do that? We expected you to push back if we were making you do that!"
This unstated goal is also, usually, the *core goal* of most projects which are replacing legacy systems. The legacy systems have become too unwieldy, and can't be changed to meet new requirements and architectural demand, so a new system is created. If I had a shiny English pound for every time I've seen a replacement system team abandon the core goal in order to meet some arbitrary deadline, I wouldn't need to work again.
By calling out this unstated goal as an explicit one, everyone involved on the project can talk about it rather than assuming it's happening.
**Educate the business about the cost of technical debt**
Technical debt only happens in the face of time pressure (or as a result of bad habit or lack of skill, which are a different problem, solved by having time to learn how to do the job well... so, time pressure).
By keeping track of the growing cost of the debt and making the business aware of it, you can help to show them the value of the options they're losing. This could include things like your best developers leaving, and the cost of re-hiring; how much extra time the devs reckon it took to create a new feature as a result of technical debt; how much more effective the team is when they're given the chance to take pride in their work instead of bowing to business pressure.
Also educate them about [the alignment trap](http://www.ebizq.net/blogs/agile_enterprise/2009/11/dont-fall-in-the-alignment-trap.php). "Companies in which IT was highly aligned with business but not effective were considerably worse off than companies in which IT was less aligned and merely kept the systems running."
**Pay back technical debt one piece at a time**
In this place I agree with @jmort253. It's even better if you can avoid falling into debt in the first place, but usually there are different skill sets on a team, people learning to code well, etc. - so having the ability to refactor as you go and help educate other developers is more important than getting it right up-front.
If the team feel pressured to churn out new features, though, they'll very quickly abandon the technical debt. It can't be seen or measured easily, and as such is usually the first victim of any pressure.
A PM's responsibility in this situation is to push back, educate, and help the business cut scope instead. | I know there's an answer for this and I mostly agree with @Lunivore and @jmort253 answers but I thought I would chime in on how I have seen and heard technical debt handled?
In our company we recently started trying to allocate dedicated week-long sprints that we focus on technical debt. Unfortunately this hasn't worked super well when there are certain features that go over the course of multiple sprints, in which case it's impossible to prioritize low-priority fixes vs features that need to ship.
Kind of building on above, I believe **it's important to show and communicate communicate how technical debt is affecting the team's velocity**. This naturally starts with being able to know what your team's velocity is, and then showing it is simply a matter of process.
Recently we have started costing out all issues with [story points](https://agilefaq.wordpress.com/2007/11/13/what-is-a-story-point/) (whether it be features and the small tasks associated with features, or just nitpicky bug fixes) everything is costed out with a certain value. After a period of time, our manager is now able to give a ballpark range of how much bandwidth each engineer has and how much time they can allocate to fixing certain bugs. When we first started this, it was naturally really bumpy because we would forget that there was more to a task so its generally better to overestimate than underestimate.
After some time though, we were able to give a good sense of what we can fit into the sprint and what we can't and we have been given dedicated time to fix bugs that makes sense (hey you have this feature but from what was costed out you seem to have time for some small bugs?). I think we are still working on a good rhythm and we have juggled between alternating people to fix bugs or just dedicating time for the entire team (especially useful if you have new devs) -- maybe I'll chime in again when we have narrowed that down but we have definitely seen an improvement in how fast we do things when given the time to fix the things that no one sees and it's nice that everyone can "see" it too now.
In regards to responsibility, I don't necessarily think it's the PM's responsibility? Our **engineering manager and tech lead drives managing technical debt** while our PM drives the projects and timeline of features. That being said, **it's important there is dedicated time for the PM and the manager to coordinate and set expectations**. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I tend to disagree with the basic assumption that technical initiatives are not business initiatives. They may be different from rolling out a new product or an advertising campaign, but:
* They have a business benefits... be it regulatory compliance, improving efficiencies, making the customer experience better, etc
* They have business costs... training, systems development, etc
* They have business risks... what if stakeholders don't like the changes, what if their costs are more than expected, what if their benefits are less, etc
Where technical initiatives tend to have problems is that they aren't easily understood by decision makers who tend to come from the marketing/sales/"business" side of the house. Basically they aren't as "sexy" as a new marketing campaign or partnership.
The best approach to getting a better focus on "technical debt" is to do a thorough business case for addressing it. How much will addressing the debt cost in time, money and effort? What is the payback period given the expected labor savings, increased sales, increased customer retention, increased market share, etc once the initiative is implemented? How does this compare to the costs and benefits of maintaining the status quo? Getting this information together will take some time and effort, but if it is done well it should be obvious to you whether or not the technical debt needs to be paid *now* or if payment can be deferred. | I would start by **Identifying the ROI that the technical debt delivers** and discussing this with the business. If you can describe both value work and what John Seddon calls 'Failure Demand' in the same terms and using the same metrics then you can agree how to split your capacity across them.
**Example - Architectural Refactoring**
We have a piece of configuration information which is baked into an app (I know, I know...). This config can go unchanged for weeks and then suddenly need changing.
If the config doesn't get changed then ads stop appearing in an application and we stop making revenue from it.
The quick and dirty solution is to change the config in the code and redeploy. This is repetitive and error prone and ultimately not sustainable.
The sustainable solution would be to factor our the config from the code and provide a mechanism for changing it independently from the code. This will take longer the first time round but will then make future config changes much quicker and less error prone.
Guess which one we have done twice already? That's right the quick and dirty. This is because the ROI on the feature is immediately visible or rather, the Cost of Delay were the work not to be done is very high.
The sell we have to make to the business is, let us spend time refactoring this to address the technical debt. That way, next time we need to change the config it will be quicker than it currently is, so quicker ROI in the future, but we will need to take some capacity away now to address the technical debt. It is deferred ROI.
**Example - Architectural Refactoring as complexity increases**
Sometimes it is hard to describe the technical debt to the business, to them it is just an implementation detail or something you should not have accrued in the first place.
For example, as something grows in complexity it requires refactoring. In this case I do one of two things.
I either cover the cost of the refactoring in the delivery of the feature which has required us to go back and look at the code in question. I always call this out to the business either to tell them that the feature will take longer to deliver than similar features have in the past, because we have reached a point where we need to refactor.
Again I describe this to them as deferred ROI. There will be a greater upfront cost but by doing the refactoring now, future work in this area will be cheaper.
The other approach I take is to treat the development team as a customer of itself and reserve a percentage of capacity, agreed with the business, in each iteration for reduction of technical debt.
**Example - Platform Upgrade**
For the example you give of upgrading to a newer platform I would again look at how you can describe this in terms of ROI, or impact on ROI.
If the existing platform is no longer supported by the vendor then the business is exposed to the risk of defects discovered in that version of the platform not getting fixed and so impacting on business functionality which depends on it.
This impact will be an increase in failure demand, that is, customers will be less able to get value out of what you as a business provide as problems with the underlying platform are getting in the way. This can be articulated as lost revenue, or potential lost revenue so the ROI is to upgrade the underlying platform.
Prioritising such an upgrade can again be done by looking at the Cost of Delay. If you were not to upgrade the platform would there be any impact on your existing products and services? Would it prevent you from launching new ones?
If problems in the existing platform are generating failure demand now then the Cost of Delay is high and you have a compelling ROI based argument for doing the work sooner rather than later.
If you are currently unaffected by problems in the existing platform but need to upgrade in order to add new functionality then the ROI of the new functionality will determine the ROI of upgrading the platform. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| I would start by **Identifying the ROI that the technical debt delivers** and discussing this with the business. If you can describe both value work and what John Seddon calls 'Failure Demand' in the same terms and using the same metrics then you can agree how to split your capacity across them.
**Example - Architectural Refactoring**
We have a piece of configuration information which is baked into an app (I know, I know...). This config can go unchanged for weeks and then suddenly need changing.
If the config doesn't get changed then ads stop appearing in an application and we stop making revenue from it.
The quick and dirty solution is to change the config in the code and redeploy. This is repetitive and error prone and ultimately not sustainable.
The sustainable solution would be to factor our the config from the code and provide a mechanism for changing it independently from the code. This will take longer the first time round but will then make future config changes much quicker and less error prone.
Guess which one we have done twice already? That's right the quick and dirty. This is because the ROI on the feature is immediately visible or rather, the Cost of Delay were the work not to be done is very high.
The sell we have to make to the business is, let us spend time refactoring this to address the technical debt. That way, next time we need to change the config it will be quicker than it currently is, so quicker ROI in the future, but we will need to take some capacity away now to address the technical debt. It is deferred ROI.
**Example - Architectural Refactoring as complexity increases**
Sometimes it is hard to describe the technical debt to the business, to them it is just an implementation detail or something you should not have accrued in the first place.
For example, as something grows in complexity it requires refactoring. In this case I do one of two things.
I either cover the cost of the refactoring in the delivery of the feature which has required us to go back and look at the code in question. I always call this out to the business either to tell them that the feature will take longer to deliver than similar features have in the past, because we have reached a point where we need to refactor.
Again I describe this to them as deferred ROI. There will be a greater upfront cost but by doing the refactoring now, future work in this area will be cheaper.
The other approach I take is to treat the development team as a customer of itself and reserve a percentage of capacity, agreed with the business, in each iteration for reduction of technical debt.
**Example - Platform Upgrade**
For the example you give of upgrading to a newer platform I would again look at how you can describe this in terms of ROI, or impact on ROI.
If the existing platform is no longer supported by the vendor then the business is exposed to the risk of defects discovered in that version of the platform not getting fixed and so impacting on business functionality which depends on it.
This impact will be an increase in failure demand, that is, customers will be less able to get value out of what you as a business provide as problems with the underlying platform are getting in the way. This can be articulated as lost revenue, or potential lost revenue so the ROI is to upgrade the underlying platform.
Prioritising such an upgrade can again be done by looking at the Cost of Delay. If you were not to upgrade the platform would there be any impact on your existing products and services? Would it prevent you from launching new ones?
If problems in the existing platform are generating failure demand now then the Cost of Delay is high and you have a compelling ROI based argument for doing the work sooner rather than later.
If you are currently unaffected by problems in the existing platform but need to upgrade in order to add new functionality then the ROI of the new functionality will determine the ROI of upgrading the platform. | I know there's an answer for this and I mostly agree with @Lunivore and @jmort253 answers but I thought I would chime in on how I have seen and heard technical debt handled?
In our company we recently started trying to allocate dedicated week-long sprints that we focus on technical debt. Unfortunately this hasn't worked super well when there are certain features that go over the course of multiple sprints, in which case it's impossible to prioritize low-priority fixes vs features that need to ship.
Kind of building on above, I believe **it's important to show and communicate communicate how technical debt is affecting the team's velocity**. This naturally starts with being able to know what your team's velocity is, and then showing it is simply a matter of process.
Recently we have started costing out all issues with [story points](https://agilefaq.wordpress.com/2007/11/13/what-is-a-story-point/) (whether it be features and the small tasks associated with features, or just nitpicky bug fixes) everything is costed out with a certain value. After a period of time, our manager is now able to give a ballpark range of how much bandwidth each engineer has and how much time they can allocate to fixing certain bugs. When we first started this, it was naturally really bumpy because we would forget that there was more to a task so its generally better to overestimate than underestimate.
After some time though, we were able to give a good sense of what we can fit into the sprint and what we can't and we have been given dedicated time to fix bugs that makes sense (hey you have this feature but from what was costed out you seem to have time for some small bugs?). I think we are still working on a good rhythm and we have juggled between alternating people to fix bugs or just dedicating time for the entire team (especially useful if you have new devs) -- maybe I'll chime in again when we have narrowed that down but we have definitely seen an improvement in how fast we do things when given the time to fix the things that no one sees and it's nice that everyone can "see" it too now.
In regards to responsibility, I don't necessarily think it's the PM's responsibility? Our **engineering manager and tech lead drives managing technical debt** while our PM drives the projects and timeline of features. That being said, **it's important there is dedicated time for the PM and the manager to coordinate and set expectations**. |
7,954 | In real world, business initiatives always take higher priority as there are associated ROIs and deliver something tangible to the users. But there are technical initiatives and projects that need to be done to keep up with the different versions of software, upgrading to a newer platforms, architecture re-factoring etc.,
1. How can we plan, prioritize and manage such competing initiatives?
2. Is there a model to quantify technical debt and its impact to the business? | 2012/11/01 | [
"https://pm.stackexchange.com/questions/7954",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4731/"
]
| **Technical Debt isn't a PM's Responsibility:**
-----------------------------------------------
As a project manager, the short answer is, you don't. This is really a job for the technical team, which includes functional managers and the actual developers working on the project. If you're doing project management correctly, then you should be getting all of your estimates from the developers themselves.
However, if it becomes a noticeable detriment to productivity, it may become a project management issue.
**Focus Primarily on Business Goals:**
--------------------------------------
However, here is where this can get tricky and why sometimes it is helpful for a project manager to have enough experience in the subject matter to know the difference between a good estimate and a bad estimate. New developers, fresh out of college and eager to apply their newfound knowledge, will sometimes be the first to suggest a complete rewrite to the database layer because it's a cluttered mess.
Sure, the job may have been to write a feature that lets the customer service team sort customer data by creation date, something that helps the team improve retention efforts, but this eager dev attempts to take the issue scope to another level. By prioritizing technical debt the wrong way, the actual feature being developed is removed from focus, and management is justified in stopping this in its tracks. If revenue isn't being generated from a development operation, then there's a problem with the balance.
**Pay Back Technical Debt One Piece at a Time:**
------------------------------------------------
As a developer, I've worked with some code that I've had a pretty strong opinion about. When I told my project manager about it, he said he didn't care. He didn't want to think about it, and that it was my job to include this in the estimates in a way that didn't conflict with business goals. I've been doing that ever since, and I manage my own technical debt while still keeping management happy with the progress. In many cases, it actually makes the development faster because the impediments that would normally slow me down are removed.
Ultimately, the solution to managing technical debt and balancing it with company initiatives is to break it up into manageable, bite-sized chunks. If the database layer needs a rewrite, start with the new feature. Add it in a manner that scales, and then next time a new feature is added fix a little bit more. You should only commit to paying back a small portion of technical debt so that it doesn't stand out as a red flag to management, similar to how you should only pay down enough of your debt to where you can still pay your rent and eat your meals. ;)
In short, the way to balance technical debt against business goals and initiatives is to [refactor as you go](http://www.codinghorror.com/blog/2009/02/paying-down-your-technical-debt.html). The code will never be perfect, and that isn't the goal. Instead, the goal is to manage the technical debt to keep it from becoming an impediment, because when it impedes progress and becomes a threat to the project, then it *is* a project management issue. | I would start by **Identifying the ROI that the technical debt delivers** and discussing this with the business. If you can describe both value work and what John Seddon calls 'Failure Demand' in the same terms and using the same metrics then you can agree how to split your capacity across them.
**Example - Architectural Refactoring**
We have a piece of configuration information which is baked into an app (I know, I know...). This config can go unchanged for weeks and then suddenly need changing.
If the config doesn't get changed then ads stop appearing in an application and we stop making revenue from it.
The quick and dirty solution is to change the config in the code and redeploy. This is repetitive and error prone and ultimately not sustainable.
The sustainable solution would be to factor our the config from the code and provide a mechanism for changing it independently from the code. This will take longer the first time round but will then make future config changes much quicker and less error prone.
Guess which one we have done twice already? That's right the quick and dirty. This is because the ROI on the feature is immediately visible or rather, the Cost of Delay were the work not to be done is very high.
The sell we have to make to the business is, let us spend time refactoring this to address the technical debt. That way, next time we need to change the config it will be quicker than it currently is, so quicker ROI in the future, but we will need to take some capacity away now to address the technical debt. It is deferred ROI.
**Example - Architectural Refactoring as complexity increases**
Sometimes it is hard to describe the technical debt to the business, to them it is just an implementation detail or something you should not have accrued in the first place.
For example, as something grows in complexity it requires refactoring. In this case I do one of two things.
I either cover the cost of the refactoring in the delivery of the feature which has required us to go back and look at the code in question. I always call this out to the business either to tell them that the feature will take longer to deliver than similar features have in the past, because we have reached a point where we need to refactor.
Again I describe this to them as deferred ROI. There will be a greater upfront cost but by doing the refactoring now, future work in this area will be cheaper.
The other approach I take is to treat the development team as a customer of itself and reserve a percentage of capacity, agreed with the business, in each iteration for reduction of technical debt.
**Example - Platform Upgrade**
For the example you give of upgrading to a newer platform I would again look at how you can describe this in terms of ROI, or impact on ROI.
If the existing platform is no longer supported by the vendor then the business is exposed to the risk of defects discovered in that version of the platform not getting fixed and so impacting on business functionality which depends on it.
This impact will be an increase in failure demand, that is, customers will be less able to get value out of what you as a business provide as problems with the underlying platform are getting in the way. This can be articulated as lost revenue, or potential lost revenue so the ROI is to upgrade the underlying platform.
Prioritising such an upgrade can again be done by looking at the Cost of Delay. If you were not to upgrade the platform would there be any impact on your existing products and services? Would it prevent you from launching new ones?
If problems in the existing platform are generating failure demand now then the Cost of Delay is high and you have a compelling ROI based argument for doing the work sooner rather than later.
If you are currently unaffected by problems in the existing platform but need to upgrade in order to add new functionality then the ROI of the new functionality will determine the ROI of upgrading the platform. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| If either of these throw
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
Then the object you were creating will not exist.
If an exception is thrown in the constructor of an object, then all fully created members are destructed (using the their destructor) and memory for the object is returned to the system. Thus any members that are not fully constructed at the throw point will not be destroyed (as they have not been created).
* If m\_str() throws in the initializer list then the object will never exist.
* If ifstream throws in the body then m\_str is destroyed and the object will never exist.
>
> Should I wrap the code in catch(exception &)? And if I do that, does string and ifstream guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
>
>
>
Even if you catch an exception (outside the object) there is no object to work on as it never existed (the object only starts its lifespan after the constructor completes).
In the above you are guaranteed there are no leaks or open resources.
>
> Also, if my class throws myexception, that is derived from exception, catch(exception &) seems to let it through. So that leaves me with catch(...) which IIRC catches access violation?.? Is there another way?
>
>
>
If your exception is derived from std::exception then `catch(std::exception&)` will work. If it is not working then you are doing something wrong (but we need more detail (like the code that throws and the code that catches, an English description is not adequate)).
>
> Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
>
>
>
Probably the best option and as a general rule not bad advice.
>
> And what if the code above would have been called not from constructor, but from regular a function void foo(), which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
>
>
>
You should only catch exceptions if you can do something about it. Usually this is nothing so don;t catch them let the application quit normally (via the exception unwinding the stack).
>
> Where is the authoritative source where I could clear all my doubts and questions on this topic?
>
>
>
You're question are so varied that that is hard.
I could recommend ["Exceptional C++" by Herb Sutter](http://www.gotw.ca/publications/xc++.htm).
>
> So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer...
>
>
>
You are wrong there. Exceptions are much easier. You just seem to be over-thinking it and getting confused. That is not to say that error codes do not have their place.
If something goes wrong `and you can not fix it locally` then throw an exception. All the classes in the standard are designed with exception in mind and will behave correctly. So that just leaves your classes.
### Rules of thumb: (for your objects)
* Make sure your classes clean themselves up in the destructor
* If your object contains resources make sure the "rule of 3 is obeyed"
* Never have more than one resource per object.
Note: You can have multiple things like std::string or std::ifstream as they are the ones controlling the resource (they each control one resource so your class is not controlling the resource). A resource (in this context) is something that you must manually create/destroy.
That's it, the rest auto-magically works. | AFAIK whether or not (and more importantly, which) exceptions are thrown is mostly left to the implementation. I don't see any point in attempting to catch those - I mean, what are you gonna do if this fails? Is there any reasonable way to recover from an exception being thrown there?
Keep in mind that no exception is thrown if, for example, a file can't be opened - that would simply lead to the stream being set to a fail state. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| The only authoritative reference on how the standard library works, including under which conditions it is allowed to throw which exception types, is the C++ Language Standard. Years ago it was available in electronic form for a reasonable price, but unfortunately this doesn't appear to be the case anymore. You might consider searching the [Standard Committee site](http://www.open-std.org/jtc1/sc22/wg21/) for drafts, but there will obviously be differences with the published standard.
Note also that a new edition of the standard has just been publish and it will take some time before vendors implement the new features with reasonable completeness. | AFAIK whether or not (and more importantly, which) exceptions are thrown is mostly left to the implementation. I don't see any point in attempting to catch those - I mean, what are you gonna do if this fails? Is there any reasonable way to recover from an exception being thrown there?
Keep in mind that no exception is thrown if, for example, a file can't be opened - that would simply lead to the stream being set to a fail state. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| Throwing exceptions in constructors *is* a good idea, since you have no other means of reporting failure.
*I tend to prefer C++ exceptions to error codes, even when they are considered "control flow", because I don't have to add checks everywhere. But this is a debatable matter of taste. For constructors, you have no choice however.*
As soon as a constructor throws an exception, all the subobjects which were initialized get destroyed, and if the object was constructed via `operator new`, the corresponding `operator delete` gets called.
Note that when a constructor throws, the object cannot be used:
```
my_class a; // If this throws, everything past this line is not accessible.
// Therefore, you cannot use a.
```
or
```
my_class* b;
try
{
b = new my_class; // If this throws, ...
}
catch (...)
{
// b has undefined state here (but no memory is leaked)
}
```
So if you only use proper RAII objects, you are safe and have nothing to do except letting the exception propagate. If however you manually retrieve a disposable resource, then you may have to clean it up and rethrow the exception:
```
template <typename T>
struct my_vector
{
// This is why it is not advisable to roll your own vector.
my_vector(size_t n, const T& x)
{
begin = static_cast<T*>(custom_allocator(n * sizeof(T)));
end = begin + n;
size_t k = 0;
try
{
// This can throw...
for (; k != n; k++) new(begin + k) T(x);
}
catch (...)
{
// ... so destroy everything and bail out
while (--k) (begin + k)->~T();
custom_deallocator(begin);
throw;
}
}
private:
T* begin;
T* end;
};
```
but this should be quite rare if you use proper RAII objects (a quick `grep` from my current codebase shows hundreds of `throw`, but only two `catch`).
The exception guarantees from the standard library can be found in the ISO standard document (you have to pay a small fee for it).
Also, any good C++ book discusses exception safety at great length, the point being that usually you have nothing special to do. For instance, in your example, everything will be disposed properly, since `ifstream` close the file in its destructor. | AFAIK whether or not (and more importantly, which) exceptions are thrown is mostly left to the implementation. I don't see any point in attempting to catch those - I mean, what are you gonna do if this fails? Is there any reasonable way to recover from an exception being thrown there?
Keep in mind that no exception is thrown if, for example, a file can't be opened - that would simply lead to the stream being set to a fail state. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| Every function has a precondition and a postcondition. The correct time to throw an exception is when the postconditions cannot be satisfied. There is no other correct time.
There are two special cases.
* *The postcondition for a constructor is the existence of a valid object*, therefore throwing is the ***only*** reasonable way to report an error. If you have something like a `Foo::is_ok()` test then what you have is a valid object which represents an invalid state.
* *The postcondition for a destructor is the nonexistence of an object*, therefore throwing is ***never*** a reasonable way to report an error. If you have something tricky to do at the end of an object's life, do it as a separate `Foo::commit()` member function call.
Beyond this you have options, and it's a matter of taste.
For example
* `std::vector::operator[]` does not check preconditions and is `noexcept(true)`, but
* `std::vector::at()` does check, and throws.
The choice is whether or not you assume your preconditions are valid. In the first case you are using design-by-contract. In the second case, *given* that you have detected that they are not, you *know* the postconditions *cannot* be valid and therefore *should* throw; in the first case you *assume* they are and, *given* that, the postconditions *must* be valid and therefore you *never* need to.
GOTW covers a lot of the dark corners of exceptions and demonstrates nicely [why things are what they are](http://www.gotw.ca/gotw/066.htm). | AFAIK whether or not (and more importantly, which) exceptions are thrown is mostly left to the implementation. I don't see any point in attempting to catch those - I mean, what are you gonna do if this fails? Is there any reasonable way to recover from an exception being thrown there?
Keep in mind that no exception is thrown if, for example, a file can't be opened - that would simply lead to the stream being set to a fail state. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| If either of these throw
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
Then the object you were creating will not exist.
If an exception is thrown in the constructor of an object, then all fully created members are destructed (using the their destructor) and memory for the object is returned to the system. Thus any members that are not fully constructed at the throw point will not be destroyed (as they have not been created).
* If m\_str() throws in the initializer list then the object will never exist.
* If ifstream throws in the body then m\_str is destroyed and the object will never exist.
>
> Should I wrap the code in catch(exception &)? And if I do that, does string and ifstream guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
>
>
>
Even if you catch an exception (outside the object) there is no object to work on as it never existed (the object only starts its lifespan after the constructor completes).
In the above you are guaranteed there are no leaks or open resources.
>
> Also, if my class throws myexception, that is derived from exception, catch(exception &) seems to let it through. So that leaves me with catch(...) which IIRC catches access violation?.? Is there another way?
>
>
>
If your exception is derived from std::exception then `catch(std::exception&)` will work. If it is not working then you are doing something wrong (but we need more detail (like the code that throws and the code that catches, an English description is not adequate)).
>
> Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
>
>
>
Probably the best option and as a general rule not bad advice.
>
> And what if the code above would have been called not from constructor, but from regular a function void foo(), which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
>
>
>
You should only catch exceptions if you can do something about it. Usually this is nothing so don;t catch them let the application quit normally (via the exception unwinding the stack).
>
> Where is the authoritative source where I could clear all my doubts and questions on this topic?
>
>
>
You're question are so varied that that is hard.
I could recommend ["Exceptional C++" by Herb Sutter](http://www.gotw.ca/publications/xc++.htm).
>
> So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer...
>
>
>
You are wrong there. Exceptions are much easier. You just seem to be over-thinking it and getting confused. That is not to say that error codes do not have their place.
If something goes wrong `and you can not fix it locally` then throw an exception. All the classes in the standard are designed with exception in mind and will behave correctly. So that just leaves your classes.
### Rules of thumb: (for your objects)
* Make sure your classes clean themselves up in the destructor
* If your object contains resources make sure the "rule of 3 is obeyed"
* Never have more than one resource per object.
Note: You can have multiple things like std::string or std::ifstream as they are the ones controlling the resource (they each control one resource so your class is not controlling the resource). A resource (in this context) is something that you must manually create/destroy.
That's it, the rest auto-magically works. | The only authoritative reference on how the standard library works, including under which conditions it is allowed to throw which exception types, is the C++ Language Standard. Years ago it was available in electronic form for a reasonable price, but unfortunately this doesn't appear to be the case anymore. You might consider searching the [Standard Committee site](http://www.open-std.org/jtc1/sc22/wg21/) for drafts, but there will obviously be differences with the published standard.
Note also that a new edition of the standard has just been publish and it will take some time before vendors implement the new features with reasonable completeness. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| If either of these throw
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
Then the object you were creating will not exist.
If an exception is thrown in the constructor of an object, then all fully created members are destructed (using the their destructor) and memory for the object is returned to the system. Thus any members that are not fully constructed at the throw point will not be destroyed (as they have not been created).
* If m\_str() throws in the initializer list then the object will never exist.
* If ifstream throws in the body then m\_str is destroyed and the object will never exist.
>
> Should I wrap the code in catch(exception &)? And if I do that, does string and ifstream guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
>
>
>
Even if you catch an exception (outside the object) there is no object to work on as it never existed (the object only starts its lifespan after the constructor completes).
In the above you are guaranteed there are no leaks or open resources.
>
> Also, if my class throws myexception, that is derived from exception, catch(exception &) seems to let it through. So that leaves me with catch(...) which IIRC catches access violation?.? Is there another way?
>
>
>
If your exception is derived from std::exception then `catch(std::exception&)` will work. If it is not working then you are doing something wrong (but we need more detail (like the code that throws and the code that catches, an English description is not adequate)).
>
> Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
>
>
>
Probably the best option and as a general rule not bad advice.
>
> And what if the code above would have been called not from constructor, but from regular a function void foo(), which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
>
>
>
You should only catch exceptions if you can do something about it. Usually this is nothing so don;t catch them let the application quit normally (via the exception unwinding the stack).
>
> Where is the authoritative source where I could clear all my doubts and questions on this topic?
>
>
>
You're question are so varied that that is hard.
I could recommend ["Exceptional C++" by Herb Sutter](http://www.gotw.ca/publications/xc++.htm).
>
> So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer...
>
>
>
You are wrong there. Exceptions are much easier. You just seem to be over-thinking it and getting confused. That is not to say that error codes do not have their place.
If something goes wrong `and you can not fix it locally` then throw an exception. All the classes in the standard are designed with exception in mind and will behave correctly. So that just leaves your classes.
### Rules of thumb: (for your objects)
* Make sure your classes clean themselves up in the destructor
* If your object contains resources make sure the "rule of 3 is obeyed"
* Never have more than one resource per object.
Note: You can have multiple things like std::string or std::ifstream as they are the ones controlling the resource (they each control one resource so your class is not controlling the resource). A resource (in this context) is something that you must manually create/destroy.
That's it, the rest auto-magically works. | Throwing exceptions in constructors *is* a good idea, since you have no other means of reporting failure.
*I tend to prefer C++ exceptions to error codes, even when they are considered "control flow", because I don't have to add checks everywhere. But this is a debatable matter of taste. For constructors, you have no choice however.*
As soon as a constructor throws an exception, all the subobjects which were initialized get destroyed, and if the object was constructed via `operator new`, the corresponding `operator delete` gets called.
Note that when a constructor throws, the object cannot be used:
```
my_class a; // If this throws, everything past this line is not accessible.
// Therefore, you cannot use a.
```
or
```
my_class* b;
try
{
b = new my_class; // If this throws, ...
}
catch (...)
{
// b has undefined state here (but no memory is leaked)
}
```
So if you only use proper RAII objects, you are safe and have nothing to do except letting the exception propagate. If however you manually retrieve a disposable resource, then you may have to clean it up and rethrow the exception:
```
template <typename T>
struct my_vector
{
// This is why it is not advisable to roll your own vector.
my_vector(size_t n, const T& x)
{
begin = static_cast<T*>(custom_allocator(n * sizeof(T)));
end = begin + n;
size_t k = 0;
try
{
// This can throw...
for (; k != n; k++) new(begin + k) T(x);
}
catch (...)
{
// ... so destroy everything and bail out
while (--k) (begin + k)->~T();
custom_deallocator(begin);
throw;
}
}
private:
T* begin;
T* end;
};
```
but this should be quite rare if you use proper RAII objects (a quick `grep` from my current codebase shows hundreds of `throw`, but only two `catch`).
The exception guarantees from the standard library can be found in the ISO standard document (you have to pay a small fee for it).
Also, any good C++ book discusses exception safety at great length, the point being that usually you have nothing special to do. For instance, in your example, everything will be disposed properly, since `ifstream` close the file in its destructor. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| If either of these throw
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
Then the object you were creating will not exist.
If an exception is thrown in the constructor of an object, then all fully created members are destructed (using the their destructor) and memory for the object is returned to the system. Thus any members that are not fully constructed at the throw point will not be destroyed (as they have not been created).
* If m\_str() throws in the initializer list then the object will never exist.
* If ifstream throws in the body then m\_str is destroyed and the object will never exist.
>
> Should I wrap the code in catch(exception &)? And if I do that, does string and ifstream guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
>
>
>
Even if you catch an exception (outside the object) there is no object to work on as it never existed (the object only starts its lifespan after the constructor completes).
In the above you are guaranteed there are no leaks or open resources.
>
> Also, if my class throws myexception, that is derived from exception, catch(exception &) seems to let it through. So that leaves me with catch(...) which IIRC catches access violation?.? Is there another way?
>
>
>
If your exception is derived from std::exception then `catch(std::exception&)` will work. If it is not working then you are doing something wrong (but we need more detail (like the code that throws and the code that catches, an English description is not adequate)).
>
> Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
>
>
>
Probably the best option and as a general rule not bad advice.
>
> And what if the code above would have been called not from constructor, but from regular a function void foo(), which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
>
>
>
You should only catch exceptions if you can do something about it. Usually this is nothing so don;t catch them let the application quit normally (via the exception unwinding the stack).
>
> Where is the authoritative source where I could clear all my doubts and questions on this topic?
>
>
>
You're question are so varied that that is hard.
I could recommend ["Exceptional C++" by Herb Sutter](http://www.gotw.ca/publications/xc++.htm).
>
> So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer...
>
>
>
You are wrong there. Exceptions are much easier. You just seem to be over-thinking it and getting confused. That is not to say that error codes do not have their place.
If something goes wrong `and you can not fix it locally` then throw an exception. All the classes in the standard are designed with exception in mind and will behave correctly. So that just leaves your classes.
### Rules of thumb: (for your objects)
* Make sure your classes clean themselves up in the destructor
* If your object contains resources make sure the "rule of 3 is obeyed"
* Never have more than one resource per object.
Note: You can have multiple things like std::string or std::ifstream as they are the ones controlling the resource (they each control one resource so your class is not controlling the resource). A resource (in this context) is something that you must manually create/destroy.
That's it, the rest auto-magically works. | Every function has a precondition and a postcondition. The correct time to throw an exception is when the postconditions cannot be satisfied. There is no other correct time.
There are two special cases.
* *The postcondition for a constructor is the existence of a valid object*, therefore throwing is the ***only*** reasonable way to report an error. If you have something like a `Foo::is_ok()` test then what you have is a valid object which represents an invalid state.
* *The postcondition for a destructor is the nonexistence of an object*, therefore throwing is ***never*** a reasonable way to report an error. If you have something tricky to do at the end of an object's life, do it as a separate `Foo::commit()` member function call.
Beyond this you have options, and it's a matter of taste.
For example
* `std::vector::operator[]` does not check preconditions and is `noexcept(true)`, but
* `std::vector::at()` does check, and throws.
The choice is whether or not you assume your preconditions are valid. In the first case you are using design-by-contract. In the second case, *given* that you have detected that they are not, you *know* the postconditions *cannot* be valid and therefore *should* throw; in the first case you *assume* they are and, *given* that, the postconditions *must* be valid and therefore you *never* need to.
GOTW covers a lot of the dark corners of exceptions and demonstrates nicely [why things are what they are](http://www.gotw.ca/gotw/066.htm). |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| Every function has a precondition and a postcondition. The correct time to throw an exception is when the postconditions cannot be satisfied. There is no other correct time.
There are two special cases.
* *The postcondition for a constructor is the existence of a valid object*, therefore throwing is the ***only*** reasonable way to report an error. If you have something like a `Foo::is_ok()` test then what you have is a valid object which represents an invalid state.
* *The postcondition for a destructor is the nonexistence of an object*, therefore throwing is ***never*** a reasonable way to report an error. If you have something tricky to do at the end of an object's life, do it as a separate `Foo::commit()` member function call.
Beyond this you have options, and it's a matter of taste.
For example
* `std::vector::operator[]` does not check preconditions and is `noexcept(true)`, but
* `std::vector::at()` does check, and throws.
The choice is whether or not you assume your preconditions are valid. In the first case you are using design-by-contract. In the second case, *given* that you have detected that they are not, you *know* the postconditions *cannot* be valid and therefore *should* throw; in the first case you *assume* they are and, *given* that, the postconditions *must* be valid and therefore you *never* need to.
GOTW covers a lot of the dark corners of exceptions and demonstrates nicely [why things are what they are](http://www.gotw.ca/gotw/066.htm). | The only authoritative reference on how the standard library works, including under which conditions it is allowed to throw which exception types, is the C++ Language Standard. Years ago it was available in electronic form for a reasonable price, but unfortunately this doesn't appear to be the case anymore. You might consider searching the [Standard Committee site](http://www.open-std.org/jtc1/sc22/wg21/) for drafts, but there will obviously be differences with the published standard.
Note also that a new edition of the standard has just been publish and it will take some time before vendors implement the new features with reasonable completeness. |
7,403,227 | I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
```
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
```
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
```
{
...
X myInstanceOfClassX;
...
}
```
Should I wrap the code in `catch(exception &)`? And if I do that, does `string` and `ifstream` guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws `myexception`, that is derived from exception, `catch(exception &)` seems to let it through. So that leaves me with `catch(...)` which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function `void foo()`, which exceptions should I catch? outofmemory\_something, filenotfound\_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer... | 2011/09/13 | [
"https://Stackoverflow.com/questions/7403227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459930/"
]
| Every function has a precondition and a postcondition. The correct time to throw an exception is when the postconditions cannot be satisfied. There is no other correct time.
There are two special cases.
* *The postcondition for a constructor is the existence of a valid object*, therefore throwing is the ***only*** reasonable way to report an error. If you have something like a `Foo::is_ok()` test then what you have is a valid object which represents an invalid state.
* *The postcondition for a destructor is the nonexistence of an object*, therefore throwing is ***never*** a reasonable way to report an error. If you have something tricky to do at the end of an object's life, do it as a separate `Foo::commit()` member function call.
Beyond this you have options, and it's a matter of taste.
For example
* `std::vector::operator[]` does not check preconditions and is `noexcept(true)`, but
* `std::vector::at()` does check, and throws.
The choice is whether or not you assume your preconditions are valid. In the first case you are using design-by-contract. In the second case, *given* that you have detected that they are not, you *know* the postconditions *cannot* be valid and therefore *should* throw; in the first case you *assume* they are and, *given* that, the postconditions *must* be valid and therefore you *never* need to.
GOTW covers a lot of the dark corners of exceptions and demonstrates nicely [why things are what they are](http://www.gotw.ca/gotw/066.htm). | Throwing exceptions in constructors *is* a good idea, since you have no other means of reporting failure.
*I tend to prefer C++ exceptions to error codes, even when they are considered "control flow", because I don't have to add checks everywhere. But this is a debatable matter of taste. For constructors, you have no choice however.*
As soon as a constructor throws an exception, all the subobjects which were initialized get destroyed, and if the object was constructed via `operator new`, the corresponding `operator delete` gets called.
Note that when a constructor throws, the object cannot be used:
```
my_class a; // If this throws, everything past this line is not accessible.
// Therefore, you cannot use a.
```
or
```
my_class* b;
try
{
b = new my_class; // If this throws, ...
}
catch (...)
{
// b has undefined state here (but no memory is leaked)
}
```
So if you only use proper RAII objects, you are safe and have nothing to do except letting the exception propagate. If however you manually retrieve a disposable resource, then you may have to clean it up and rethrow the exception:
```
template <typename T>
struct my_vector
{
// This is why it is not advisable to roll your own vector.
my_vector(size_t n, const T& x)
{
begin = static_cast<T*>(custom_allocator(n * sizeof(T)));
end = begin + n;
size_t k = 0;
try
{
// This can throw...
for (; k != n; k++) new(begin + k) T(x);
}
catch (...)
{
// ... so destroy everything and bail out
while (--k) (begin + k)->~T();
custom_deallocator(begin);
throw;
}
}
private:
T* begin;
T* end;
};
```
but this should be quite rare if you use proper RAII objects (a quick `grep` from my current codebase shows hundreds of `throw`, but only two `catch`).
The exception guarantees from the standard library can be found in the ISO standard document (you have to pay a small fee for it).
Also, any good C++ book discusses exception safety at great length, the point being that usually you have nothing special to do. For instance, in your example, everything will be disposed properly, since `ifstream` close the file in its destructor. |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| You’re using `+arrayWithContentsOfFile:`, which returns an autoreleased object, then autoreleasing it again. Take out the call to `-autorelease` and you’ll be OK. You could re-write it as so:
```
sources = [[NSArray arrayWithContentsOfFile:plistPath] retain];
``` | That's because arrayWithContentsOfFile: returns an autoreleased array to you. Calling autorelease on this array will release it twice at the end of current event run loop. |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| You’re using `+arrayWithContentsOfFile:`, which returns an autoreleased object, then autoreleasing it again. Take out the call to `-autorelease` and you’ll be OK. You could re-write it as so:
```
sources = [[NSArray arrayWithContentsOfFile:plistPath] retain];
``` | Ditch the autorelease on the factory method. It's why you need a second retain. |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| Is it something to do with that autorelease? I can't see why that's there: it should be the factory method that autoreleases. Although I don't know what the consequence of adding an extra autorelease is, it might be worth seeing what happens if you take that out along with one of the retains. | ```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray alloc] initWithContentsOfFile:plistPath];
``` |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| Ditch the autorelease on the factory method. It's why you need a second retain. | ```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray alloc] initWithContentsOfFile:plistPath];
``` |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| There *is* an explicit call to release the array. `autorelease` is just as explicit as `release` — it just happens later. Not only that, but it was wrong to autorelease the array in the first place, since you didn't own it. One `retain` is necessary to claim ownership of the array. The second one prevents the crash by balancing out the incorrect use of `autorelease`. | That's because arrayWithContentsOfFile: returns an autoreleased array to you. Calling autorelease on this array will release it twice at the end of current event run loop. |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| There *is* an explicit call to release the array. `autorelease` is just as explicit as `release` — it just happens later. Not only that, but it was wrong to autorelease the array in the first place, since you didn't own it. One `retain` is necessary to claim ownership of the array. The second one prevents the crash by balancing out the incorrect use of `autorelease`. | ```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray alloc] initWithContentsOfFile:plistPath];
``` |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| There *is* an explicit call to release the array. `autorelease` is just as explicit as `release` — it just happens later. Not only that, but it was wrong to autorelease the array in the first place, since you didn't own it. One `retain` is necessary to claim ownership of the array. The second one prevents the crash by balancing out the incorrect use of `autorelease`. | Ditch the autorelease on the factory method. It's why you need a second retain. |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| That's because arrayWithContentsOfFile: returns an autoreleased array to you. Calling autorelease on this array will release it twice at the end of current event run loop. | ```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray alloc] initWithContentsOfFile:plistPath];
``` |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| You’re using `+arrayWithContentsOfFile:`, which returns an autoreleased object, then autoreleasing it again. Take out the call to `-autorelease` and you’ll be OK. You could re-write it as so:
```
sources = [[NSArray arrayWithContentsOfFile:plistPath] retain];
``` | ```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray alloc] initWithContentsOfFile:plistPath];
``` |
4,083,195 | I have a complex App that runs reliably, but I'm puzzled why I need to retain a particular NSArray ('sources') *twice* to prevent a crash (although no exception is reported on the console, but the application crashes and returns to the springboard).
A snippet of the code is included below. There's too much code to paste it all, but you have my word that there are no explicit calls to release the array. 'sources' is an instance variable.
If I only retain the array once (or not at all), I get the crash. With two retains, the App is perfectly stable.
```
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Sources" ofType:@"plist"];
sources = [[NSArray arrayWithContentsOfFile:plistPath] autorelease];
[sources retain];
[sources retain];
```
Thoughts on why I would need to retain this array *twice* appreciated. Thanks in advance. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4083195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451544/"
]
| There *is* an explicit call to release the array. `autorelease` is just as explicit as `release` — it just happens later. Not only that, but it was wrong to autorelease the array in the first place, since you didn't own it. One `retain` is necessary to claim ownership of the array. The second one prevents the crash by balancing out the incorrect use of `autorelease`. | You’re using `+arrayWithContentsOfFile:`, which returns an autoreleased object, then autoreleasing it again. Take out the call to `-autorelease` and you’ll be OK. You could re-write it as so:
```
sources = [[NSArray arrayWithContentsOfFile:plistPath] retain];
``` |
21,721 | Does anyone know why in some stores the save does not change the is\_anchor and in some stores it does? It is not working on a multi-store site (multiple default root categories)., though there may be other reasons.
The code below generally works. When it does not it, the save has no effect, without any log errors.
$anchorNew has the correct value in it.
```
Mage::app()->setCurrentStore($store_id);
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array("gt" => 1))
->setOrder('entity_id') ;
foreach($categories as $category) {
$anchor = $category->getIsAnchor();
if ($anchor == 1 ) {
continue;
}
$category->setIsAnchor(1);
$category->save();
$anchorNew = $category->getIsAnchor(); // this shows a 1 in is_anchor
}
```
I checked the database and there are not as many entries in - `catalog_category_entity_int`
WHERE attribute\_id = 51 - as there are categories. The $category->getIsAnchor() returns null for many of my categories. | 2014/05/28 | [
"https://magento.stackexchange.com/questions/21721",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3373/"
]
| The problem might be the fact that you are calling `save` on a category object that comes from a collection. To be sure it works, you should always call `load` before calling `save`.
something like this:
```
foreach($categories as $category) {
$anchor = $category->getIsAnchor();
if ($anchor == 1 ) {
continue;
}
$category->load($category->getId());
$category->setIsAnchor(1);
$category->save();
}
```
I know it's not a good practice to call `load` in a loop, but neither is calling `save` in a loop. | • Create a php file, Add below content
```
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('app/Mage.php');
Mage::app();
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_anchor', 0)
->addAttributeToFilter('entity_id', array("gt" => 1))
->setOrder('entity_id')
;
foreach($categories as $category) {
$category->setIsAnchor(1);
$category->save();
}
echo “Done”;
?>
```
* Upload to root of Magento server.
* Access the file from your web browser. |
21,721 | Does anyone know why in some stores the save does not change the is\_anchor and in some stores it does? It is not working on a multi-store site (multiple default root categories)., though there may be other reasons.
The code below generally works. When it does not it, the save has no effect, without any log errors.
$anchorNew has the correct value in it.
```
Mage::app()->setCurrentStore($store_id);
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array("gt" => 1))
->setOrder('entity_id') ;
foreach($categories as $category) {
$anchor = $category->getIsAnchor();
if ($anchor == 1 ) {
continue;
}
$category->setIsAnchor(1);
$category->save();
$anchorNew = $category->getIsAnchor(); // this shows a 1 in is_anchor
}
```
I checked the database and there are not as many entries in - `catalog_category_entity_int`
WHERE attribute\_id = 51 - as there are categories. The $category->getIsAnchor() returns null for many of my categories. | 2014/05/28 | [
"https://magento.stackexchange.com/questions/21721",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3373/"
]
| The problem might be the fact that you are calling `save` on a category object that comes from a collection. To be sure it works, you should always call `load` before calling `save`.
something like this:
```
foreach($categories as $category) {
$anchor = $category->getIsAnchor();
if ($anchor == 1 ) {
continue;
}
$category->load($category->getId());
$category->setIsAnchor(1);
$category->save();
}
```
I know it's not a good practice to call `load` in a loop, but neither is calling `save` in a loop. | Almost certainly the reason is that you have ***Use Flat Catalog Category*** set to ***Yes*** and your code doesn't account for this scenario.
Try turning that setting off in ***System -> Configuration -> Catalog -> Frontend*** and then run the script again. When you switch flat catalog back on again, be sure to reindex the required tables. |
21,721 | Does anyone know why in some stores the save does not change the is\_anchor and in some stores it does? It is not working on a multi-store site (multiple default root categories)., though there may be other reasons.
The code below generally works. When it does not it, the save has no effect, without any log errors.
$anchorNew has the correct value in it.
```
Mage::app()->setCurrentStore($store_id);
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array("gt" => 1))
->setOrder('entity_id') ;
foreach($categories as $category) {
$anchor = $category->getIsAnchor();
if ($anchor == 1 ) {
continue;
}
$category->setIsAnchor(1);
$category->save();
$anchorNew = $category->getIsAnchor(); // this shows a 1 in is_anchor
}
```
I checked the database and there are not as many entries in - `catalog_category_entity_int`
WHERE attribute\_id = 51 - as there are categories. The $category->getIsAnchor() returns null for many of my categories. | 2014/05/28 | [
"https://magento.stackexchange.com/questions/21721",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/3373/"
]
| Almost certainly the reason is that you have ***Use Flat Catalog Category*** set to ***Yes*** and your code doesn't account for this scenario.
Try turning that setting off in ***System -> Configuration -> Catalog -> Frontend*** and then run the script again. When you switch flat catalog back on again, be sure to reindex the required tables. | • Create a php file, Add below content
```
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('app/Mage.php');
Mage::app();
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_anchor', 0)
->addAttributeToFilter('entity_id', array("gt" => 1))
->setOrder('entity_id')
;
foreach($categories as $category) {
$category->setIsAnchor(1);
$category->save();
}
echo “Done”;
?>
```
* Upload to root of Magento server.
* Access the file from your web browser. |
69,495,808 | My code is:
```
import time
local_time = time.localtime()
time_string_d = time.strftime("%d", local_time)
time_string_m = time.strftime("%m", local_time)
time_string_y = time.strftime("%Y", local_time)
time_string_hm = time.strftime("%H:%M", local_time)
day_st = ['1', '21', '31']
day_nd = ['2', '22', '32']
day_rd = ['3', '23']
day_th = ['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18',
'19', '20', '24', '25', '26', '27', '28', '29', '30']
def month():
if time_string_m == '1':
print('It is ' + time_string_hm)
print('January ', day())
if time_string_m == '2':
print('It is ' + time_string_hm)
print('February ', day())
if time_string_m == '3':
print('It is ' + time_string_hm)
print('March ', day())
if time_string_m == '4':
print('It is ' + time_string_hm)
print('April ', day())
if time_string_m == '5':
print('It is ' + time_string_hm)
print('May ', day())
if time_string_m == '6':
print('It is ' + time_string_hm)
print('June ', day())
if time_string_m == '7':
print('It is ' + time_string_hm)
print('July ', day())
if time_string_m == '8':
print('It is ' + time_string_hm)
print('August ', day())
if time_string_m == '9':
print('It is ' + time_string_hm)
print('September ', day())
if time_string_m == '10':
print('It is ' + time_string_hm)
print('October ', day())
if time_string_m == '11':
print('It is ' + time_string_hm)
print('November ', day())
if time_string_m == '12':
print('It is ' + time_string_hm)
print('December ', day())
else:
print('There was an error in the month detecting system.')
def day():
if time_string_d in day_st:
print('st')
if time_string_d in day_nd:
print('nd')
if time_string_d in day_rd:
print('rd')
if time_string_d in day_th:
print('th')
else:
print('There was an error in the day detecting system.')
```
and I want it to print the following:
>
> It is (current time for example: 14:20)
>
> (current month for example: October, current day + /st/nd/rd/th for example 8th)
>
>
>
Like this:
```none
It is 14:20
October 8th
```
Also if it fails then the following:
>
> There was an error in the month detecting system
>
>
>
or
>
> There was an error in the day detecting system.
>
>
>
What it actually prints out:
```none
It is 14:20
There was an error in the day detecting system.
October None
There was an error in the month detecting system.
``` | 2021/10/08 | [
"https://Stackoverflow.com/questions/69495808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13814234/"
]
| You should use single [if-elif-else](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement) for example
```
x = 1
if x == 1:
print(1)
elif x == 2:
print(2)
else:
print("else")
```
will print `1`, whilst
```
x = 1
if x == 1:
print(1)
if x == 2:
print(2)
else:
print("else")
```
will print `1` then `else` because it has 2 if statements - if and if-else. You might use 0 or more `elif`s in single if statement, if you want to know more read linked docs. | The issue here is that you are chaining `if` statements instead of `elif`s, when your code is running, it checks each line, but the else statement runs in every case where:
```
if time_string_d in day_th:
```
is not true. As in, your function looks like this:
```
def day():
if time_string_d in day_st:
print('st')
if time_string_d in day_nd:
print('nd')
if time_string_d in day_rd:
print('rd')
if time_string_d in day_th:
print('th')
else:
print('There was an error in the day detecting system.')
```
and only this part matters for the else statement:
```
if time_string_d in day_th:
print('th')
else:
print('There was an error in the day detecting system.')
``` |
28,948,726 | I would like to create a button style which all of my buttons use, this way I do not need to set the android:textColor on each one.
I have this styling in a file named defaultbutton.xml
```
<item android:state_pressed="false" android:state_focused="false">
<shape android:shape="rectangle">
<solid android:color="#F3C22C"/>
<corners android:radius="10dp" />
</shape>
<color android:color="@color/brown"></color>
</item>
```
And for a test button I set:
```
android:background="@drawable/defaultbutton"
```
The button gets the background color but the text color stays as black.
What am I doing wrong? | 2015/03/09 | [
"https://Stackoverflow.com/questions/28948726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522049/"
]
| You need to add color attribute to the item tag to set color of text.
`/res/drawable/custom_color.xml`
```
<item android:state_pressed="false" android:state_focused="false"
android:color="@color/text_color"> //this is how text color can be defined
</item>
```
Now set `textColor` to the `textView` of your layout
```
<TextView ...
android:textColor="@drawable/custom_color">
``` | You can set it with style:
```
<style name="MyButtonText" parent="@android:style/Widget.Button">
<item name="android:textColor">@color/mycolor</item>
``` |
28,948,726 | I would like to create a button style which all of my buttons use, this way I do not need to set the android:textColor on each one.
I have this styling in a file named defaultbutton.xml
```
<item android:state_pressed="false" android:state_focused="false">
<shape android:shape="rectangle">
<solid android:color="#F3C22C"/>
<corners android:radius="10dp" />
</shape>
<color android:color="@color/brown"></color>
</item>
```
And for a test button I set:
```
android:background="@drawable/defaultbutton"
```
The button gets the background color but the text color stays as black.
What am I doing wrong? | 2015/03/09 | [
"https://Stackoverflow.com/questions/28948726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1522049/"
]
| You need to add color attribute to the item tag to set color of text.
`/res/drawable/custom_color.xml`
```
<item android:state_pressed="false" android:state_focused="false"
android:color="@color/text_color"> //this is how text color can be defined
</item>
```
Now set `textColor` to the `textView` of your layout
```
<TextView ...
android:textColor="@drawable/custom_color">
``` | You can go to "styles.xml" file, you can find it in "values" folder
and add the following lines to the file :
```
<style name="buttonstyle" >
<item name="android:textColor" >#ff11</item>
</style>
```
after that when you add button add this line to your button attr.
```
style="@style/buttonstyle"
``` |
2,455,061 | A function f is defined to be convex on the closed interval $[1,5]$ if and only if $f(t+(1-t)5) \le tf(1) + (1-t)f(5)$ for any $t$ between $0$ and $1$ inclusive $(0\le t\le 1).$
Please help me prove this or at least where to start and what I am looking for at the end. I am lost.
I would really appreciate it!
Thanks! | 2017/10/03 | [
"https://math.stackexchange.com/questions/2455061",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/486823/"
]
| $f(1)=(1-3)^2=4$,
$f(5)=(5-3)^2=4$, so the right hand side is $tf(1)+(1-t)f(5)=4t+(1-t)4=4$. The left hand side is $f(t+(1-t)5)=f(5-4t)=(5-4t-3)^2=(2-4t)^2=4(1-t)^2$.
Note that $0\leq t\leq 1$, so $0\leq 1-t\leq 1$, $0\leq(1-t)^2\leq 1$.
Multiply by 4 to obtain
$4(1-t)^2\leq 4$. Q.E.D. | As per my comment, we must show
$$f(tx + (1 - t)y) \le tf(x) + (1 - t)f(y)$$
for $t \in [0, 1]$ and $x, y \in [1, 5]$. Actually, $f(x) = (x - 3)^2$ is convex everywhere, so you'll find that we don't really need the assumption that $x, y \in [1, 5]$.
We have,
\begin{align\*}
&tf(x) + (1 - t)f(y) - f(tx + (1- t)y) \\
= ~ &t(x - 3)^2 + (1- t)(y - 3)^2 - (tx + (1 - t)y - 3)^2 \\
= ~ &t(x - 3)^2 + (1- t)(y - 3)^2 - (t(x - 3) + (1 - t)(y - 3))^2 \\
= ~ &t(x - 3)^2 + (1- t)(y - 3)^2 - t^2(x - 3)^2 - (1 - t)^2(y - 3)^2 - 2t(1 - t)(x - 3)(y - 3) \\
= ~ &t(1 - t)(x - 3)^2 + t(1- t)(y - 3)^2 - 2t(1 - t)(x - 3)(y - 3) \\
= ~ &t(1 - t)[(x - 3)^2 + (y - 3)^2 - 2(x - 3)(y - 3)] \\
= ~ &t(1 - t)[(x - 3) - (y - 3)]^2 \\
= ~ &t(1 - t)(x - y)^2 \ge 0,
\end{align\*}
which is what we wanted to prove. |
2,455,061 | A function f is defined to be convex on the closed interval $[1,5]$ if and only if $f(t+(1-t)5) \le tf(1) + (1-t)f(5)$ for any $t$ between $0$ and $1$ inclusive $(0\le t\le 1).$
Please help me prove this or at least where to start and what I am looking for at the end. I am lost.
I would really appreciate it!
Thanks! | 2017/10/03 | [
"https://math.stackexchange.com/questions/2455061",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/486823/"
]
| $f(1)=(1-3)^2=4$,
$f(5)=(5-3)^2=4$, so the right hand side is $tf(1)+(1-t)f(5)=4t+(1-t)4=4$. The left hand side is $f(t+(1-t)5)=f(5-4t)=(5-4t-3)^2=(2-4t)^2=4(1-t)^2$.
Note that $0\leq t\leq 1$, so $0\leq 1-t\leq 1$, $0\leq(1-t)^2\leq 1$.
Multiply by 4 to obtain
$4(1-t)^2\leq 4$. Q.E.D. | In this case,
the function has a second derivative
and $f''(x) = 2 > 0$
so it is convex. |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| The `*` character in a regular expression has a special meaning. To show the Pattern you don't mean for this special meaning, you have to "escape" it. The easiest way to do it is to put your expression through `Pattern.quote()`.
For example:
```
String searchFor = Pattern.quote("***");
```
Then use that string to search | This is not perfect, but it'll get you started:
```
// 4 lines, 2 of each containing "***" at random locations
String input = "abc***def\nghijkl\n***mnop\n**blah";
// replacing multiline pattern starting with any character 0 or more times,
// followed by 3 escaped "*"s,
// followed by any character 0 or more times
System.out.println(input.replaceAll("(?m).*\\*{3}.*", ""));
```
Output:
```
ghijkl
**blah
``` |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| The `*` character in a regular expression has a special meaning. To show the Pattern you don't mean for this special meaning, you have to "escape" it. The easiest way to do it is to put your expression through `Pattern.quote()`.
For example:
```
String searchFor = Pattern.quote("***");
```
Then use that string to search | If the three asterisks are not always at the begining of the line, you can use this pattern that removes newlines too:
```
(\r?\n)?[^\r\n*]*\Q***\E.*((1)?|\r?\n?)
``` |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| The `*` character in a regular expression has a special meaning. To show the Pattern you don't mean for this special meaning, you have to "escape" it. The easiest way to do it is to put your expression through `Pattern.quote()`.
For example:
```
String searchFor = Pattern.quote("***");
```
Then use that string to search | If all you're doing is looking for three specific characters together in a string, you don't need a regex at all:
```
if (line.contains("***")) {
...
}
```
(But if things get more complicated and you do need a regex, then use a backslash or `Pattern.quote` as the other answers say.)
(This is assuming you're reading lines one at a time, instead of having one big long buffer containing all the lines with newline characters. Some of the other answers handle the latter case.) |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| Note that`*` is a special character in regex so you have to use `\\*`
Your expression will be: `(?m)^\\*\\*.\\*` | This is not perfect, but it'll get you started:
```
// 4 lines, 2 of each containing "***" at random locations
String input = "abc***def\nghijkl\n***mnop\n**blah";
// replacing multiline pattern starting with any character 0 or more times,
// followed by 3 escaped "*"s,
// followed by any character 0 or more times
System.out.println(input.replaceAll("(?m).*\\*{3}.*", ""));
```
Output:
```
ghijkl
**blah
``` |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| Note that`*` is a special character in regex so you have to use `\\*`
Your expression will be: `(?m)^\\*\\*.\\*` | If the three asterisks are not always at the begining of the line, you can use this pattern that removes newlines too:
```
(\r?\n)?[^\r\n*]*\Q***\E.*((1)?|\r?\n?)
``` |
20,024,688 | I have a DIV which will contain the content for a website of mine. On the left side there is a menu which has its position set to `float`. When I re-size my browser the container gets under the box and it looks quite bad.
This is how it looks like:

I have tried to put all the relevant HTML and CSS in this fiddle: <http://jsfiddle.net/Dugi/qZ67C/>
How would I make the DIV container have itself getting smaller against the floating menu and not get under it? | 2013/11/16 | [
"https://Stackoverflow.com/questions/20024688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445820/"
]
| Note that`*` is a special character in regex so you have to use `\\*`
Your expression will be: `(?m)^\\*\\*.\\*` | If all you're doing is looking for three specific characters together in a string, you don't need a regex at all:
```
if (line.contains("***")) {
...
}
```
(But if things get more complicated and you do need a regex, then use a backslash or `Pattern.quote` as the other answers say.)
(This is assuming you're reading lines one at a time, instead of having one big long buffer containing all the lines with newline characters. Some of the other answers handle the latter case.) |
3,284,131 | I would like to solve the following series: $$\sum\_{n=3}^\infty \frac{\log(n-1)-\log(n)}{\log(n-1)\log(n)}$$
Here's what I did:
$$\sum\_{n=3}^\infty \frac{\log(n-1)-\log(n)}{\log(n-1)\log(n)}=\sum\_{n=3}^\infty \frac{\log\bigl(\frac{n-1}{n}\bigr)}{\log(n-1)\log(n)}=\sum\_{n=3}^\infty\frac{\log\bigl(1-\frac{1}{n}\bigr)}{\log(n-1)\log(n)}$$
Apparently I can solve this by using the comparison test, but I don't know how this would be implemented in this exercise. Also, if it is possible, how can I find the result of the series? | 2019/07/05 | [
"https://math.stackexchange.com/questions/3284131",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/353053/"
]
| $$\begin{align}
\sum\_{n=3}^{\infty} \frac{\log(n-1)-\log(n)}{\log(n-1) \log(n)}
&=\sum\_{n=3}^{\infty}\left( \frac{\log(n-1)}{\log(n-1) \log(n)}-\frac{\log(n)}{\log(n-1) \log(n)}\right) \\
&=\sum\_{n=3}^{\infty}\left( \frac{1}{\log(n)}-\frac{1}{\log(n-1)}\right) \\
&=\lim\_{N\to \infty}\sum\_{n=3}^N\left( \frac{1}{\log(n)}-\frac{1}{\log(n-1)}\right) \\
&=\lim\_{N\to \infty}\left(\frac{1}{\log N}-\frac{1}{\log 2}\right) \\
&=-\frac{1}{\log 2}.
\end{align}$$ | Hint: It is $$\sum\_{n=3}^{\infty}\frac{1}{\log(n)}-\frac{1}{\log(n-1)}$$ |
18,758,041 | I'm trying to play a video from youtube using javaFX. Here is my code
```
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Media");
Group root = new Group();
Media media = new Media("http://www.youtube.com/watch?v=k0BWlvnBmIE");
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
MediaView mediaView = new MediaView(mediaPlayer);
root.getChildren().add(mediaView);
Scene scene = SceneBuilder.create().width(500).height(500).root(root)
.fill(Color.WHITE).build();
primaryStage.setScene(scene);
primaryStage.show();
}
}
```
The window opens but video doesn't play and there is no exception. What is the problem and how can i fix it.
Thanks. | 2013/09/12 | [
"https://Stackoverflow.com/questions/18758041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2326666/"
]
| *Update Oct 2021*
I tried this solution again using JavaFX 17, it worked fine for me, which is kind of nice six years later.
Note that the video in the original example is no longer hosted on YouTube, but you would want to play a different video anyway.
To do so, just substitute the video id part of the url `utUPth77L_o` with the id of your video (which you can see in the url when you play it in YouTube).
Example URLs which worked in 2021:
* <https://www.youtube.com/watch?v=P_tAU3GM9XI>
* <https://www.youtube.com/embed/P_tAU3GM9XI?autoplay=1>
The `watch` linked videos display the full YouTube site, the `embed` linked videos just display the YouTube player for the video.
YouTube does force some videos to be displayed on its site rather than using the embed link, so even if the video can be watched on YouTube via the watch URL, the embed link won't always work, but the watch link should work OK in WebView for such cases.
*Update Dec 4th 2015*
Some versions of JavaFX 8 are unable to play back youtube video content. Currently, for instance, Java 8u66 cannot playback youtube video content, but Java 8u72 early access release can.
**Background**
General information on playing video in JavaFX is located in my answer to: [Any simple (and up to date) Java frameworks for embedding movies](https://stackoverflow.com/a/10441210/1155209). This answer just deals with embedding YouTube videos as that appears to be what the question asker is interested in.
**Solution**
JavaFX can play a YouTube video using a YouTube video URL if you supply the URL to a [WebView](http://docs.oracle.com/javafx/2/api/javafx/scene/web/WebView.html) rather than a [MediaPlayer](http://docs.oracle.com/javafx/2/api/javafx/scene/media/MediaPlayer.html).
**Considerations**
If you just want the YouTube media player and not the whole related YouTube page, use the `/embed` location rather than the `/watch` location in the URL.
Only some videos can be embedded. For instance, you can't embed the Katy Perry video because YouTube blocks it's distribution in an embedded format (instead telling you to view the video on the YouTube site, where it is only provided through the YouTube Flash player).
Only videos which YouTube allow to play in their HTML5 player may be played in JavaFX. This is a pretty large percentage of YouTube videos. YouTube videos which only play in YouTube's Flash player do not play in JavaFX.
**Sample Application**
The JavaFX application below plays a YouTube video advertisement for a piece of fruit.

```
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class VideoPlayer extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage) throws Exception {
WebView webview = new WebView();
webview.getEngine().load(
"http://www.youtube.com/embed/utUPth77L_o?autoplay=1"
);
webview.setPrefSize(640, 390);
stage.setScene(new Scene(webview));
stage.show();
}
}
``` | JavaFX can't play youtube video just with the video url. you need to specify the file of your video, not just a random youtube link.
Try with this URL : <http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv>
your code works fine |
124,653 | I am new to Python and need help. Looked for my answer but don't know if I am even using the correct terminology.
I have a model in which I iterated through rows and performed a set of processes on each. For example a feature class with 10 features and on each of the 10 features I wanted to create an individual feature class....or... for each row create a raster based on the field (e.g.) ID. I am trying to turn this to Python due to a host of reasons.
I am using 10.1 and the error is occurring at line 40 "FeatureClassToFeatureClass"
I believe that it is failing due to my improper use of 'row" as the input.
Here is what I have so far, but I cannot get it to work
---
```
# Import arcpy module
print "Starting...."
import arcpy
from arcpy import env
# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")
env.overwriteOutput = True
selectingfeatures = "\\\\silver\\clients\\trans1.shp"
Trans1_shp = "\\\\silver\\clients\\trans1.shp"
basecldem = "\\\\silver\\clients\\basecldem"
TEMP = "\\\\silver\\clients\\TEMP"
Zone3_shp = "\\\\silver\\clients\\Zone2.shp"
transarea = "\\\\silver\\clients\\transarea"
RegionGRP = "\\\\silver\\clients\\regiongrp"
ZonalMean = "\\\\silver\\clients\\zonalmean"
ZoneArea = "\\\\silver\\clients\\zonearea"
Transition__n_ = "\\\\silver\\clients\\transition_%n%"
I_trans1 = "I_trans1_FID"
selectingLayer = arcpy.MakeFeatureLayer_management(selectingfeatures)
rows = arcpy.SearchCursor(selectingLayer)
#cursor = arcpy.SearchCursor(fc)
#row = cursor.next()
#while row:
# print(row.getValue(field))
for row in rows:
arcpy.FeatureClassToFeatureClass_conversion(row, TEMP, "Zone2.shp", "", "ID \"ID\" true true false 4 Short 0 4 ,First,#,\\\\silver\\clients\\Projects\\P696\\8_BaseMine\\Processing\\TEMP\\trans1.shp,ID,-1,-1", "")
print "Finished PFC 2 FC...."
# Process: Polygon to Raster
arcpy.PolygonToRaster_conversion(Zone3_shp, "ID", ZoneArea, "CELL_CENTER", "NONE", "1")
print "Finished Polygon to Raster...."
# Process: Extract by Mask
arcpy.gp.ExtractByMask_sa(basecldem, Zone3_shp, transarea)
print "Extract by Mask...."
# Process: Region Group
arcpy.gp.RegionGroup_sa(ZoneArea, RegionGRP, "FOUR", "WITHIN", "ADD_LINK", "")
print "Finished Region Group...."
# Process: Zonal Statistics
arcpy.gp.ZonalStatistics_sa(RegionGRP, "VALUE", transarea, ZonalMean, "MEAN", "DATA")
print "Finished Zonal Statistics...."
# Process: Raster Calculator
arcpy.gp.RasterCalculator_sa("If( \"%basecldem%\" > ( 0.5 + \"%ZonalMean%\" ), 0, 1 )", Transition__n_)
print "Finished Raster Calcualtor"
#row = cursor.next()
``` | 2014/12/05 | [
"https://gis.stackexchange.com/questions/124653",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/41060/"
]
| `row.getValue(field)` didn't make sense to me. Going down that path never worked out. I ended up finding something that worked:
```
arcpy.MakeFeatureLayer_management(Caribou, FCView)
cursor = arcpy.SearchCursor(FCView)
for row in cursor:
objectid = str(row.getValue("OBJECTID"))
arcpy.SelectLayerByAttribute_management(FCView, "NEW_SELECTION", '"OBJECTID"= {}'.format(objectid))
arcpy.FeatureClassToFeatureClass_conversion(FCView , TEMP, "CARIBOU", "#", FieldMappings2)
``` | I think your error is with:
```
rows = arcpy.SearchCursor(selectingLayer)
for row in rows:
arcpy.FeatureClassToFeatureClass_conversion(row, TEMP, "Zone2.shp", "", "ID \"ID\" true true false 4 Short 0 4 ,First,#,\\\\silver\\clients\\SYNCRUDE\\Projects\\P696\\8_BaseMine\\Processing\\TEMP\\trans1.shp,ID,-1,-1", "")
```
[FeatureClassToFeatureClass](http://resources.arcgis.com/en/help/main/10.1/index.html#//001200000020000000) expects as its first parameter:
>
> The feature class or feature layer that will be converted.
>
>
>
You are providing it with a row object (which you named `row`) instead. Rather than `row`, if the name of the feature class or feature layer is being stored in a variable called `field` then use:
```
arcpy.FeatureClassToFeatureClass_conversion(row.getValue(field), TEMP, "Zone2.shp", "", "ID \"ID\" true true false 4 Short 0 4 ,First,#,\\\\silver\\clients\\SYNCRUDE\\Projects\\P696\\8_BaseMine\\Processing\\TEMP\\trans1.shp,ID,-1,-1", "")
```
but be aware that your code does not set the variable `field` anywhere that I can see.
Depending on how you are setting `field` you may need to be aware that ListFields returns a list of field objects rather than field names so `field.name` may be needed. |
48,930,447 | I am trying to learn geofire I try to implement the SFVehicle app but it is showing error can you please help this is the crucial part of my project
```
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final GeoLocation INITIAL_CENTER = new GeoLocation(37.7789, -122.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static String GEO_FIRE_DB = "https://learngoef.firebaseio.com";
private static String GEO_FIRE_REF = GEO_FIRE_DB+ "/_geofire";
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery mGeoQuery;
private Map<String,Marker> markers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase database = FirebaseDatabase.getInstance();
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017));
}
```
This is the error that I'm getting:
>
> java.lang.NoSuchMethodError: No virtual method
> setValue(Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/firebase/tasks/Task;
> in class Lcom/google/firebase/database/DatabaseReference; or its super
> classes (declaration of
> 'com.google.firebase.database.DatabaseReference' appears in
> /data/app/com.myapps.learninggeofire-2/split\_lib\_dependencies\_apk.apk)
>
>
> | 2018/02/22 | [
"https://Stackoverflow.com/questions/48930447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204259/"
]
| It will work fine if you add a listener in its parameters.As
```
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017)),new
GeoFire.CompletionListener(){
@Override
public void onComplete(String key, DatabaseError error) {
//Do some stuff if you want to
}
});
```
I think it might help you. | I spent 4 hours working on that error
```
geoFire.setLocation(userId, new GeoLocation(37.7789, -122.4017)),new
GeoFire.CompletionListener(){
@Override
public void onComplete(String key, DatabaseError error) {
Log.e(TAG, "GeoFire Complete");
}
});
```
It still didn't work till I change the firebase dependency to 16.0.4 instead of 16.0.1 |
48,930,447 | I am trying to learn geofire I try to implement the SFVehicle app but it is showing error can you please help this is the crucial part of my project
```
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final GeoLocation INITIAL_CENTER = new GeoLocation(37.7789, -122.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static String GEO_FIRE_DB = "https://learngoef.firebaseio.com";
private static String GEO_FIRE_REF = GEO_FIRE_DB+ "/_geofire";
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery mGeoQuery;
private Map<String,Marker> markers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase database = FirebaseDatabase.getInstance();
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017));
}
```
This is the error that I'm getting:
>
> java.lang.NoSuchMethodError: No virtual method
> setValue(Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/firebase/tasks/Task;
> in class Lcom/google/firebase/database/DatabaseReference; or its super
> classes (declaration of
> 'com.google.firebase.database.DatabaseReference' appears in
> /data/app/com.myapps.learninggeofire-2/split\_lib\_dependencies\_apk.apk)
>
>
> | 2018/02/22 | [
"https://Stackoverflow.com/questions/48930447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204259/"
]
| It will work fine if you add a listener in its parameters.As
```
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017)),new
GeoFire.CompletionListener(){
@Override
public void onComplete(String key, DatabaseError error) {
//Do some stuff if you want to
}
});
```
I think it might help you. | Downgrade your geofire dependency from latest version to
implementation 'com.firebase:geofire-android:2.1.1' |
48,930,447 | I am trying to learn geofire I try to implement the SFVehicle app but it is showing error can you please help this is the crucial part of my project
```
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final GeoLocation INITIAL_CENTER = new GeoLocation(37.7789, -122.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static String GEO_FIRE_DB = "https://learngoef.firebaseio.com";
private static String GEO_FIRE_REF = GEO_FIRE_DB+ "/_geofire";
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery mGeoQuery;
private Map<String,Marker> markers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase database = FirebaseDatabase.getInstance();
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017));
}
```
This is the error that I'm getting:
>
> java.lang.NoSuchMethodError: No virtual method
> setValue(Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/firebase/tasks/Task;
> in class Lcom/google/firebase/database/DatabaseReference; or its super
> classes (declaration of
> 'com.google.firebase.database.DatabaseReference' appears in
> /data/app/com.myapps.learninggeofire-2/split\_lib\_dependencies\_apk.apk)
>
>
> | 2018/02/22 | [
"https://Stackoverflow.com/questions/48930447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9204259/"
]
| It will work fine if you add a listener in its parameters.As
```
geoFire = new GeoFire(database.getReference().child("geofire_location"));
String key = geoFire.getDatabaseReference().push().getKey();
geoFire.setLocation(key,new GeoLocation(37.7789, -122.4017)),new
GeoFire.CompletionListener(){
@Override
public void onComplete(String key, DatabaseError error) {
//Do some stuff if you want to
}
});
```
I think it might help you. | Read this - <https://github.com/firebase/geofire-java>
Its support - implementation 'com.firebase:geofire-java:3.0.0' (vertion)
//----------------------------------------code-------------------------------------------
```
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
String userid = firebaseUser.getUid();
DatabaseReference ref = firebaseDatabase.getReference("Active Users");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userid, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
if (error!=null)
{
Toast.makeText(client_dashboard.this,"Can't go Active",Toast.LENGTH_SHORT).show();
}
Toast.makeText(client_dashboard.this,"You are Active",Toast.LENGTH_SHORT).show();
}
});
``` |
13,628,337 | Is it possible to detect where text wraps?
>
> Lorem ipsum dolor sit amet
>
>
>
lets say that above text wraps after 'dolor' word. How to detect that and insert there some mark of it so it would be `Lorem ipsum dolor<div class='wrap-mark'/> sit amet` for example? | 2012/11/29 | [
"https://Stackoverflow.com/questions/13628337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1785870/"
]
| I've seen this problem solved a few different ways. One of my favorites involves creating a div that mirrors the width of the container that holds your text. You then print words of your content into faux-container one-by-one, measuring the height of the container along the way. When the height of the container changes, you know you have a line feed/wrap.
Facebook and a few other CMS's use a method like this to grow their textareas to fit the contents of a user's input. I'm sure you could probably glean a few more creative ways to measure your text by researching those techniques, too. | Use the soft-hyphen entity to mark the wrapping position, plus the non-breaking-space entity to separate words without whitespace. The non-breaking space needs to come before the soft hyphen for IE10. Here is an example:
Here is a cross-browser solution:
```
<!doctype html>
<html>
<head>
<title>Soft Hyphen Text Wrapping</title>
<style>
/* Generate space after each soft hyphen */
.fake-space:after { content: "\00a0"; }
@media all and (-ms-high-contrast: none) {
/* Generate space before each soft hyphen for IE10 */
.fake-space:before { content: "\00a0"; }
.fake-space:after { content: ""; }
}
</style>
</head>
<body>
<!--Paragraph with words separated by soft hypen entity wrapped in a span-->
<p>Lorem<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet<span class="fake-space">­</span>ipsum<span class="fake-space">­</span>dolor<span class="fake-space">­</span>sit<span class="fake-space">­</span>amet</p>
</body>
</html>
```
**References**
* [Yes, SOFT HYPHEN is a hard problem](http://www.unicode.org/L2/L2002/02279-muller.htm)
* [Unicode Line Breaking Algorithm](http://www.unicode.org/reports/tr14/)
* [The WBR tag](http://www.quirksmode.org/oddsandends/wbr.html)
* [Soft Hyphen - A Hard Problem?](http://www.cs.tut.fi/~jkorpela/shy.html)
* [No-wrapping and Softwrapping: with NOBR, WBR and ­](http://www.sam-i-am.com/work/sandbox/html/wbr.html)
* [nobr and wbr](http://www.cs.tut.fi/~jkorpela/html/nobr.html#wbr)
* [Suggested Word Break](http://reference.sitepoint.com/html/wbr)
* [The WBR Element](http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-wbr-element) |
59,356,616 | I have a large data-set consisting of a header and a series of values in that column. I want to detect the presence and number of duplicates of these values within the whole dataset.
```
1 2 3 4 5 6 7
734 456 346 545 874 734 455
734 783 482 545 456 948 483
```
So for example, it would detect 734 3 times, 456 twice etc.
I've tried using the duplicated function in r but this seems to only work on rows as a whole or columns as a whole. Using
```
duplicated(df)
```
doesn't pick up any duplicates, though I know there are two duplicates in the first row.
So I'm asking how to detect duplicates both within and between columns/rows.
Cheers | 2019/12/16 | [
"https://Stackoverflow.com/questions/59356616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7136792/"
]
| You can use `table()` and `data.frame()` to see the occurrence
```
data.frame(table(v))
```
such that
```
v Freq
1 1 1
2 2 1
3 3 1
4 4 1
5 5 1
6 6 1
7 7 1
8 346 1
9 455 1
10 456 2
11 482 1
12 483 1
13 545 2
14 734 3
15 783 1
16 874 1
17 948 1
```
**DATA**
```
v <- c(1, 2, 3, 4, 5, 6, 7, 734, 456, 346, 545, 874, 734, 455, 734,
783, 482, 545, 456, 948, 483)
``` | You can transform it to a vector and then use `table()` as follows:
```
library(data.table)
library(dplyr)
df<-fread("734 456 346 545 874 734 455
734 783 482 545 456 948 483")
df%>%unlist()%>%table()
# 346 455 456 482 483 545 734 783 874 948
# 1 1 2 1 1 2 3 1 1 1
``` |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @Aaron's code above is broken due to *gensim* API changes. I rewrote and simplified it as follows. Works as of June 2017 with *gensim* v2.1.0
```
import pandas as pd
def topic_prob_extractor(gensim_hdp):
shown_topics = gensim_hdp.show_topics(num_topics=-1, formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})
``` | @user3907335 is exactly correct here: HDP will calculate as many topics as the assigned truncation level. *However*, it may be the case that many of these topics have basically zero probability of occurring. To help with this in my own work, I wrote a handy little function that performs a rough estimate of the probability weight associated with each topic. Note that this is a rough metric only: *it does not account for the probability associated with each word*. Even so, it provides a pretty good metric for which topics are meaningful and which aren't:
```
import pandas as pd
import numpy as np
def topic_prob_extractor(hdp=None, topn=None):
topic_list = hdp.show_topics(topics=-1, topn=topn)
topics = [int(x.split(':')[0].split(' ')[1]) for x in topic_list]
split_list = [x.split(' ') for x in topic_list]
weights = []
for lst in split_list:
sub_list = []
for entry in lst:
if '*' in entry:
sub_list.append(float(entry.split('*')[0]))
weights.append(np.asarray(sub_list))
sums = [np.sum(x) for x in weights]
return pd.DataFrame({'topic_id' : topics, 'weight' : sums})
```
I assume that you already know how to calculate an HDP model. Once you have an hdp model calculated by gensim you call the function as follows:
```
topic_weights = topic_prob_extractor(hdp, 500)
``` |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| There is apparently a bug in Gensim(version 3.8.3), in which giving `-1` to `show_topics` doesn't return anything at all. So I have tweaked the answers by **Roko Mijic** and **aaron**.
```
def topic_prob_extractor(gensim_hdp):
shown_topics = gensim_hdp.show_topics(num_topics=gensim_hdp.m_T, formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})
``` | I haven't used gensim for HDPs, but is it possible that most of the topics in the smaller corpus have extremely low probability of occurring ? Can you trying printing the topic probabilities? Maybe, the length of the topics array doesn't necessarily mean that all those topics were actually found in the corpus. |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @Aron's and @Roko Mijic's approaches neglect the fact that the function [`show_topics`](https://radimrehurek.com/gensim/models/hdpmodel.html#gensim.models.hdpmodel.HdpModel.show_topics) returns by default the top 20 words of each topic only. If one returns all the words that compose a topic, all the approximated topic probabilities in that case will be 1 (or 0.999999). I experimented with the following code, which is an adaptation of @Roko Mijic's:
```
def topic_prob_extractor(gensim_hdp, t=-1, w=25, isSorted=True):
"""
Input the gensim model to get the rough topics' probabilities
"""
shown_topics = gensim_hdp.show_topics(num_topics=t, num_words=w ,formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
if (isSorted):
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights}).sort_values(by = "weight", ascending=False);
else:
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights});
```
A better, yet I'm not sure if 100% valid, approach is the one mentioned [here](https://groups.google.com/d/msg/gensim/YujF90ahELE/KV2cNBpXV7IJ). You can get the topics' true weights (alpha vector) of the HDP model as:
```
alpha = hdpModel.hdp_to_lda()[0];
```
Examining the topics' equivalent alpha values is more logical than tallying up the weights of the first 20 words of each topic to approximate its probability of usage in the data. | I think you misunderstood the operation performed by the called method. Directly from the documentation you can see:
>
> Alias for show\_topics() that prints the top n most probable words for topics number of topics to log. Set topics=-1 to print all topics.
>
>
>
You trained the model without specifying the truncation level on the number of topics and the default one is 150. Calling the `print_topics` with `topics=-1` you'll get the top 20 words for each topic , in your case 150 topics.
I'm still a newbie of the library, so maybe I' wrong |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @Aron's and @Roko Mijic's approaches neglect the fact that the function [`show_topics`](https://radimrehurek.com/gensim/models/hdpmodel.html#gensim.models.hdpmodel.HdpModel.show_topics) returns by default the top 20 words of each topic only. If one returns all the words that compose a topic, all the approximated topic probabilities in that case will be 1 (or 0.999999). I experimented with the following code, which is an adaptation of @Roko Mijic's:
```
def topic_prob_extractor(gensim_hdp, t=-1, w=25, isSorted=True):
"""
Input the gensim model to get the rough topics' probabilities
"""
shown_topics = gensim_hdp.show_topics(num_topics=t, num_words=w ,formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
if (isSorted):
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights}).sort_values(by = "weight", ascending=False);
else:
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights});
```
A better, yet I'm not sure if 100% valid, approach is the one mentioned [here](https://groups.google.com/d/msg/gensim/YujF90ahELE/KV2cNBpXV7IJ). You can get the topics' true weights (alpha vector) of the HDP model as:
```
alpha = hdpModel.hdp_to_lda()[0];
```
Examining the topics' equivalent alpha values is more logical than tallying up the weights of the first 20 words of each topic to approximate its probability of usage in the data. | Deriving the average coherence of HDP topics from their coherence at the individual text level is a way to order (and potentially truncate) them. The following function does just that:
```py
def order_subset_by_coherence(dirichlet_model, bow_corpus, num_topics=10, num_keywords=10):
"""
Orders topics based on their average coherence across the corpus
Parameters
----------
dirichlet_model : gensim.models.hdpmodel.HdpModel
bow_corpus : list of lists (contains (id, freq) tuples)
num_topics : int (default=10)
num_keywords : int (default=10)
Returns
-------
ordered_topics: list of lists containing topic tokens
"""
shown_topics = dirichlet_model.show_topics(num_topics=150, # return all topics
num_words=num_keywords,
formatted=False)
model_topics = [[word[0] for word in topic[1]] for topic in shown_topics]
topic_corpus = dirichlet_model.__getitem__(bow=bow_corpus, eps=0) # cutoff probability to 0
topics_per_response = [response for response in topic_corpus]
flat_topic_coherences = [item for sublist in topics_per_response for item in sublist]
significant_topics = list(set([t_c[0] for t_c in flat_topic_coherences])) # those that appear
topic_averages = [sum([t_c[1] for t_c in flat_topic_coherences if t_c[0] == topic_num]) / len(bow_corpus) \
for topic_num in significant_topics]
topic_indexes_by_avg_coherence = [tup[0] for tup in sorted(enumerate(topic_averages), key=lambda i:i[1])[::-1]]
significant_topics_by_avg_coherence = [significant_topics[i] for i in topic_indexes_by_avg_coherence]
ordered_topics = [model_topics[i] for i in significant_topics_by_avg_coherence][:num_topics] # truncate if desired
return ordered_topics
```
A version of this function that includes an output of the averages coherences associated with the topics for keyword (tag) generation for a corpus can be found in [this answer](https://stackoverflow.com/a/64284694/12446118). A similar process for keywords for individual texts can further be found in [this answer](https://stackoverflow.com/a/64285526/12446118). |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| I haven't used gensim for HDPs, but is it possible that most of the topics in the smaller corpus have extremely low probability of occurring ? Can you trying printing the topic probabilities? Maybe, the length of the topics array doesn't necessarily mean that all those topics were actually found in the corpus. | Deriving the average coherence of HDP topics from their coherence at the individual text level is a way to order (and potentially truncate) them. The following function does just that:
```py
def order_subset_by_coherence(dirichlet_model, bow_corpus, num_topics=10, num_keywords=10):
"""
Orders topics based on their average coherence across the corpus
Parameters
----------
dirichlet_model : gensim.models.hdpmodel.HdpModel
bow_corpus : list of lists (contains (id, freq) tuples)
num_topics : int (default=10)
num_keywords : int (default=10)
Returns
-------
ordered_topics: list of lists containing topic tokens
"""
shown_topics = dirichlet_model.show_topics(num_topics=150, # return all topics
num_words=num_keywords,
formatted=False)
model_topics = [[word[0] for word in topic[1]] for topic in shown_topics]
topic_corpus = dirichlet_model.__getitem__(bow=bow_corpus, eps=0) # cutoff probability to 0
topics_per_response = [response for response in topic_corpus]
flat_topic_coherences = [item for sublist in topics_per_response for item in sublist]
significant_topics = list(set([t_c[0] for t_c in flat_topic_coherences])) # those that appear
topic_averages = [sum([t_c[1] for t_c in flat_topic_coherences if t_c[0] == topic_num]) / len(bow_corpus) \
for topic_num in significant_topics]
topic_indexes_by_avg_coherence = [tup[0] for tup in sorted(enumerate(topic_averages), key=lambda i:i[1])[::-1]]
significant_topics_by_avg_coherence = [significant_topics[i] for i in topic_indexes_by_avg_coherence]
ordered_topics = [model_topics[i] for i in significant_topics_by_avg_coherence][:num_topics] # truncate if desired
return ordered_topics
```
A version of this function that includes an output of the averages coherences associated with the topics for keyword (tag) generation for a corpus can be found in [this answer](https://stackoverflow.com/a/64284694/12446118). A similar process for keywords for individual texts can further be found in [this answer](https://stackoverflow.com/a/64285526/12446118). |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @Aron's and @Roko Mijic's approaches neglect the fact that the function [`show_topics`](https://radimrehurek.com/gensim/models/hdpmodel.html#gensim.models.hdpmodel.HdpModel.show_topics) returns by default the top 20 words of each topic only. If one returns all the words that compose a topic, all the approximated topic probabilities in that case will be 1 (or 0.999999). I experimented with the following code, which is an adaptation of @Roko Mijic's:
```
def topic_prob_extractor(gensim_hdp, t=-1, w=25, isSorted=True):
"""
Input the gensim model to get the rough topics' probabilities
"""
shown_topics = gensim_hdp.show_topics(num_topics=t, num_words=w ,formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
if (isSorted):
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights}).sort_values(by = "weight", ascending=False);
else:
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights});
```
A better, yet I'm not sure if 100% valid, approach is the one mentioned [here](https://groups.google.com/d/msg/gensim/YujF90ahELE/KV2cNBpXV7IJ). You can get the topics' true weights (alpha vector) of the HDP model as:
```
alpha = hdpModel.hdp_to_lda()[0];
```
Examining the topics' equivalent alpha values is more logical than tallying up the weights of the first 20 words of each topic to approximate its probability of usage in the data. | I haven't used gensim for HDPs, but is it possible that most of the topics in the smaller corpus have extremely low probability of occurring ? Can you trying printing the topic probabilities? Maybe, the length of the topics array doesn't necessarily mean that all those topics were actually found in the corpus. |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @Aaron's code above is broken due to *gensim* API changes. I rewrote and simplified it as follows. Works as of June 2017 with *gensim* v2.1.0
```
import pandas as pd
def topic_prob_extractor(gensim_hdp):
shown_topics = gensim_hdp.show_topics(num_topics=-1, formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})
``` | @Aron's and @Roko Mijic's approaches neglect the fact that the function [`show_topics`](https://radimrehurek.com/gensim/models/hdpmodel.html#gensim.models.hdpmodel.HdpModel.show_topics) returns by default the top 20 words of each topic only. If one returns all the words that compose a topic, all the approximated topic probabilities in that case will be 1 (or 0.999999). I experimented with the following code, which is an adaptation of @Roko Mijic's:
```
def topic_prob_extractor(gensim_hdp, t=-1, w=25, isSorted=True):
"""
Input the gensim model to get the rough topics' probabilities
"""
shown_topics = gensim_hdp.show_topics(num_topics=t, num_words=w ,formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
if (isSorted):
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights}).sort_values(by = "weight", ascending=False);
else:
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights});
```
A better, yet I'm not sure if 100% valid, approach is the one mentioned [here](https://groups.google.com/d/msg/gensim/YujF90ahELE/KV2cNBpXV7IJ). You can get the topics' true weights (alpha vector) of the HDP model as:
```
alpha = hdpModel.hdp_to_lda()[0];
```
Examining the topics' equivalent alpha values is more logical than tallying up the weights of the first 20 words of each topic to approximate its probability of usage in the data. |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @user3907335 is exactly correct here: HDP will calculate as many topics as the assigned truncation level. *However*, it may be the case that many of these topics have basically zero probability of occurring. To help with this in my own work, I wrote a handy little function that performs a rough estimate of the probability weight associated with each topic. Note that this is a rough metric only: *it does not account for the probability associated with each word*. Even so, it provides a pretty good metric for which topics are meaningful and which aren't:
```
import pandas as pd
import numpy as np
def topic_prob_extractor(hdp=None, topn=None):
topic_list = hdp.show_topics(topics=-1, topn=topn)
topics = [int(x.split(':')[0].split(' ')[1]) for x in topic_list]
split_list = [x.split(' ') for x in topic_list]
weights = []
for lst in split_list:
sub_list = []
for entry in lst:
if '*' in entry:
sub_list.append(float(entry.split('*')[0]))
weights.append(np.asarray(sub_list))
sums = [np.sum(x) for x in weights]
return pd.DataFrame({'topic_id' : topics, 'weight' : sums})
```
I assume that you already know how to calculate an HDP model. Once you have an hdp model calculated by gensim you call the function as follows:
```
topic_weights = topic_prob_extractor(hdp, 500)
``` | I think you misunderstood the operation performed by the called method. Directly from the documentation you can see:
>
> Alias for show\_topics() that prints the top n most probable words for topics number of topics to log. Set topics=-1 to print all topics.
>
>
>
You trained the model without specifying the truncation level on the number of topics and the default one is 150. Calling the `print_topics` with `topics=-1` you'll get the top 20 words for each topic , in your case 150 topics.
I'm still a newbie of the library, so maybe I' wrong |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| There is apparently a bug in Gensim(version 3.8.3), in which giving `-1` to `show_topics` doesn't return anything at all. So I have tweaked the answers by **Roko Mijic** and **aaron**.
```
def topic_prob_extractor(gensim_hdp):
shown_topics = gensim_hdp.show_topics(num_topics=gensim_hdp.m_T, formatted=False)
topics_nos = [x[0] for x in shown_topics ]
weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]
return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})
``` | Deriving the average coherence of HDP topics from their coherence at the individual text level is a way to order (and potentially truncate) them. The following function does just that:
```py
def order_subset_by_coherence(dirichlet_model, bow_corpus, num_topics=10, num_keywords=10):
"""
Orders topics based on their average coherence across the corpus
Parameters
----------
dirichlet_model : gensim.models.hdpmodel.HdpModel
bow_corpus : list of lists (contains (id, freq) tuples)
num_topics : int (default=10)
num_keywords : int (default=10)
Returns
-------
ordered_topics: list of lists containing topic tokens
"""
shown_topics = dirichlet_model.show_topics(num_topics=150, # return all topics
num_words=num_keywords,
formatted=False)
model_topics = [[word[0] for word in topic[1]] for topic in shown_topics]
topic_corpus = dirichlet_model.__getitem__(bow=bow_corpus, eps=0) # cutoff probability to 0
topics_per_response = [response for response in topic_corpus]
flat_topic_coherences = [item for sublist in topics_per_response for item in sublist]
significant_topics = list(set([t_c[0] for t_c in flat_topic_coherences])) # those that appear
topic_averages = [sum([t_c[1] for t_c in flat_topic_coherences if t_c[0] == topic_num]) / len(bow_corpus) \
for topic_num in significant_topics]
topic_indexes_by_avg_coherence = [tup[0] for tup in sorted(enumerate(topic_averages), key=lambda i:i[1])[::-1]]
significant_topics_by_avg_coherence = [significant_topics[i] for i in topic_indexes_by_avg_coherence]
ordered_topics = [model_topics[i] for i in significant_topics_by_avg_coherence][:num_topics] # truncate if desired
return ordered_topics
```
A version of this function that includes an output of the averages coherences associated with the topics for keyword (tag) generation for a corpus can be found in [this answer](https://stackoverflow.com/a/64284694/12446118). A similar process for keywords for individual texts can further be found in [this answer](https://stackoverflow.com/a/64285526/12446118). |
31,543,550 | this is my first post so I'll try to make sure I'm following appropriate posting etiquette.
I have no experience whatsoever with html, d3, or javascript. I do however have some exposure to xml and svg. I'm trying to work through this tutorial: [<http://bost.ocks.org/mike/circles/]>. I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. Unfortunately the tutorial never shows the entirety of their code. I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. I'm not even sure if the xml is embedded within the html or if it is external and read in somehow.
Could someone post the html you would use to do this? Any assistance would be greatly appreciated.
Here is the xml corresponding to the circles:
```
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
And here is the code to make the changes:
```
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
``` | 2015/07/21 | [
"https://Stackoverflow.com/questions/31543550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139794/"
]
| @user3907335 is exactly correct here: HDP will calculate as many topics as the assigned truncation level. *However*, it may be the case that many of these topics have basically zero probability of occurring. To help with this in my own work, I wrote a handy little function that performs a rough estimate of the probability weight associated with each topic. Note that this is a rough metric only: *it does not account for the probability associated with each word*. Even so, it provides a pretty good metric for which topics are meaningful and which aren't:
```
import pandas as pd
import numpy as np
def topic_prob_extractor(hdp=None, topn=None):
topic_list = hdp.show_topics(topics=-1, topn=topn)
topics = [int(x.split(':')[0].split(' ')[1]) for x in topic_list]
split_list = [x.split(' ') for x in topic_list]
weights = []
for lst in split_list:
sub_list = []
for entry in lst:
if '*' in entry:
sub_list.append(float(entry.split('*')[0]))
weights.append(np.asarray(sub_list))
sums = [np.sum(x) for x in weights]
return pd.DataFrame({'topic_id' : topics, 'weight' : sums})
```
I assume that you already know how to calculate an HDP model. Once you have an hdp model calculated by gensim you call the function as follows:
```
topic_weights = topic_prob_extractor(hdp, 500)
``` | I haven't used gensim for HDPs, but is it possible that most of the topics in the smaller corpus have extremely low probability of occurring ? Can you trying printing the topic probabilities? Maybe, the length of the topics array doesn't necessarily mean that all those topics were actually found in the corpus. |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| ```
$newformat = new DateTime::createFromFormat('Y z', "2009 322")->format('Y-M-d');
```
Relevant docs here: <http://php.net/manual/en/datetime.createfromformat.php> | Try this
[strtotime function](http://php.net/manual/en/function.strtotime.php) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.