id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,629,697 | How to turn on error messages in magento 2 | <p>I have installed magento 2 and it working.I just created the Hello world module and it working now.</p>
<p>My issue was I had called non existing method in execute method.</p>
<p>While trying to get it to work I tried to load the page it shows blank white screen, but no error.</p>
<p>How do I get errors to display in magento2?</p> | 34,740,378 | 7 | 3 | null | 2016-01-06 09:32:54.767 UTC | 5 | 2019-07-09 20:31:16.243 UTC | 2016-01-06 09:53:50.8 UTC | null | 5,633,805 | null | 5,633,805 | null | 1 | 23 | magento2 | 60,457 | <p>Enabling Error reporting in magento2 is little tricky , as magento2 now comes with 3 different modes</p>
<ol>
<li>Default </li>
<li>Developer</li>
<li>Production</li>
</ol>
<p>Magento2 by default install in “default” mode and thats why you dont get the error log at the front-end of the site , that can a viewed at magento error log . You may check the complete details over here <a href="http://devdocs.magento.com/guides/v2.0/config-guide/bootstrap/magento-modes.html">http://devdocs.magento.com/guides/v2.0/config-guide/bootstrap/magento-modes.html</a></p>
<p>How to enable developer mode in Magento2</p>
<p>This is must have if you are a developer and building extension and template for magento2 , magento provide a command for this purpose . Login in to your linux terminal and under magento execute</p>
<pre><code>php bin/magento deploy:mode:set developer
</code></pre>
<p>and it will enable the developer mode under your magento instance for production mode you can set the mode to production or default .</p>
<p>still if you are experiencing in error reporting </p>
<blockquote>
<p>you can give a try by renaming local.xml.sample to local.xml under
pub/errors</p>
</blockquote> |
26,797,739 | Does swift have a trim method on String? | <p>Does swift have a trim method on String? For example:</p>
<pre><code>let result = " abc ".trim()
// result == "abc"
</code></pre> | 26,797,958 | 16 | 1 | null | 2014-11-07 09:12:33.13 UTC | 53 | 2021-01-15 07:02:59.537 UTC | 2016-11-17 18:57:42.03 UTC | null | 611,879 | null | 3,115,587 | null | 1 | 420 | string|swift|trim | 208,187 | <p>Here's how you remove all the whitespace from the beginning and end of a <code>String</code>.</p>
<p><em>(Example tested with <strong>Swift 2.0</strong>.)</em></p>
<pre><code>let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"
</code></pre>
<p><em>(Example tested with <strong>Swift 3+</strong>.)</em></p>
<pre><code>let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"
</code></pre> |
20,220,090 | Undock Chrome Developer Tools | <p>How do I undock the Chrome Developer Tools in Chrome?
Pressing the left bottom corner just moves it to the right side.</p>
<p><a href="https://i.stack.imgur.com/GQGBR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GQGBR.png" alt="Chrome Corner"></a><br>
<sub>(source: <a href="http://jeremistadler.github.io/corner.png" rel="noreferrer">github.io</a>)</sub> </p> | 20,220,142 | 3 | 1 | null | 2013-11-26 14:40:13.95 UTC | 15 | 2019-11-23 18:06:10.533 UTC | 2019-09-09 09:08:48.263 UTC | null | 4,751,173 | null | 451,905 | null | 1 | 202 | google-chrome|google-chrome-devtools | 53,507 | <p>Click the vertical ellipsis button ( ⋮ ) then choose the desired docking option. (the docking option with the red circle around it, is undock)</p>
<p><img src="https://i.stack.imgur.com/LkDhu.png" alt=""></p>
<p>For older version of Chrome, press and hold the corner button</p>
<p><img src="https://i.stack.imgur.com/1h4tF.png" alt=""></p>
<p>You can also undock/dock-to-left/dock-to-right/dock-to-bottom from the Command Menu. Press <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> (Mac) or <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> (Windows, Linux, Chrome OS) to open the Command Menu, then start typing <code>bottom</code>/<code>left</code>/<code>right</code>/<code>undock</code>.</p>
<p><a href="https://i.stack.imgur.com/xvIB6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xvIB6.png" alt="undocking via command menu"></a></p>
<p>DevTools documentation on docking: <a href="https://developers.google.com/web/tools/chrome-devtools/ui#placement" rel="noreferrer">https://developers.google.com/web/tools/chrome-devtools/ui#placement</a></p> |
6,752,237 | Force div to scroll if the text overflows HTML/CSS? | <p>So I have a div tag to sort of draw boxes around various sections, and of course make actual sections. </p>
<p>In one of the sections, there is more text than can be held in the div tag, so I want to for the text within the div tag to have a scroll bar to make it so the text doesn't overflow outside of the box.</p>
<p>How would I do that?</p> | 6,752,254 | 2 | 0 | null | 2011-07-19 18:32:36.037 UTC | 2 | 2013-12-30 12:41:57.19 UTC | null | null | null | null | 763,725 | null | 1 | 10 | css|html|scrollbar | 41,581 | <p>Use the following:</p>
<pre><code>div {
overflow: scroll;
}
</code></pre>
<p>If you want them to scroll only in one direction, you can use the <code>overflow-x</code> and <code>overflow-y</code> properties.</p> |
7,663,343 | Simplest Possible Example to Show GPU Outperform CPU Using CUDA | <p>I am looking for the most concise amount of code possible that can be coded both for a CPU (using g++) and a GPU (using nvcc) for which the GPU consistently outperforms the CPU. Any type of algorithm is acceptable.</p>
<p>To clarify: I'm literally looking for two short blocks of code, one for the CPU (using C++ in g++) and one for the GPU (using C++ in nvcc) for which the GPU outperforms. Preferably on the scale of seconds or milliseconds. The shortest code pair possible.</p> | 7,664,280 | 4 | 9 | null | 2011-10-05 14:56:49.14 UTC | 8 | 2018-01-29 14:59:43.87 UTC | 2011-10-05 15:42:50.13 UTC | null | 130,427 | null | 130,427 | null | 1 | 29 | cuda|g++|nvcc | 25,163 | <p>First off, I'll reiterate my comment: GPUs are high bandwidth, high latency. Trying to get the GPU to beat a CPU for a nanosecond job (or even a millisecond or second job) is completely missing the point of doing GPU stuff. Below is some simple code, but to really appreciate the performance benefits of GPU, you'll need a big problem size to amortize the startup costs over... otherwise, it's meaningless. I can beat a Ferrari in a two foot race, simply because it take some time to turn the key, start the engine and push the pedal. That doesn't mean I'm faster than the Ferrari in any meaningful way.</p>
<p>Use something like this in C++:</p>
<pre><code> #define N (1024*1024)
#define M (1000000)
int main()
{
float data[N]; int count = 0;
for(int i = 0; i < N; i++)
{
data[i] = 1.0f * i / N;
for(int j = 0; j < M; j++)
{
data[i] = data[i] * data[i] - 0.25f;
}
}
int sel;
printf("Enter an index: ");
scanf("%d", &sel);
printf("data[%d] = %f\n", sel, data[sel]);
}
</code></pre>
<p>Use something like this in CUDA/C:</p>
<pre><code> #define N (1024*1024)
#define M (1000000)
__global__ void cudakernel(float *buf)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
buf[i] = 1.0f * i / N;
for(int j = 0; j < M; j++)
buf[i] = buf[i] * buf[i] - 0.25f;
}
int main()
{
float data[N]; int count = 0;
float *d_data;
cudaMalloc(&d_data, N * sizeof(float));
cudakernel<<<N/256, 256>>>(d_data);
cudaMemcpy(data, d_data, N * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(d_data);
int sel;
printf("Enter an index: ");
scanf("%d", &sel);
printf("data[%d] = %f\n", sel, data[sel]);
}
</code></pre>
<p>If that doesn't work, try making N and M bigger, or changing 256 to 128 or 512.</p> |
8,044,221 | Does Apache2 support virtual hosting of subdomains? | <p>Currently my Apache server is set up like so</p>
<pre><code><VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
DocumentRoot /var/www
</VirtualHost>
</code></pre>
<p>The problem is that everything below <code>/var/www</code> is accessible from everywhere else. If I have a web page <code>/var/www/john/bio.html</code>, then that web page could borrow scripts/pictures from <code>var/www/jane/</code></p>
<p>I want to set up my Apache server like so</p>
<pre><code><VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
DocumentRoot /var/www
</VirtualHost>
<VirtualHost *:80>
ServerName www.john.example.com
ServerAlias john.example.com
DocumentRoot /var/www/john
</VirtualHost>
<VirtualHost *:80>
ServerName www.jane.example.com
ServerAlias jane.example.com
DocumentRoot /var/www/jane
</VirtualHost>
</code></pre>
<p>So all the files for user <code>john</code> go in the <code>/var/www/john/</code> folder, and likewise for user <code>jane</code>. Then, with symbolic links turned off (by default), and access only provided from <code>/var/www/user/</code> downwards (again by default), I don't have to worry about <code>john's</code> web page including scripts/images from <code>jane's</code> web page. </p> | 8,045,377 | 1 | 0 | null | 2011-11-07 23:37:58.403 UTC | 11 | 2014-03-18 17:13:36.597 UTC | null | null | null | null | 654,789 | null | 1 | 7 | apache2|subdomain|virtualhost | 32,821 | <p>Using local measures only (<code>/etc/hosts</code> instead of a DNS) I found that this can indeed work.</p>
<p>First, change your <code>/etc/hosts</code> file to have a mapping of your desired website name(s) (<a href="http://www.google.com" rel="nofollow noreferrer">www.example.com</a>), and target IP address (192.168.1.1). I used my local IP address.</p>
<pre><code> IPAddress Hostname Alias
----------- -------------------------- ------------------
192.168.1.1 www.example.com example.com
192.168.1.1 www.john.example.com john.example.com
192.168.1.1 www.jane.example.com jane.example.com
</code></pre>
<p>Your web browser will check your <code>/etc/hosts</code> file <strong>before</strong> looking at the world wide web. </p>
<p>Next go through all your Apache config files (<code>httpd.conf</code>, <code>apache2.conf</code>, <code>ports.conf</code>, <code>conf.d/*</code>) and make sure in <strong>exactly one</strong> file the command <code>NameVirtualHost *:80</code> is issued (it doesn't have to be port <code>:80</code> but if it is issued more than once, you will get <a href="https://serverfault.com/q/1405/99913">this problem</a>). Mine was issued in <code>/etc/apache2/ports.conf</code>, so put yours there if you have to. Finally, update your Apache configuration file (mine was at <code>/etc/apache2/sites-available/default</code>) like so.</p>
<pre><code><VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
DocumentRoot /var/www
</VirtualHost>
<VirtualHost *:80>
ServerName www.john.example.com
ServerAlias john.example.com
DocumentRoot /var/www/john
</VirtualHost>
<VirtualHost *:80>
ServerName www.jane.example.com
ServerAlias jane.example.com
DocumentRoot /var/www/jane
</VirtualHost>
</code></pre>
<p>As a final step, you may need to add the websites to Apache by issuing the below commands (this step is not necessary, if you give all websites into <code>sites-available/default</code> and not into separate files for individual websites).</p>
<pre><code># a2ensite www.example.com
# a2ensite www.john.example.com
# a2ensite www.jane.example.com
</code></pre>
<p>After doing this, <code>john.example.com</code> will go to <code>/var/www/john</code>. That directory will then act as the root directory, and <code>john</code> will no longer have access to <code>www</code>, and, therefore, have no access to <code>/var/www/jane</code>.</p>
<p>Likewise, after doing this, <code>jane.example.com</code> will go to <code>/var/www/jane</code>. That directory will then act as the root directory, and <code>jane</code> will no longer have access to <code>www</code>, and, therefore, have no access to <code>/var/www/john</code>.</p>
<p>With symbolic links turned off --by default-- neither directories will be able to access each other</p> |
1,418,245 | Invoking a script, which has an awk shebang, with parameters (vars) | <p>I have an awk script that I have defined thus:</p>
<pre><code>#!/usr/bin/env awk
BEGIN { if (!len) len = 1; end = start + len }
{ for (i = start; i < end; i++) { print $1 } }
</code></pre>
<p>I have saved it as <code>columns</code> and <code>chmod +x</code>'d it. I want invoke it so that <code>start</code> and <code>end</code> are defined as it traverses over a file. I was thinking this should work:</p>
<pre><code>cat some_file | columns -v start=2
</code></pre>
<p>But it doesn't. Help!</p> | 1,418,292 | 4 | 0 | null | 2009-09-13 17:06:58.01 UTC | 2 | 2019-12-13 21:57:56.003 UTC | 2014-10-14 18:27:18.667 UTC | null | 45,375 | null | 113,019 | null | 1 | 37 | shell|awk|shebang | 14,962 | <p>Try using:</p>
<pre><code>#!/usr/bin/awk -f
</code></pre>
<p>as an interpreter</p> |
1,456,901 | How to wrap an Ant build with Maven? | <p>We use maven for our large-ish product. All of our artifacts are deployed to a shared archiva repository using the maven deploy goal. I am now integrating a third party product that has an ant build. I know how to call ant targets from maven using the antrun plugin, but I'm not sure how to setup the pom in this instance. I don't want maven to actually generate an artifact, but I do want it to pull the artifact that was built by ant when the maven deploy goal is run.</p>
<p>I am planning on having the pom adjacent to build.xml. The pom will use the antrun plugin in the package goal to call the ant target at the appropriate time to build the .war artifact.</p>
<p>Questions:</p>
<p>a) I am creating a .war file but it is created via ant, not Maven, so having a war packaging type in the pom doesn't make sense. What should my packaging type be?</p>
<p>b) How do I cause maven to pull the artifact from my ant output directory for the deploy goal?</p>
<p>c) If there are no good answers to A and B, then are there ant tasks that replicate the maven deploy functionality for getting my .war artifact into the shared repository?</p> | 1,456,976 | 4 | 0 | null | 2009-09-21 21:12:26.227 UTC | 15 | 2019-01-13 01:41:33.82 UTC | 2009-09-21 21:28:32.737 UTC | null | 123,582 | null | 67,598 | null | 1 | 41 | maven-2|ant | 31,444 | <p>You can use the <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" rel="nofollow noreferrer">maven-antrun-plugin</a> to invoke the ant build. Then use the <a href="https://www.mojohaus.org/build-helper-maven-plugin" rel="nofollow noreferrer">build-helper-maven-plugin</a> to attach the jar produced by ant to the project. The attached artifact will be installed/deployed alongside the pom.<br>
If you specify your project with packaging <code>pom</code>, Maven will not conflict with the ant build.</p>
<p>In the example below, the ant build.xml is assumed to be in src/main/ant, have a <code>compile</code> goal, and output to <code>ant-output.jar</code>.</p>
<pre><code><plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<tasks>
<ant antfile="src/main/ant/build.xml" target="compile"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<id>add-jar</id>
<phase>package</phase>
<goals>
<goal>attach-artifact</goal>
</goals>
<configuration>
<artifacts>
<artifact>
<file>${project.build.directory}/ant-output.jar</file>
<type>jar</type>
</artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
</code></pre> |
2,293,498 | Applying a git post-commit hook to all current and future repositories | <p>I've written a Git post-commit hook and it works correctly. However, I want to add this hook to apply to all current (and future) Git repositories I am working on. I tried adding the hook to my <code>~/.git/hooks/</code> directory instead of in the hooks directory in the project directory, however, this did not seem to work.</p>
<p>Is there a way to create global Git hooks that will apply to all repositories on my system (without having to copy them into each project directory)? If not, what would be the best solution going forward -- perhaps a git-init template?</p> | 37,293,198 | 4 | 3 | null | 2010-02-19 01:24:42.103 UTC | 137 | 2021-12-30 01:49:22.857 UTC | 2021-12-30 01:39:16.11 UTC | null | 63,550 | null | 184,609 | null | 1 | 307 | git|hook|githooks | 88,258 | <blockquote>
<p>I want to add this hook to apply to all current (and future) git repositories I am working on</p>
</blockquote>
<p>With git 2.9+ (June 2016), all you would do is:</p>
<pre><code>git config --global core.hooksPath /path/to/my/centralized/hooks
</code></pre>
<p>See "<a href="https://stackoverflow.com/a/37293001/6309">change default git hooks</a>": this has been done to manage centralized hooks.</p> |
2,074,956 | Logo recognition in images | <p>Does anyone know of recent academic work which has been done on logo recognition in images?
Please answer only if you are familiar with this specific subject (I can search Google for "logo recognition" myself, thank you very much).
Anyone who is knowledgeable in computer vision and has done work on object recognition is welcome to comment as well. </p>
<p><strong>Update</strong>:
Please refer to the algorithmic aspects (what approach you think is appropriate, papers in the field, whether it should work(and has been tested) for real world data, efficiency considerations) and not the technical sides (the programming language used or whether it was with OpenCV...)
Work on image indexing and content based image retrieval can also help.</p> | 2,092,456 | 4 | 3 | null | 2010-01-15 21:38:28.717 UTC | 48 | 2018-05-29 12:52:19.493 UTC | 2010-01-18 19:27:39.987 UTC | null | 235,263 | null | 235,263 | null | 1 | 58 | machine-learning|computer-vision|image-recognition | 41,736 | <p>You could try to use local features like SIFT here:
<a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">http://en.wikipedia.org/wiki/Scale-invariant_feature_transform</a></p>
<p>It should work because logo shape is usually constant, so extracted features shall match well.</p>
<p>The workflow will be like this:</p>
<ol>
<li><p>Detect corners (e.g. Harris corner detector) - for Nike logo they are two sharp ends.</p></li>
<li><p>Compute descriptors (like SIFT - 128D integer vector)</p></li>
<li><p>On training stage remember them; on matching stage find nearest neighbours for every feature in the database obtained during training. Finally, you have a set of matches (some of them are probably wrong).</p></li>
<li><p>Seed out wrong matches using RANSAC. Thus you'll get the matrix that describes transform from ideal logo image to one where you find the logo. Depending on the settings, you could allow different kinds of transforms (just translation; translation and rotation; affine transform).</p></li>
</ol>
<p>Szeliski's book has a chapter (4.1) on local features.
<a href="http://research.microsoft.com/en-us/um/people/szeliski/Book/" rel="noreferrer">http://research.microsoft.com/en-us/um/people/szeliski/Book/</a></p>
<p>P.S. </p>
<ol>
<li><p>I assumed you wanna find logos in photos, for example find all Pepsi billboards, so they could be distorted. If you need to find a TV channel logo on the screen (so that it is not rotated and scaled), you could do it easier (pattern matching or something).</p></li>
<li><p>Conventional SIFT does not consider color information. Since logos usually have constant colors (though the exact color depends on lightning and camera) you might want to consider color information somehow.</p></li>
</ol> |
7,452,418 | How can I customize the active admin layout? | <p>I need to customize the active admin layout, but how can I do it?</p> | 7,454,502 | 5 | 0 | null | 2011-09-17 04:24:37.267 UTC | 11 | 2021-01-30 06:44:03.283 UTC | null | null | null | null | 753,891 | null | 1 | 25 | ruby-on-rails|layout|rubygems|activeadmin | 20,876 | <p>When a view is defined in a gem AND in the rails app, the one defined in the Rails app is served. It's a logic priority.</p>
<p>So if you need to override all or some active admin views, you'll have to copy these in your app and change them as you desire.</p> |
7,176,657 | Difference between unsigned and unsigned int in C | <p>Could you please make it clear what the difference is between <code>unsigned</code> and <code>unsigned int</code>? Maybe some example code would be helpful.</p> | 7,176,690 | 5 | 1 | null | 2011-08-24 13:56:33.023 UTC | 8 | 2012-10-19 21:13:34.547 UTC | 2011-08-25 06:46:56.557 UTC | null | 13,295 | null | 286,579 | null | 1 | 44 | c|int|unsigned | 19,399 | <p><code>unsigned</code> is a modifier which can apply to any integral type (<code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, etc.) but on its own it is identical to <code>unsigned int</code>.</p> |
14,141,156 | JPA merge in a RESTful web application with DTOs and Optimistic Locking? | <p>My question is this: <strong><em>Is there ever a role for JPA <code>merge</code> in a stateless web application?</em></strong></p>
<p>There is a lot of discussion on SO about the <code>merge</code> operation in JPA. There is also a <a href="http://blog.xebia.com/2009/03/23/jpa-implementation-patterns-saving-detached-entities/" rel="noreferrer">great article on the subject</a> which contrasts JPA merge via a more manual Do-It-Yourself process (where you find the entity via the entity manager and make your changes).</p>
<p>My application has a rich domain model (ala domain-driven design) that uses the <code>@Version</code> annotation in order to make use of optimistic locking. We have also created DTOs to send over the wire as part of our RESTful web services. The creation of this DTO layer also allows us to send to the client everything it needs and nothing it doesn't.</p>
<p>So far, I understand this is a fairly typical architecture. My question is about the service methods that need to UPDATE (i.e. HTTP PUT) existing objects. In this case we have these two approaches 1) JPA Merge, and 2) DIY. </p>
<p>What I don't understand is how JPA merge can even be considered an option for handling updates. Here's my thinking and I am wondering if there is something I don't understand:</p>
<p>1) In order to properly create a detached JPA entity from a wire DTO, the version number must be set correctly...else an OptimisticLockException is thrown. But the JPA spec says:</p>
<blockquote>
<p>An entity may access the state of its version field or property or
export a method for use by the application to access the version, but
must not modify the version value[30]. Only the persistence provider
is permitted to set or update the value of the version attribute in
the object.</p>
</blockquote>
<p>2) Merge doesn't handle bi-directional relationships ... the back-pointing fields always end up as null.</p>
<p>3) If any fields or data is missing from the DTO (due to a partial update), then the JPA merge will delete those relationships or null-out those fields. Hibernate can handle partial updates, but not JPA merge. DIY can handle partial updates.</p>
<p>4) The first thing the merge method will do is query the database for the entity ID, so there is no performance benefit over DIY to be had.</p>
<p>5) In a DYI update, we load the entity and make the changes according to the DTO -- there is no call to <code>merge</code> or to <code>persist</code> for that matter because the JPA context implements the unit-of-work pattern out of the box. </p>
<p><strong><em>Do I have this straight?</em></strong></p>
<p><strong>Edit:</strong></p>
<p>6) Merge behavior with regards to lazy loaded relationships can <a href="https://hibernate.onjira.com/browse/HHH-4135" rel="noreferrer">differ amongst providers</a>.</p> | 14,141,709 | 2 | 0 | null | 2013-01-03 14:49:20.153 UTC | 11 | 2017-08-31 19:02:34.83 UTC | 2014-02-07 14:10:05.79 UTC | null | 218,028 | null | 218,028 | null | 1 | 17 | java|rest|jpa|web|dto | 4,414 | <p>Using Merge does require you to either send and receive a complete representation of the entity, or maintain server side state. For trivial CRUD-y type operations, it is easy and convenient. I have used it plenty in stateless web apps where there is no meaningful security hazard to letting the client see the entire entity. </p>
<p>However, if you've already reduced operations to only passing the immediately relevant information, then you need to also manually write the corresponding services.</p>
<p>Just remember that when doing your 'DIY' update you still need to pass a Version number around on the DTO and manually compare it to the one that comes out of the database. Otherwise you don't get the Optimistic Locking that spans 'user think-time' that you would have if you were using the simpler approach with merge.</p>
<ol>
<li><p>You can't change the version on an entity created by the provider, but when you have made your own instance of the entity class with the <code>new</code> keyword it is fine and expected to set the version on it.</p></li>
<li><p>It will make the persistent representation match the in-memory representation you provide, this can include making things null. Remember when an object is merged that object is supposed to be discarded and replaced with the one returned by merge. You are not supposed to merge an object and then continue using it. Its state is not defined by the spec.</p></li>
<li><p>True.</p></li>
<li><p>Most likely, as long as your DIY solution is also using the entity ID and not an arbitrary query. (There are other benefits to using the 'find' method over a query.)</p></li>
<li><p>True.</p></li>
</ol> |
13,847,936 | Plot random effects from lmer (lme4 package) using qqmath or dotplot: How to make it look fancy? | <p>The qqmath function makes great caterpillar plots of random effects using the output from the lmer package. That is, qqmath is great at plotting the intercepts from a hierarchical model with their errors around the point estimate. An example of the lmer and qqmath functions are below using the built-in data in the lme4 package called Dyestuff. The code will produce the hierarchical model and a nice plot using the ggmath function.</p>
<pre><code>library("lme4")
data(package = "lme4")
# Dyestuff
# a balanced one-way classiï¬cation of Yield
# from samples produced from six Batches
summary(Dyestuff)
# Batch is an example of a random effect
# Fit 1-way random effects linear model
fit1 <- lmer(Yield ~ 1 + (1|Batch), Dyestuff)
summary(fit1)
coef(fit1) #intercept for each level in Batch
# qqplot of the random effects with their variances
qqmath(ranef(fit1, postVar = TRUE), strip = FALSE)$Batch
</code></pre>
<p>The last line of code produces a really nice plot of each intercept with the error around each estimate. But formatting the qqmath function seems to be very difficult, and I've been struggling to format the plot. I've come up with a few questions that I cannot answer, and that I think others could also benefit from if they are using the lmer/qqmath combination: </p>
<ol>
<li>Is there a way to take the qqmath function above and add a few
options, such as, making certain points empty vs. filled-in, or
different colors for different points? For example, can you make the points for A,B, and C of the Batch variable filled, but then the rest of the points empty?</li>
<li>Is it possible to add axis labels for each point (maybe along the
top or right y axis, for example)?</li>
<li>My data has closer to 45 intercepts, so it is possible to add
spacing between the labels so they do not run into each other?
MAINLY, I am interested in distinguishing/labeling between points on the
graph, which seems to be cumbersome/impossible in the ggmath function.</li>
</ol>
<p>So far, adding any additional option in the qqmath function produce errors where I would not get errors if it was a standard plot, so I'm at a loss.</p>
<p>Also, if you feel there is a better package/function for plotting intercepts from lmer output, I'd love to hear it! (for example, can you do points 1-3 using dotplot?)</p>
<p><strong>EDIT:</strong> I'm also open to an alternative dotplot if it can be reasonably formatted. I just like the look of a ggmath plot, so I'm starting with a question about that.</p> | 13,921,774 | 4 | 0 | null | 2012-12-12 20:20:21.163 UTC | 44 | 2020-04-06 07:39:56.817 UTC | 2019-08-29 08:57:16.46 UTC | null | 680,068 | null | 1,030,771 | null | 1 | 39 | r|ggplot2|lme4|random-effects | 43,891 | <p>One possibility is to use library <code>ggplot2</code> to draw similar graph and then you can adjust appearance of your plot.</p>
<p>First, <code>ranef</code> object is saved as <code>randoms</code>. Then variances of intercepts are saved in object <code>qq</code>.</p>
<pre><code>randoms<-ranef(fit1, postVar = TRUE)
qq <- attr(ranef(fit1, postVar = TRUE)[[1]], "postVar")
</code></pre>
<p>Object <code>rand.interc</code> contains just random intercepts with level names.</p>
<pre><code>rand.interc<-randoms$Batch
</code></pre>
<p>All objects put in one data frame. For error intervals <code>sd.interc</code> is calculated as 2 times square root of variance.</p>
<pre><code>df<-data.frame(Intercepts=randoms$Batch[,1],
sd.interc=2*sqrt(qq[,,1:length(qq)]),
lev.names=rownames(rand.interc))
</code></pre>
<p>If you need that intercepts are ordered in plot according to value then <code>lev.names</code> should be reordered. This line can be skipped if intercepts should be ordered by level names.</p>
<pre><code>df$lev.names<-factor(df$lev.names,levels=df$lev.names[order(df$Intercepts)])
</code></pre>
<p>This code produces plot. Now points will differ by <code>shape</code> according to factor levels.</p>
<pre><code>library(ggplot2)
p <- ggplot(df,aes(lev.names,Intercepts,shape=lev.names))
#Added horizontal line at y=0, error bars to points and points with size two
p <- p + geom_hline(yintercept=0) +geom_errorbar(aes(ymin=Intercepts-sd.interc, ymax=Intercepts+sd.interc), width=0,color="black") + geom_point(aes(size=2))
#Removed legends and with scale_shape_manual point shapes set to 1 and 16
p <- p + guides(size=FALSE,shape=FALSE) + scale_shape_manual(values=c(1,1,1,16,16,16))
#Changed appearance of plot (black and white theme) and x and y axis labels
p <- p + theme_bw() + xlab("Levels") + ylab("")
#Final adjustments of plot
p <- p + theme(axis.text.x=element_text(size=rel(1.2)),
axis.title.x=element_text(size=rel(1.3)),
axis.text.y=element_text(size=rel(1.2)),
panel.grid.minor=element_blank(),
panel.grid.major.x=element_blank())
#To put levels on y axis you just need to use coord_flip()
p <- p+ coord_flip()
print(p)
</code></pre>
<p><img src="https://i.stack.imgur.com/BrJcz.jpg" alt="enter image description here"></p> |
14,227,363 | Using turbolinks in a Rails link_to | <p>Just wondering whether there's a way to use turbolinks directly in a rails link_to helper, a quick bit of googling didn't uncover anything of note, here's the type of thing I've tried to no avail.</p>
<pre><code><%= link_to 'Giraffe', giraffe_path(@giraffe), :data-no-turbolink => 'true' %>
<%= link_to 'Giraffe', giraffe_path(@giraffe), :data { :no-turbolink => 'true'} %>
</code></pre>
<p>I know you can do it in regular links like this</p>
<pre><code><a data-no-turbolink='true' href="/giraffe-130">Giraffe</a>
</code></pre>
<p>Right now I'm just including the attribute on elements that surround the link such as lis or divs.</p>
<p>Thanks in advance. </p> | 14,310,416 | 6 | 0 | null | 2013-01-09 02:23:29.93 UTC | 11 | 2018-12-14 17:57:45.83 UTC | 2013-01-09 02:30:14.643 UTC | null | 940,492 | null | 940,492 | null | 1 | 45 | ruby-on-rails-3.2|turbolinks|ruby-on-rails-4 | 38,079 | <p><strong>Edit for Rails 5+:</strong> @ManishShrivastava correctly pointed out the different syntax needed for Rails 5 as shown in <a href="https://stackoverflow.com/a/37999169/4299353">Joseph's answer</a>.</p>
<p><code><%= link_to('Giraffe', @giraffe, data: { turbolinks: false }) %></code></p>
<p><strong>For Rails 4 and below</strong></p>
<p>Originally I thought you needed to use the hash rocket syntax for the symbol but that isn't the case. You can use a <code>data:</code> hash and inside that hash any symbols using underscores <code>_</code> will be converted to dashes <code>-</code>.</p>
<p>I think most Rails developers would prefer to see the following (including myself now that I know better):</p>
<p><code><%= link_to('Giraffe', @giraffe, data: { no_turbolink: true }) %></code></p>
<p>But the following also works:</p>
<p><code><%= link_to('Giraffe', @giraffe, 'data-no-turbolink' => true) %></code></p> |
14,290,100 | When debugging autolayout what is the meaning of the autoresizing mask strings such as h=--& v=-&-? | <p>I guess they must refer to the struts and springs model but I can't find any mention of them. When you <code>NSLog</code> constraint they sometimes appear as the description string of the undocumented class <code>NSAutoresizingMaskLayoutConstraint</code>. I have noticed at least 3 different types: <code>h=---</code>, <code>h=--&</code>, <code>h=-&-</code> with horizontal and vertical version.</p>
<p>They turn up a lot when debugging over constrained layouts.</p> | 14,408,985 | 3 | 4 | null | 2013-01-12 04:02:57.3 UTC | 19 | 2015-05-18 03:54:12.867 UTC | null | null | null | null | 92,610 | null | 1 | 53 | cocoa|autolayout | 10,719 | <p>If you specify autoresizing masks instead of constraints, or specify no constraints at all, then the view will have NSAutoResizingMaskLayoutConstraint constraints as opposed to NSLayoutConstraints. If you set <code>translatesAutoresizingMaskIntoConstraints</code> to <code>NO</code>, then these constraints do not appear. You can't mix and match on a single view, or you get unsatisfiable constraint errors.</p>
<p>I set up a quick test project with various combinations of autoresizing masks and the logging format is pretty straightforward. </p>
<ul>
<li><code>h=</code> or <code>v=</code> indicates that we are talking about contraints in the horizontal or vertical direction.</li>
<li><code>-</code> indicates a fixed size</li>
<li><code>&</code> indicates a flexible size</li>
<li>The order of symbols represents margin, dimension, margin</li>
</ul>
<p>Therefore, <code>h=&-&</code> means you have flexible left and right margins and a fixed width, <code>v=-&-</code> means fixed top and bottom margins and flexible height, and so forth. </p> |
14,327,104 | Is there any way for "position:absolute" div to retain relative width? | <p>Let's say I have two divs, one inside the other, like so:</p>
<pre><code><html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="width:100%">
</div>
</div>
</body>
</html>
</code></pre>
<p>Right now, the inner div has a width of 100% of 50% of the screen size, or 50% of the screen size. If I were to change the inner div to position absolute, like this:</p>
<pre><code><html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="position:absolute;width:100%">
</div>
</div>
</body>
</html>
</code></pre>
<p>In this case the inner div takes up 100% of the screen space, because its position is set to absolute.</p>
<p>My question is this: Is there any way to maintain relative width of the inner div while its position is set to absolute?</p> | 14,327,156 | 3 | 0 | null | 2013-01-14 21:33:31.577 UTC | 7 | 2021-10-16 12:18:46.733 UTC | 2019-05-01 16:51:32.713 UTC | null | 4,475,011 | null | 634,324 | null | 1 | 54 | html|css|position|absolute | 66,324 | <p>Add <strong>position:relative</strong> to your outer div.</p>
<p><em>update</em>: It works because positions in <code>position: absolute</code> are relative to the first parent that has some positioning (other than static). In this case there was no such container, so it uses the page.</p> |
43,270,793 | Angular 2 how to display .pdf file | <p>I have an angular2 app, where I want the user to be able to download and open a pdf file in the browser.</p>
<p>Is there an angular2 module or component that I can use?</p> | 43,270,950 | 10 | 2 | null | 2017-04-07 06:05:52.603 UTC | 1 | 2021-08-19 08:26:49.44 UTC | 2019-08-27 13:32:18.393 UTC | null | 3,995,261 | null | 4,221,619 | null | 1 | 31 | angular|pdf | 120,618 | <p>Have you taken a look at this module <a href="https://www.npmjs.com/package/ng2-pdf-viewer" rel="noreferrer">https://www.npmjs.com/package/ng2-pdf-viewer</a>?</p>
<p>remember to declare it in the module like so</p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { PdfViewerComponent } from 'ng2-pdf-viewer';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
PdfViewerComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre> |
9,022,750 | Running emulator after building Android from source | <p>I am able to pull down the latest android source code into a Ubuntu virtual machine 32-bit (Host: Windows 7 64-bit). The build completes without any errors.</p>
<p>Then I tried to follow <a href="http://source.android.com/source/building.html" rel="noreferrer">these instructions</a>, where it mentions that I should run the emulator on the root of my source code. However, when I tried that, I get an error stating that this command is not found.</p>
<p>So I went to the folder <code>out/host/linux-x86/bin</code> and I found out that there are couple files for <code>emulator*</code>:</p>
<ul>
<li><code>emulator</code></li>
<li><code>emulator-arm</code></li>
<li><code>emulator_renderer</code></li>
<li><code>emulator-ui</code></li>
<li><code>emulator-x86</code></li>
</ul>
<p>When I typed the <code>emulator</code> and <code>emulator-x86</code> here, it also doesn't work. Here is the error I'm getting:</p>
<pre><code>xxxx/out/host/linux-x86/bin$ ./emulator-x86
emulator: ERROR: You did not specify a virtual device name, and the system
directory could not be found.
If you are an Android SDK user, please use '@<name>' or '-avd <name>'
to start a given virtual device (see -help-avd for details).
Otherwise, follow the instructions in -help-disk-images to start the emulator
</code></pre>
<p>So when I run <code>./emulator-x86 -help-disk-images</code>, I see the following:</p>
<pre><code>If you are building from the Android build system, you should
have ANDROID_PRODUCT_OUT defined in your environment, and the
emulator shall be able to pick-up the right image files automatically.
See -help-build-images for more details.
</code></pre>
<p>I built this myself, so I would think that <code>ANDROID_PRODUCT_OUT</code> is set in my environment variables, but I don't see it. So I think that I should run some other shell script to get that set.</p>
<p>I looked at the <code>img</code> files, I saw couple at the location <code>out/target/product/generic</code>:</p>
<ul>
<li><code>ramdisk.img</code></li>
<li><code>system.img</code></li>
<li><code>userdata.img</code></li>
</ul>
<p>Could anyone shed some light on this and assist me on what I should do next? I am new to Android and I did some research on this but I couldn't find any similar issues.</p> | 9,023,141 | 10 | 1 | null | 2012-01-26 17:46:19.083 UTC | 25 | 2019-12-04 16:02:26.92 UTC | 2012-11-07 09:17:46.33 UTC | null | 154,306 | null | 702,804 | null | 1 | 28 | android|android-emulator|linux-kernel | 51,618 | <p>I do not know for which product you do your build but to run emulator you can use the following command:</p>
<blockquote>
<p>out/host/linux-x86/bin/emulator -sysdir out/target/product/generic/ -system out/target/product/generic/system.img -ramdisk out/target/product/generic/ramdisk.img -data out/target/product/generic/userdata.img -kernel prebuilt/android-arm/kernel/kernel-qemu -sdcard sdcard.img -skindir sdk/emulator/skins -skin WVGA800 -scale 0.7 -memory 512 -partition-size 1024</p>
</blockquote>
<p>Just copy it into .sh file into the root of your Android source folder and run this file. Or you can just run it but you should chdir to your Android source folder root at first.</p>
<p>And do not forget to create an sdcard image in the root folder with command <code>mksdcard</code>.</p> |
58,636,087 | Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float) | <p>Continuation from previous question: <a href="https://stackoverflow.com/questions/58635521/tensorflow-typeerror-int-object-is-not-iterable/58635565#58635583">Tensorflow - TypeError: 'int' object is not iterable</a></p>
<p>My training data is a list of lists each comprised of 1000 floats. For example, <code>x_train[0] =</code></p>
<pre><code>[0.0, 0.0, 0.1, 0.25, 0.5, ...]
</code></pre>
<p>Here is my model:</p>
<pre><code>model = Sequential()
model.add(LSTM(128, activation='relu',
input_shape=(1000, 1), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3, validation_data=(x_test, y_test))
</code></pre>
<p>Here is the error I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\bencu\Desktop\ProjectFiles\Code\Program.py", line 88, in FitModel
model.fit(x_train, y_train, epochs=3, validation_data=(x_test, y_test))
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 728, in fit
use_multiprocessing=use_multiprocessing)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 224, in fit
distribution_strategy=strategy)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 547, in _process_training_inputs
use_multiprocessing=use_multiprocessing)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 606, in _process_inputs
use_multiprocessing=use_multiprocessing)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py", line 479, in __init__
batch_size=batch_size, shuffle=shuffle, **kwargs)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py", line 321, in __init__
dataset_ops.DatasetV2.from_tensors(inputs).repeat()
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py", line 414, in from_tensors
return TensorDataset(tensors)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py", line 2335, in __init__
element = structure.normalize_element(element)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\util\structure.py", line 111, in normalize_element
ops.convert_to_tensor(t, name="component_%d" % i))
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1184, in convert_to_tensor
return convert_to_tensor_v2(value, dtype, preferred_dtype, name)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1242, in convert_to_tensor_v2
as_ref=False)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1296, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\tensor_conversion_registry.py", line 52, in _default_conversion_function
return constant_op.constant(value, dtype, name=name)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 227, in constant
allow_broadcast=True)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 235, in _constant_impl
t = convert_to_eager_tensor(value, ctx, dtype)
File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 96, in convert_to_eager_tensor
return ops.EagerTensor(value, ctx.device_name, dtype)
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).
</code></pre>
<p>I've tried googling the error myself, I found something about using the <code>tf.convert_to_tensor</code> function. I tried passing my training and testing lists through this but the function won't take them.</p> | 58,667,409 | 15 | 4 | null | 2019-10-31 02:18:03.363 UTC | 24 | 2022-06-21 16:24:10.297 UTC | 2021-08-12 17:11:04.373 UTC | null | 3,750,257 | null | 6,748,145 | null | 1 | 124 | python|tensorflow|keras|lstm | 284,158 | <p><strong>TL;DR</strong> Several possible errors, most fixed with <code>x = np.asarray(x).astype('float32')</code>.</p>
<p>Others may be faulty data preprocessing; ensure everything is <em>properly formatted</em> (categoricals, nans, strings, etc). Below shows what the model expects:</p>
<pre class="lang-py prettyprint-override"><code>[print(i.shape, i.dtype) for i in model.inputs]
[print(o.shape, o.dtype) for o in model.outputs]
[print(l.name, l.input_shape, l.dtype) for l in model.layers]
</code></pre>
<hr>
<p>The problem's rooted in using <em>lists</em> as inputs, as opposed to Numpy arrays; Keras/TF doesn't support former. A simple conversion is: <code>x_array = np.asarray(x_list)</code>.</p>
<p>The next step's to ensure data is fed in expected format; for LSTM, that'd be a 3D tensor with dimensions <code>(batch_size, timesteps, features)</code> - or equivalently, <code>(num_samples, timesteps, channels)</code>. Lastly, as a debug pro-tip, <em>print ALL the shapes</em> for your data. Code accomplishing all of the above, below:</p>
<pre class="lang-py prettyprint-override"><code>Sequences = np.asarray(Sequences)
Targets = np.asarray(Targets)
show_shapes()
Sequences = np.expand_dims(Sequences, -1)
Targets = np.expand_dims(Targets, -1)
show_shapes()
</code></pre>
<pre class="lang-py prettyprint-override"><code># OUTPUTS
Expected: (num_samples, timesteps, channels)
Sequences: (200, 1000)
Targets: (200,)
Expected: (num_samples, timesteps, channels)
Sequences: (200, 1000, 1)
Targets: (200, 1)
</code></pre>
<hr>
<p>As a bonus tip, I notice you're running via <code>main()</code>, so your IDE probably lacks a Jupyter-like cell-based execution; I strongly recommend the <a href="https://www.spyder-ide.org/" rel="noreferrer">Spyder IDE</a>. It's as simple as adding <code># In[]</code>, and pressing <code>Ctrl + Enter</code> below:</p>
<img src="https://i.stack.imgur.com/AltOS.png" height="69">
<hr>
<p><strong>Function used</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def show_shapes(): # can make yours to take inputs; this'll use local variable values
print("Expected: (num_samples, timesteps, channels)")
print("Sequences: {}".format(Sequences.shape))
print("Targets: {}".format(Targets.shape))
</code></pre> |
35,239,880 | Find all Bluetooth devices (headsets, phones etc) nearby, without forcing the devices in discoverable mode | <p><strong>My goal:</strong></p>
<p>To detect all nearby Bluetooth devices(phones, headsets, etc.) from my Android application.</p>
<p>Here's a nice example from <a href="https://github.com/googlearchive/android-BluetoothChat" rel="nofollow noreferrer">developer.android.com</a> which discovers the Bluetooth devices nearby along with the list of already paired devices. </p>
<p><strong>My situation:</strong></p>
<p>I had two Bluetooth headsets turned on and they were not being detected after a successful Bluetooth scan! So I dig into the problem and somewhere found that the Bluetooth headset needs to be switched to pairing mode in case of being detected by android. </p>
<p>To switch the headsets in pairing mode, I had to long-press the power button while turning them on. And yes, finally, the Bluetooth headsets are now detected by the scan from my application.</p>
<p><strong>My problem:</strong></p>
<p>I want my headsets will be detected automatically without switching them in pairing mode. Couldn't find a way to detect all nearby Bluetooth devices which are turned on.</p> | 36,984,988 | 1 | 3 | null | 2016-02-06 10:21:27.153 UTC | 8 | 2020-05-11 16:24:41.48 UTC | 2020-05-11 16:24:41.48 UTC | null | 3,145,960 | null | 3,145,960 | null | 1 | 2 | android|bluetooth|bluetooth-lowenergy|android-bluetooth | 42,814 | <p>So, here's all I found after reading blogs, threads, documentations, SO answers etc. regarding Android's bluetooth discovery. Thought this might be useful to post my findings here. </p>
<p>So before someone starts reading, I want to clarify that, <strong>I could not find any way to detect a bluetooth device nearby which is turned on but not discoverable.</strong> </p>
<h1>Detect all nearby Bluetooth devices</h1>
<p>My primary target is to detect all nearby bluetooth devices. To do so, we have a <code>BluetoothAdapter</code> class in Android which has a <code>startDiscovery</code> function to scan for bluetooth devices nearby. Hence, this doesn't serves my purpose, as the bluetooth devices need to be discoverable to be detected by a bluetooth scan by Android. What I want is to detect all Bluetooth devices nearby without forcing them to be discoverable. I started searching for a solution to achieve this goal. </p>
<p>I started with studying <a href="https://en.wikipedia.org/wiki/List_of_Bluetooth_protocols" rel="noreferrer">Bluetooth protocols</a> and found the underlying protocols used for bluetooth detection, connection and pairing. For Android, I found no API to discover/detect BT devices which are turned on but not in discoverable mode.</p>
<h3>Bluetooth devices with class 0x00 are ignored</h3>
<p>Digging into this detection problem without forcing the bluetooth devices to discoverable mode lead us to a point where we found Bluetooth device which advertises itself as <code>class 0×00</code> is ignored automatically while running scan for nearby BT devices. This problem is stated in several places. Here I have listed some. </p>
<ol>
<li><a href="https://stackoverflow.com/questions/4215398/bluetooth-device-not-discoverable">Stackoverflow question</a></li>
<li><a href="https://groups.google.com/forum/#!topic/android-developers/6dgkxYKsRBg" rel="noreferrer">Google group</a></li>
<li><a href="http://comments.gmane.org/gmane.comp.handhelds.android.devel/111691" rel="noreferrer">Discuss DEV</a></li>
<li><a href="https://www.reddit.com/r/Android/comments/hao6p/my_experience_with_htc_support_eu_anyone_has/" rel="noreferrer">Found in HTC devices</a></li>
</ol>
<p>I tried to find a work-around of this problem and yes, I found one, though the documentation and reviews along with this work-around says, it doesn't work for all kind of Android devices. Anyway, the alternate scan is the same as the default BT scan, but it does some additional works. It reads the Android log after a successful BT scan and check if there's any BT device is skipped through out the operation. This is a simple hack described <a href="http://zornsoftware.codenature.info/blog/category/bluetooth" rel="noreferrer">here </a>. There's a google group discussing about the same work-around <a href="https://groups.google.com/forum/#!topic/ioio-users/F7V_rfPaNl8" rel="noreferrer">here</a>.</p>
<p>The work-around above doesn't solve my problem either. Bluetooth headsets need to be discoverable for being detected by a BT scan. They are not skipped while Android is scanning nearby BT devices. They are simply not found.</p>
<h3>Bluetooth Page Scan</h3>
<p>However, I started searching for a solution again and found something interesting again! This is from another <a href="https://stackoverflow.com/questions/15820829/detect-hidden-not-visible-bluetooth-device-on-mobile/15822738#15822738">Stackoverflow answer</a> which says, <strong>It is possible to know whether a bluetooth device is around, even if he is in an undiscoverable mode, by knowing his full MAC address in the first place</strong>. I'm quoting again from his answer for future reference,</p>
<blockquote>
<p>The technique is to try a PAGE request, sending all the 6 bytes that are composing the seeked Bluetooth host MAC identifier. A PAGE request allows one to connect with a Bluetooth slave when knowing his BT ADDR. Devices that are in undiscoverable mode does not respond to inquiry scan (device discovery intent), but they do respond to page scan which is used by a device wanting to connect to an another previously known device.</p>
</blockquote>
<p>I found hope and started searching for, how can we initiate a page scan in Android but failed this time too. Couldn't find any kind of APIs to initiate page scan. From Android documentation of <code>BluetoothAdapter</code> class, I came to know that, when a BT scan starts,</p>
<blockquote>
<p>This usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name.</p>
</blockquote>
<p>There is an indication of page scan in Android documentation, but, surprisingly, there is no other documentation regarding page scan anywhere. I put a <a href="https://stackoverflow.com/questions/35536940/how-to-initiate-a-page-scan-for-bluetooth-in-android">Stackoverflow question</a> for inquiry.</p>
<h3>Can we "fool" android by appending a list of BTIDs to the "already paired" list?</h3>
<p>No, I did not find any way to do so. I read about how Android's bluetooth pairing works. Here is a <a href="https://stackoverflow.com/questions/27360338/how-does-bluetooth-pairing-work/27596841#27596841">nice flow diagram along with detailed reading manual</a>. We were trying to use Android's hidden APIs and could use some hidden APIs using Reflection. Then we started to look for hidden APIs which we might use to serve my purpose. But, unfortunately, we failed to find any hidden APIs to add a BT device in Android's already paired list programatically.</p>
<p>Here are some helpful links to check for bluetooth pairing, hidden APIs and how to invoke them via reflection for future reference.</p>
<ol>
<li><a href="https://stackoverflow.com/questions/5764958/android-bluetooth-how-to-initiate-pairing">How to initiate pairing</a></li>
<li><a href="http://wiresareobsolete.com/2010/11/android-bluetooth-rfcomm/" rel="noreferrer">How to use reflection to work with Android's hidden APIs</a></li>
<li><a href="https://groups.google.com/forum/#!topic/android-developers/wdiofHRYvH0" rel="noreferrer">Here's a google group discussion I followed, some people are facing the same problem we've here</a></li>
</ol>
<p>So I could pair a BT device when it was in discoverable mode and was not in the paired list in Android. In my case, I used a bluetooth headset. It was turned on and put in discoverable mode. The BT Address (MAC address) of the headset was known. So I called the function <code>createBond</code> from my code using reflection and it worked perfectly. The device was added in the "already-paired" list of Android successfully. While roaming around for solutions to serve my purpose I found something interesting...</p>
<h3>Interesting observation about already paired devices</h3>
<p>I found that, android preserves a previously paired device in its memory even if I remove it from the already-paired list. Let us share a case study along with the findings here for a better understanding. In my case the headset was paired previously. </p>
<ol>
<li>Unpaired/forget the headset from Android</li>
<li>Then turned the headset off.</li>
<li>Then started scanning for bluetooth devices nearby</li>
<li>Of course, the headset was not found</li>
<li>But we went through the Android logs and found that, Android remembers the change of bonding state (paring state) of that headset. </li>
<li>It scanned for the previously bonded headphone and reported remote device is down</li>
</ol>
<p>Here is the log that printed along with the MAC address of the headset we paired before and then unpaired. </p>
<pre><code>PREV_BOND_STATE = 11 // BOND_BONDING (BluetoothDevice.java)
BOND_STATE = 10 // BOND_NONE
REASON = 4 // UNBOND_REASON_REMOTE_DEVICE_DOWN
</code></pre>
<p>Then again, I ran the same test, but this time we turned the bluetooth headset on (not discoverable). The headset was not found in this case too, but the interesting thing is, this time a different log was printed. </p>
<pre><code>PREV_BOND_STATE = 11 // BOND_BONDING (BluetoothDevice.java)
BOND_STATE = 10 // BOND_NONE
REASON = 2 // UNBOND_REASON_AUTH_CANCELLED
</code></pre>
<p>The <code>REASON</code> is changed and hence I can understand Android tried to connect with the bluetooth headset. The headset was not in discoverable mode, yet Android could find it and tried to connect with it as it was in paired list before. </p>
<p>This log was printed while a bluetooth scan was running with adding <code>ACTION_BOND_STATE_CHANGED</code> action with <code>intent.addAction</code>.</p>
<h3>Can Android be used as beacon?</h3>
<p>Yes, but in that case Android needs to advertise itself as a BLE too. This is what new in Android and not all devices support this functionality till now. Here is a <a href="http://altbeacon.github.io/android-beacon-library/beacon-transmitter-devices.html" rel="noreferrer">list of devices</a> which support Bluetooth LE advertisement capability. But, as Bluetooth LE advertisement has a very low power consumption along with a high performance, I think this will be the next big thing in Android.</p>
<p>Here are some helpful links for future research. </p>
<ul>
<li><a href="https://stackoverflow.com/questions/19602913/can-an-android-device-act-as-an-ibeacon/19606979#19606979">Can Android act as an iBeacon?</a></li>
<li><a href="https://stackoverflow.com/questions/34424479/can-an-android-4-4-device-act-as-an-ibeacon">Android 4.4 as an iBeacon</a></li>
<li><a href="https://github.com/AltBeacon/android-beacon-library/blob/master/src/main/java/org/altbeacon/beacon/BeaconTransmitter.java" rel="noreferrer">Android Beacon Library</a></li>
<li><a href="https://github.com/AltBeacon/android-beacon-library" rel="noreferrer">AltBeacon library in Github</a></li>
<li><a href="http://altbeacon.github.io/android-beacon-library/" rel="noreferrer">Learning more about AltBeacon</a></li>
<li><a href="https://web.archive.org/web/20140630050633/http://developer.radiusnetworks.com/2014/06/24/making-an-ibeacon-using-androids-hidden-apis.html" rel="noreferrer">Rooting your phone to advertise</a></li>
</ul>
<h3>Helpful functions and libraries for bluetooth operations</h3>
<ul>
<li><a href="https://github.com/giladHaimov/BTWiz" rel="noreferrer">Helpful library for easy Bluetooth operations, named BTWiz</a>.</li>
<li><a href="https://stackoverflow.com/questions/22001271/android-ndk-accessing-native-bluetooth-functions-bluedroid">Bluedroid - native bluetooth functions</a></li>
<li><a href="https://stackoverflow.com/questions/12723852/are-there-native-apis-for-communicaion-over-bluetooth-in-androidif-so-where-do">More about native APIs for bluetooth communication</a></li>
</ul> |
830,673 | Instantiating Custom Class from NSDictionary | <p>I have a feeling that this is stupid question, but I'll ask anyway...</p>
<p>I have a collection of <code>NSDictionary</code> objects whose key/value pairs correspond to a custom class I've created, call it <code>MyClass</code>. Is there an easy or "best practice" method for me to basically do something like <code>MyClass * instance = [</code>map <code>NSDictionary</code> properties to <code>MyClass</code> <code>];</code>? I have a feeling I need to do something with <code>NSCoding</code> or <code>NSKeyedUnarchiver</code>, but rather than stumble through it on my own, I figure someone out there might be able to point me in the right direction.</p> | 831,076 | 5 | 0 | null | 2009-05-06 17:03:53.603 UTC | 16 | 2017-01-30 13:06:38.093 UTC | null | null | null | null | 89,170 | null | 1 | 20 | iphone|objective-c|collections|nsdictionary | 10,393 | <p>The -setValuesForKeysWithDictionary: method, along with -dictionaryWithValuesForKeys:, is what you want to use.</p>
<p>Example:</p>
<pre><code>// In your custom class
+ (id)customClassWithProperties:(NSDictionary *)properties {
return [[[self alloc] initWithProperties:properties] autorelease];
}
- (id)initWithProperties:(NSDictionary *)properties {
if (self = [self init]) {
[self setValuesForKeysWithDictionary:properties];
}
return self;
}
// ...and to easily derive the dictionary
NSDictionary *properties = [anObject dictionaryWithValuesForKeys:[anObject allKeys]];
</code></pre> |
1,051,464 | Excel interop: _Worksheet or Worksheet? | <p>I'm currently writing about dynamic typing, and I'm giving an example of Excel interop. I've hardly done any Office interop before, and it shows. The <a href="http://msdn.microsoft.com/en-us/library/dd264733(VS.100).aspx" rel="noreferrer">MSDN Office Interop tutorial</a> for C# 4 uses the <code>_Worksheet</code> interface, but there's also a <code>Worksheet</code> interface. I've no idea what the difference is.</p>
<p>In my absurdly simple demo app (shown below) either works fine - but if best practice dictates one or the other, I'd rather use it appropriately.</p>
<pre><code>using System;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
class DynamicExcel
{
static void Main()
{
var app = new Excel.Application { Visible = true };
app.Workbooks.Add();
// Can use Excel._Worksheet instead here. Which is better?
Excel.Worksheet workSheet = app.ActiveSheet;
Excel.Range start = workSheet.Cells[1, 1];
Excel.Range end = workSheet.Cells[1, 20];
workSheet.get_Range(start, end).Value2 = Enumerable.Range(1, 20)
.ToArray();
}
}
</code></pre>
<p>I'm trying to avoid doing a full deep-dive into COM or Office interoperability, just highlighting the new features of C# 4 - but I don't want to do anything really, really dumb.</p>
<p>(There may be something really, really dumb in the code above as well, in which case please let me know. Using separate start/end cells instead of just "A1:T1" is deliberate - it's easier to see that it's genuinely a range of 20 cells. Anything else is probably accidental.)</p>
<p>So, should I use <code>_Worksheet</code> or <code>Worksheet</code>, and why?</p> | 1,051,546 | 5 | 4 | null | 2009-06-26 22:02:32.417 UTC | 12 | 2015-09-15 00:52:07.593 UTC | 2015-09-15 00:52:07.593 UTC | null | 1,505,120 | null | 22,656 | null | 1 | 79 | c#|excel|com|interop | 24,846 | <p>If I recall correctly -- and my memory on this is a bit fuzzy, it has been a long time since I took the Excel PIA apart -- it's like this.</p>
<p>An event is essentially a method that an object calls when something happens. In .NET, events are delegates, plain and simple. But in COM, it is very common to organize a whole bunch of event callbacks into interfaces. You therefore have two interfaces on a given object -- the "incoming" interface, the methods you expect other people to call on you, and the "outgoing" interface, the methods you expect to call on other people when events happen.</p>
<p>In the unmanaged metadata -- the type library -- for a creatable object there are definitions for three things: the incoming interface, the outgoing interface, and the coclass, which says "I'm a creatable object that implements this incoming interface and this outgoing interface".</p>
<p>Now when the type library is automatically translated into metadata, those relationships are, sadly, preserved. It would have been nicer to have a hand-generated PIA that made the classes and interfaces conform more to what we'd expect in the managed world, but sadly, that didn't happen. Therefore the Office PIA is full of these seemingly odd duplications, where every creatable object seems to have two interfaces associated with it, with the same stuff on them. One of the interfaces represents the interface to the coclass, and one of them represents the incoming interface to that coclass.</p>
<p>The _Workbook interface is the incoming interface on the workbook coclass. The Workbook interface is the interface which represents the coclass itself, and therefore inherits from _Workbook.</p>
<p>Long story short, I would use Workbook if you can do so conveniently; _Workbook is a bit of an implementation detail.</p> |
842,856 | What's the most efficient way to find one of several substrings in Python? | <p>I have a list of possible substrings, e.g. <code>['cat', 'fish', 'dog']</code>. In practice, the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substrings.</p>
<p>To clarify, for <code>'012cat'</code> the result is 3, and for <code>'0123dog789cat'</code> the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/regex solution for this.</p> | 842,871 | 6 | 1 | null | 2009-05-09 07:20:49.307 UTC | 11 | 2021-05-11 14:55:27.3 UTC | 2020-04-20 12:07:01.33 UTC | null | 7,851,470 | null | 103,532 | null | 1 | 30 | python|regex|string|substring | 14,544 | <p>I would assume a regex is better than checking for each substring individually because <em>conceptually</em> the regular expression is modeled as a <a href="https://en.m.wikipedia.org/wiki/Deterministic_finite_automaton" rel="nofollow noreferrer">DFA</a>, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).</p>
<p>So, here is an example:</p>
<pre><code>import re
def work():
to_find = re.compile("cat|fish|dog")
search_str = "blah fish cat dog haha"
match_obj = to_find.search(search_str)
the_index = match_obj.start() # produces 5, the index of fish
which_word_matched = match_obj.group() # "fish"
# Note, if no match, match_obj is None
</code></pre>
<p><em><strong>UPDATE:</strong></em>
Some care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but <a href="http://docs.python.org/2.7/library/re.html#re.escape" rel="nofollow noreferrer">escapes any regex special characters</a> and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word:</p>
<pre><code>def wordlist_to_regex(words):
escaped = map(re.escape, words)
combined = '|'.join(sorted(escaped, key=len, reverse=True))
return re.compile(combined)
>>> r.search('smash atomic particles').span()
(6, 10)
>>> r.search('visit usenet:comp.lang.python today').span()
(13, 29)
>>> r.search('a north\south division').span()
(2, 13)
>>> r.search('012cat').span()
(3, 6)
>>> r.search('0123dog789cat').span()
(4, 7)
</code></pre>
<p><em><strong>END UPDATE</strong></em></p>
<p>It should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here:</p>
<p><a href="http://docs.python.org/library/re.html" rel="nofollow noreferrer">http://docs.python.org/library/re.html</a></p>
<p>Hope this helps.</p>
<p><em><strong>UPDATE:</strong></em> I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to "|" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code:</p>
<pre><code>import random
import re
import string
import sys
def main(args):
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
match_obj = search_for.search(search_string)
if match_obj is None:
print "Ahhhg"
return
index = match_obj.start()
which = match_obj.group()
if index != 0:
print "ahhhg"
return
if words[-1] != which:
print "ahhg"
return
print "success!!! Generated 2000 random words, compiled re, and was able to perform matches."
if __name__ == "__main__":
main(sys.argv)
</code></pre>
<p><em><strong>UPDATE:</strong></em> It should be noted that the order of of things ORed together in the regex <em>matters</em>. Have a look at the following test inspired by <a href="https://stackoverflow.com/users/6899/">TZOTZIOY</a>:</p>
<pre><code>>>> search_str = "01catdog"
>>> test1 = re.compile("cat|catdog")
>>> match1 = test1.search(search_str)
>>> match1.group()
'cat'
>>> match1.start()
2
>>> test2 = re.compile("catdog|cat") # reverse order
>>> match2 = test2.search(search_str)
>>> match2.group()
'catdog'
>>> match2.start()
2
</code></pre>
<p>This suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known.</p>
<p><em><strong>UPDATE:</strong></em> I posted <a href="https://stackoverflow.com/questions/844183/python-regular-expression-implementation-details">this questions about the implementation of regular expressions in Python</a> which will hopefully give us some insight into the issues found with this question.</p> |
1,066,857 | Determine if page is valid in JavaScript - ASP.NET | <p>What is the best way to determine if a form on an ASPX page is valid in JavaScript? </p>
<p>I am trying to check the validation of an user control that was opened using the JavaScript <code>window.showModalDialog()</code> and checking the 'Page.IsValid' property on the server side does not work. I am using ASP.NET validation controls for page validation. </p> | 1,069,287 | 6 | 0 | null | 2009-07-01 01:12:56.86 UTC | 25 | 2014-02-07 07:06:37.71 UTC | 2009-07-01 15:32:55.087 UTC | null | 26,327 | null | 26,327 | null | 1 | 80 | asp.net|javascript|validation | 102,663 | <p>If I have a page that is using a bunch of ASP.NET validation controls I will use code similar to the following to validate the page. Make the call on an input submit. Hopefully this code sample will get you started!</p>
<pre><code> <input type="submit" value="Submit" onclick"ValidatePage();" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
}
else {
// do something else
alert('Page is not valid!');
}
}
</script>
</code></pre> |
989,093 | Soft wrap at 80 characters in Vim in window of arbitrary width | <p>I want to use Vim's <a href="https://stackoverflow.com/questions/319925/difference-between-hard-wrap-and-soft-wrap">soft wrap</a> capability (<code>:set wrap</code>) to wrap some code at 80 characters, regardless of my actual window width.</p>
<p>I haven't been able to find a way to do this yet - all the soft wrapping seems tied to the width of the window</p>
<ul>
<li><code>textwidth</code> and <code>wrapmargin</code> are both for hard wrapping (they insert newline characters into the file)</li>
<li>vertical splitting into multiple windows and using <code>:vertical resize 80</code> (possibly with <code>:set breakat=</code> to allow breaks on any character) on one of them sort of works (even though it's a bit hackish), but breaks when using <code>:set number</code> as the line numbers take up a variable number of columns (depending on the file length) and these are part of the 80.</li>
</ul>
<p>Is there any way to do this in vim? <a href="http://web.archive.org/web/20090704071718/http://objectmix.com/editors/149624-vim-how-control-wrap-width-please-help.html" rel="noreferrer">It doesn't look promising, according to other sources</a>.</p>
<p>Right now my approximation is just to have <code>/^.\{80}\zs.\+</code> as my default search so it's at least highlighted. I thought about adding a <code>:syntax</code> item for it, but that broke when it overlapped other syntax items, so I dropped that idea.</p> | 989,317 | 6 | 2 | null | 2009-06-12 21:18:31.237 UTC | 29 | 2022-05-12 01:34:32.997 UTC | 2019-04-17 22:08:33.38 UTC | null | 2,370,483 | null | 9,859 | null | 1 | 149 | vim|word-wrap | 42,776 | <p>You could </p>
<ul>
<li>set a large minimum width for the line numbers column via <code>:set numberwidth=6</code> and </li>
<li>then you could resize your window with <code>:set columns=86</code> (or with the mouse) to the proper size. </li>
</ul>
<p>If you edit a file with a million lines in it, you may have trouble, but that's unlikely. You're wasting 6 columns of screen real estate this way too. So there are still all kinds of problems.</p>
<p>You can highlight past the 80th column using <code>:match</code> like it says <a href="https://stackoverflow.com/questions/830645/changing-background-color-in-vim-at-a-certain-column">here</a> and <a href="http://vim.wikia.com/wiki/Highlight_long_lines" rel="noreferrer">here</a>.</p>
<p>Beyond that I can't see any way to do this. Seems like it'd be a nice feature though.</p> |
42,238,819 | Angular 2: How to call a function after get a response from subscribe http.post | <p>I need to call a method after get the data from the http post request </p>
<p><strong>service: request.service.TS</strong></p>
<pre><code>get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
</code></pre>
<p><strong>component: categories.TS</strong> </p>
<pre><code>search_categories() {
this.get_categories(1);
//I need to call a Method here after get the data from response.json() !! e.g.: send_catagories();
}
</code></pre>
<p>Only works if I change to:</p>
<p><strong>service: request.service.TS</strong></p>
<pre><code>get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
this.send_catagories(); //here works fine
}, error => {
}
);
}
</code></pre>
<p>But I need to call the method <code>send_catagories()</code> inside of component after call <code>this.get_categories(1);</code> like this</p>
<p>component: categories.TS </p>
<pre><code>search_categories() {
this.get_categories(1);
this.send_catagories(response);
}
</code></pre>
<p>What I doing wrong?</p> | 42,239,388 | 5 | 3 | null | 2017-02-15 00:38:30.16 UTC | 15 | 2018-10-24 21:24:44.743 UTC | 2017-12-03 15:48:25.84 UTC | null | 7,603,109 | null | 6,089,644 | null | 1 | 43 | javascript|angular|typescript|promise|subscribe | 166,255 | <p>Update your <code>get_categories()</code> method to <strong>return</strong> the total (wrapped in an observable):</p>
<pre class="lang-ts prettyprint-override"><code>// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
return this.http.post( url, body, {headers: headers, withCredentials:true})
.map(response => response.json());
}
</code></pre>
<p>In <code>search_categories()</code>, you can subscribe the observable returned by <code>get_categories()</code> (or you could keep transforming it by chaining more RxJS operators):</p>
<pre class="lang-ts prettyprint-override"><code>// send_categories() is now called after get_categories().
search_categories() {
this.get_categories(1)
// The .subscribe() method accepts 3 callbacks
.subscribe(
// The 1st callback handles the data emitted by the observable.
// In your case, it's the JSON data extracted from the response.
// That's where you'll find your total property.
(jsonData) => {
this.send_categories(jsonData.total);
},
// The 2nd callback handles errors.
(err) => console.error(err),
// The 3rd callback handles the "complete" event.
() => console.log("observable complete")
);
}
</code></pre>
<p>Note that you <strong>only subscribe ONCE</strong>, at the end.</p>
<p>Like I said in the comments, the <code>.subscribe()</code> method of any observable accepts 3 callbacks like this:</p>
<pre class="lang-ts prettyprint-override"><code>obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
</code></pre>
<p>They must be passed in this order. You don't have to pass all three. Many times only the <code>nextCallback</code> is implemented:</p>
<pre class="lang-ts prettyprint-override"><code>obs.subscribe(nextCallback);
</code></pre> |
37,639,271 | Processing camera feed data on GPU (metal) and CPU (OpenCV) on iPhone | <p>I'm doing realtime video processing on iOS at 120 fps and want to first preprocess image on GPU (downsample, convert color, etc. that are not fast enough on CPU) and later postprocess frame on CPU using OpenCV.</p>
<p><strong>What's the fastest way to share camera feed between GPU and CPU using Metal?</strong></p>
<p>In other words the pipe would look like:</p>
<pre><code>CMSampleBufferRef -> MTLTexture or MTLBuffer -> OpenCV Mat
</code></pre>
<p>I'm converting CMSampleBufferRef -> MTLTexture the following way</p>
<pre><code>CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// textureRGBA
{
size_t width = CVPixelBufferGetWidth(pixelBuffer);
size_t height = CVPixelBufferGetHeight(pixelBuffer);
MTLPixelFormat pixelFormat = MTLPixelFormatBGRA8Unorm;
CVMetalTextureRef texture = NULL;
CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, _textureCache, pixelBuffer, NULL, pixelFormat, width, height, 0, &texture);
if(status == kCVReturnSuccess) {
textureBGRA = CVMetalTextureGetTexture(texture);
CFRelease(texture);
}
}
</code></pre>
<p>After my metal shader is finised I convert MTLTexture to OpenCV</p>
<pre><code>cv::Mat image;
...
CGSize imageSize = CGSizeMake(drawable.texture.width, drawable.texture.height);
int imageByteCount = int(imageSize.width * imageSize.height * 4);
int mbytesPerRow = 4 * int(imageSize.width);
MTLRegion region = MTLRegionMake2D(0, 0, int(imageSize.width), int(imageSize.height));
CGSize resSize = CGSizeMake(drawable.texture.width, drawable.texture.height);
[drawable.texture getBytes:image.data bytesPerRow:mbytesPerRow fromRegion:region mipmapLevel:0];
</code></pre>
<p><strong>Some observations:</strong></p>
<p>1) Unfortunately <code>MTLTexture.getBytes</code> seems expensive (copying data from GPU to CPU?) and takes around 5ms on my iphone 5S which is too much when processing at ~100fps</p>
<p>2) I noticed some people use MTLBuffer instead of MTLTexture with the following method:
<code>metalDevice.newBufferWithLength(byteCount, options: .StorageModeShared)</code>
(see: <a href="https://stackoverflow.com/questions/35860898/memory-write-performance-gpu-cpu-shared-memory">Memory write performance - GPU CPU Shared Memory</a>)</p>
<p>However <code>CMSampleBufferRef</code> and accompanying <code>CVPixelBufferRef</code> is managed by CoreVideo is guess.</p> | 38,884,664 | 1 | 5 | null | 2016-06-05 06:57:04.35 UTC | 10 | 2016-08-11 15:03:27.333 UTC | 2017-05-23 12:17:59.923 UTC | null | -1 | null | 657,429 | null | 1 | 16 | ios|objective-c|opencv|gpgpu|metal | 5,833 | <p>The fastest way to do this is to use a MTLTexture backed by a MTLBuffer; it is a special kind of MTLTexture that shares memory with a MTLBuffer. However, your C processing (openCV) will be running a frame or two behind, this is unavoidable as you need to submit the commands to the GPU (encoding) and the GPU needs to render it, if you use waitUntilCompleted to make sure the GPU is finished that just chews up the CPU and is wasteful. </p>
<p>So the process would be: first you create the MTLBuffer then you use the MTLBuffer method "newTextureWithDescriptor:offset:bytesPerRow:" to create the special MTLTexture. You need to create the special MTLTexture beforehand (as an instance variable), then you need to setup up a standard rendering pipeline (faster than using compute shaders) that will take the MTLTexture created from the CMSampleBufferRef and pass this into your special MTLTexture, in that pass you can downscale and do any colour conversion as necessary in one pass. Then you submit the command buffer to the gpu, in a subsequent pass you can just call [theMTLbuffer contents] to grab the pointer to the bytes that back your special MTLTexture for use in openCV. </p>
<p>Any technique that forces a halt in the CPU/GPU behaviour will never be efficient as half the time will be spent waiting i.e. the CPU waits for the GPU to finish and the GPU has to wait also for the next encodings (when the GPU is working you want the CPU to be encoding the next frame and doing any openCV work rather than waiting for the GPU to finish). </p>
<p>Also, when people normally refer to real-time processing they usually are referring to some processing with real-time feedback (visual), all modern iOS devices from the 4s and above have a 60Hz screen refresh rate, so any feedback presented faster than that is pointless but if you need 2 frames (at 120Hz) to make 1 (at 60Hz) then you have to have a custom timer or modify CADisplayLink. </p> |
18,037,716 | How to redirect single URL in Nginx? | <p>I'm in the process of reorganizing URL structure.
I need to setup redirect rules for specific URLs - I'm using Nginx.</p>
<p>Basically Something like this:</p>
<pre><code>http://example.com/issue1 --> http://example.com/shop/issues/custom_issue_name1
http://example.com/issue2 --> http://example.com/shop/issues/custom_issue_name2
http://example.com/issue3 --> http://example.com/shop/issues/custom_issue_name3
</code></pre>
<p>Thanks!</p> | 18,038,165 | 3 | 2 | null | 2013-08-03 21:59:39.84 UTC | 44 | 2021-04-02 08:35:15.97 UTC | 2021-04-02 08:35:15.97 UTC | null | 9,193,372 | null | 724,368 | null | 1 | 124 | nginx|url-rewriting | 235,725 | <p>Put this in your server directive:</p>
<pre><code>location /issue {
rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
}
</code></pre>
<p>Or duplicate it:</p>
<pre><code>location /issue1 {
rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
...
</code></pre> |
33,520,854 | filtering data frame based on NA on multiple columns | <p>I have the following data frame lets call it <code>df</code>, with the following observations:</p>
<pre><code>id type company
1 NA NA
2 NA ADM
3 North Alex
4 South NA
NA North BDA
6 NA CA
</code></pre>
<p>I want to retain only the records which do not have NA in column "type" and "company".</p>
<pre><code>id type company
3 North Alex
NA North BDA
</code></pre>
<p>I tried: </p>
<pre><code> df_non_na <- df[!is.na(df$company) || !is.na(df$type), ]
</code></pre>
<p>But this did not work. </p>
<p>Thanks in advance</p> | 33,520,902 | 6 | 5 | null | 2015-11-04 11:36:28.197 UTC | 6 | 2022-08-11 20:08:09.183 UTC | 2019-05-28 06:41:19.173 UTC | null | 9,855,745 | null | 3,875,610 | null | 1 | 17 | r|dataframe | 50,515 | <p>We can get the logical index for both columns, use <code>&</code> and subset the rows.</p>
<pre><code>df1[!is.na(df1$type) & !is.na(df1$company),]
# id type company
#3 3 North Alex
#5 NA North BDA
</code></pre>
<p>Or use <code>rowSums</code> on the logical matrix (<code>is.na(df1[-1])</code>) to subset.</p>
<pre><code>df1[!rowSums(is.na(df1[-1])),]
</code></pre> |
1,365,305 | Flat object file directory structure output with GNU Make | <p>I have a C++ small project using GNU Make. I'd like to be able to turn the following source files:</p>
<pre><code>src/
a.cpp
b/
b.cpp
c/
c.cpp
</code></pre>
<p>into the following output structure (I'm not concerned about duplicates at this point):</p>
<pre><code>build/
a.o
b.o
c.o
</code></pre>
<p>So far I have the following, which unfortunately puts the .o and .d right next to each .cpp:</p>
<pre><code>OBJS := $(foreach file,$(SRCS),$(file).o)
DEPS := $(patsubst %.o,%.d,$(OBJS))
sinclude $(DEPS)
$(OBJS) : %.o : %.cpp
@echo Compiling $<
$(CC) $(CC_FLAGS) $(INCS) -MMD -o $@ $<
</code></pre>
<p>I'm aware of the $(notdir ...) function, but at this point my efforts to use it to filter the objects has failed. Can anyone shed some light on this? It seems like fairly reasonable thing to do.</p> | 1,365,388 | 5 | 0 | null | 2009-09-02 00:21:42.27 UTC | 10 | 2012-12-01 08:21:15.98 UTC | null | null | null | null | 94,239 | null | 1 | 9 | makefile|gnu-make | 8,527 | <p>There are at least two ways you can do this. First (and what I'd recommend) is you can add the build directory to the target names (even when using a pattern rule). For example:</p>
<pre><code>$(OBJS) : build/%.o : %.cpp
</code></pre>
<p>Second, you can use the VPATH variable to tell make to search a different directory for prerequisites. This is probably the more commonly (over) used approach. It has at least one serious drawback, and that is if you go with it, and later run into problems with "duplicates", there's no way to solve the problem. With the former approach, you can always mirror the source directory structure underneath the build directory to avoid duplicates clashing.</p>
<p><strong>Edit:</strong> My previous answer was a little short on detail, so I will expand upon it to show that this actually works as advertised. Here is a complete working example Makefile that uses the first technique described above to solve the problem. Simply paste this into a Makefile and run make -- it will do the rest and show that this does in fact work.</p>
<p><strong>Edit:</strong> I can't figure out how to get SO to allow tab characters in my answer text (it replaced them with spaces). After copying and pasting this example, you'll need to convert the leading spaces in the command scripts into tabs.</p>
<pre><code>BUILD_DIR := build
SRCS := \
a.c \
b.c \
c.c \
a/a.c \
b/b.c \
c/c.c
OBJS := ${SRCS:%.c=${BUILD_DIR}/%.o}
foo: ${OBJS}
@echo Linking $@ using $?
@touch $@
${BUILD_DIR}/%.o: %.c
@mkdir -p $(dir $@)
@echo Compiling $< ...
@touch $@
${SRCS}:
@echo Creating $@
@mkdir -p $(dir $@)
@touch $@
.PHONY: clean
clean:
rm -f foo
rm -f ${OBJS}
</code></pre>
<p>In particular, note that there are source files with duplicate names (a.c and a/a.c, b.c and b/b.c, etc) and that this doesn't cause any problems. Also note there is no use of VPATH, which I recommend to avoid using due to its inherent limitations.</p> |
1,583,150 | C#: Oracle Data Type Equivalence with OracleDbType | <hr>
<h2>Situation:</h2>
<p>I am creating an app in C# that uses Oracle.DataAccess.Client (11g) to do certain operations on a Oracle database with stored procedures. I am aware that there is a certain enum (OracleDbType) that contains the Oracle data types, but I am not sure which one to use for certain types.</p>
<h2>Questions:</h2>
<ul>
<li><p>What is the equivalent <strong>Oracle PL/SQL data
type</strong> for each enumerated type in the
<strong>OracleDbType enumeration</strong>?</p></li>
<li><p>There are three types of integer<br>
(Int16, Int32, Int64) in the OracleDbType... how to know
which one to use or are they all<br>
suppose to work?</p></li>
</ul>
<hr> | 1,583,402 | 5 | 1 | null | 2009-10-17 20:43:10.317 UTC | 12 | 2021-08-27 09:40:45.643 UTC | 2009-10-17 21:45:22.293 UTC | null | 127,716 | null | 127,716 | null | 1 | 24 | c#|oracle|plsql|types|type-equivalence | 79,744 | <p>The values of the OracleDbType Enumeration are defined in the documentation. Read <a href="http://download.oracle.com/docs/cd/B19306_01/win.102/b14307/OracleDbTypeEnumerationType.htm" rel="nofollow noreferrer">the ODP for .NET Developer's Guide</a>.</p>
<p>With regards to choosing between Int16, Int32 and Int64, they are all supposed to work. Choose the one which matches the expected size of your .Net variable: Int16 for values between -32768 and 32767, Int32 for values between -2147483648 and 2147483647, and Int64 for anything larger. There appear to be some funnies relating to converting Ints and PL/SQL data types. Check <a href="http://oradim.blogspot.com/2009/08/odpnet-vb-and-from-type-to-type-is-not.html" rel="nofollow noreferrer" title="Conversion from type 'OracleDecimal' to type 'Integer' is not valid.">this blog post by Mark Williams</a>.</p>
<hr />
<h2>Coda</h2>
<p>Greetings from 2021. This post has just been upvoted, so presumably Seekers are still finding it and finding it useful. But please note that <strong>it is more than ten years old</strong>. Consequently the advice it offers may not be relevant for more recent versions of ODP, particularly regarding unusual behaviour. Please don't follow recommendations without verifying them for yourself. (This is general advice which holds for anything you read on the Internet, and not just about software development!)</p>
<p><a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/odpnt/OracleDbTypeEnumerationType.html#GUID-E5D6E666-49EA-4A8D-822A-A190101C33D7" rel="nofollow noreferrer">Here is the pertinent link for Oracle 21c ODP documentation</a>.</p> |
1,985,978 | Combining a vector of strings | <p>I've been reading <a href="https://rads.stackoverflow.com/amzn/click/com/020170353X" rel="noreferrer" rel="nofollow noreferrer">Accelerated C++</a> and I have to say it's an interesting book.</p>
<p>In chapter 6, I have to use a function from <algorithm> to concatenate from a vector<string> into a single string. I could use accumulate, but it doesn't help because string containers can only push_back characters. </p>
<pre><code>int main () {
using namespace std;
string str = "Hello, world!";
vector<string> vec (10, str);
// Concatenate here?
return 0;
}
</code></pre>
<p>How do I join the strings together?</p> | 1,986,048 | 5 | 1 | null | 2009-12-31 16:16:01.607 UTC | 11 | 2022-03-16 20:47:42.16 UTC | 2013-12-31 12:56:33.337 UTC | null | 2,231,440 | null | 178,481 | null | 1 | 25 | c++|string|vector|stl | 37,887 | <p>Assuming this is question 6.8, it doesn't say you have to use accumulate - it says use "a library algorithm". However, you can use accumulate:</p>
<pre><code>#include <numeric>
int main () {
std::string str = "Hello World!";
std::vector<std::string> vec(10,str);
std::string a = std::accumulate(vec.begin(), vec.end(), std::string(""));
std::cout << a << std::endl;
}
</code></pre>
<p>All that accumulate does is set 'sum' to the third parameter, and then for all of the values 'val' from first parameter to second parameter, do:</p>
<pre><code>sum = sum + val
</code></pre>
<p>it then returns 'sum'. Despite the fact that accumulate is declared in <code><numeric></code> it will work for anything that implements <code>operator+()</code></p>
<hr />
<p><strong>Note</strong>: <em>This solution, while elegant, is inefficient, as a new string will be allocated and populated for each element of <code>vec</code>.</em></p> |
1,775,954 | Using Python 3.1 with TextMate | <p>TextMate seems to use the built-in Python version I assume (sys.path doesn't work). How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I need to use TextMate now.</p>
<p>Thanks</p> | 1,776,026 | 5 | 0 | null | 2009-11-21 16:34:17.207 UTC | 16 | 2022-07-22 10:06:39.657 UTC | 2009-11-21 20:17:07.133 UTC | null | 8,061 | null | 172,637 | null | 1 | 29 | python|macos|python-3.x|textmate | 17,466 | <p>TextMate uses the value of the <code>TM_PYTHON</code> variable to find the path to the Python interpreter. A good solution is to take advantage of TextMate's ability to define variables like <code>TM_PYTHON</code> on a per-project basis:</p>
<ol>
<li><p>Open a new or existing TextMate Project (<code>File -> New Project</code> or <code>File -> Open</code>)</p></li>
<li><p>De-select any file in the project list sidebar.</p></li>
<li><p>Click on the <code>Get Info</code> (<strong>i</strong>) icon in the sidebar. A <code>Project Information</code> pane appears.</p></li>
<li><p>Click + to add a new variable.</p></li>
<li><p>Enter TM_PYTHON in the Variable field and the full path to the desired python in the Value field (for example, <code>/usr/local/bin/python3.1</code>).</p></li>
<li><p>Close the Information window and save the Project (<code>File</code> -> <code>Save Project As</code>).</p></li>
</ol>
<p>Then you can add files as needed to the project and they will be run under the chosen python with TextMate Python bundle's Run Script command. You might want to save a <code>Python 3</code> project, say, for running ad-hoc scripts under Python 3. For bigger projects, you'll want to create a separate TextMate project for it anyway.</p>
<p>To change the Python version used globally within <code>TextMate</code>:</p>
<ol>
<li><p>From the <code>TextMate</code> menu bar, open <code>TextMate</code> -> <code>Preferences</code></p></li>
<li><p>click on the <code>Advanced</code> pane</p></li>
<li><p>click on the <code>Shell Variable</code> tab</p></li>
<li><p>click the <code>+</code> to add a new variable</p></li>
<li><p>enter <code>TM_PYTHON</code> in the <code>Variable</code> field and the full path to the python in the <code>Value</code> field (perhaps <code>/usr/local/bin/python3.1</code>)</p></li>
</ol>
<p>As Alex points out, you may break other TextMate functionality by changing the Python version globally so the per-project change is probably a better solution.</p>
<p>UPDATE (2010-10-31):</p>
<p>There is another approach that may be easier to use for some projects. The <code>Run</code> command in <code>TextMate</code>'s Python bundle appears to respect a <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)" rel="noreferrer">shebang</a> line in the file being run. So, instead of modifying <code>TM_PYTHON</code>, you can specify the path to the interpreter to be used by including a first line like this:</p>
<pre><code>#!/usr/local/bin/python3.1
# sample code to show version
import sys
print(sys.version_info)
</code></pre>
<p>In many case you would prefer not to <em>hardwire</em> the absolute path but manage use through the normal shell <code>PATH</code> environment variable. Traditionally <code>/usr/bin/env</code> is used for that purpose. However when running under <code>TextMate</code>, your shell profile files are not normally used so any changes to PATH do not show up there including possibly <code>/usr/local/bin</code> or <code>/opt/local/bin</code> or wherever your desired <code>python3</code> command is located. To get around that, you can add or modify a global <code>PATH</code> shell variable to <code>TextMate</code> -> <code>Preferences</code> (see above) with a value of, say, <code>/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin</code>. Then you can use a more general shebang line like this:</p>
<pre><code>#!/usr/bin/env python3
</code></pre>
<p>(This all seems to work with the most recent vanilla <code>TextMate</code> and its Python bundle: no guarantees about earlier versions or with other Python bundles.)</p> |
1,615,612 | How can you download a file/zip from the commandline using putty? | <p>I'm trying to write a batch script (CMD @ Windows XP Pro) that will automatically download and unzip packages with the help of 7zip and putty/psftp</p>
<p>If I have a URL to a package to download <a href="http://somesite.org/packages/package.zip" rel="noreferrer">http://somesite.org/packages/package.zip</a> how do I download it on command line using putty?</p>
<p>Also if you have a better way to do this that would be helpful too.</p> | 1,615,748 | 6 | 0 | null | 2009-10-23 20:04:31.78 UTC | 2 | 2014-04-23 16:33:17.053 UTC | 2011-11-13 13:34:26.42 UTC | null | 73,070 | null | 177,389 | null | 1 | 5 | cmd|putty|7zip | 53,031 | <p>wget is of course an obvious solution, but I also suggest to have a look at <a href="http://curl.haxx.se/" rel="noreferrer">cURL</a>. From their website:</p>
<blockquote>
<p>curl is a command line tool for
transferring files with URL syntax,
supporting FTP, FTPS, HTTP, HTTPS,
SCP, SFTP, TFTP, TELNET, DICT, LDAP,
LDAPS and FILE. curl supports SSL
certificates, HTTP POST, HTTP PUT, FTP
uploading, HTTP form based upload,
proxies, cookies, user+password
authentication (Basic, Digest, NTLM,
Negotiate, kerberos...), file transfer
resume, proxy tunneling and a busload
of other useful tricks.</p>
</blockquote>
<p>Of course free and open source, and despite its huge list of supported protocols it's as simple to use as wget, so to use your example</p>
<pre><code>curl -O http://somesite.org/packages/package.zip
</code></pre>
<p>downloads package.zip to a local file with the same name </p>
<pre><code>curl -o myname.zip http://somesite.org/packages/package.zip
</code></pre>
<p>downloads package.zip as myname.zip</p>
<pre><code>curl http://somesite.org/packages/package.zip > package.zip
</code></pre>
<p>redirects curl's stdout to package.zip</p>
<p>EDIT - example corrected, with thanks to @PrabhakarKasi</p> |
1,803,215 | How can I tell if a socket buffer is full? | <p>How can I tell if a read socket buffer is full or a write socket buffer is empty?</p>
<p>Is there a way I can get the status of a socket buffer without a system call?</p>
<p>UPDATE: How about this: I'd like to get a callback or signal when either the read socket buffer is full or the write socket buffer is empty. This way I can stop processing to allow more I/O to occur on the wire, since being I/O bound is always an issue when sending data on the wire.</p>
<p>The <code>select()</code> call is how you check if the read buffer has something in it. <em>Not</em> when it is full (I think).</p> | 1,805,234 | 8 | 3 | null | 2009-11-26 11:43:27.553 UTC | 14 | 2011-10-19 01:10:10.593 UTC | 2009-11-26 15:24:03.8 UTC | null | 71,865 | null | 71,865 | null | 1 | 18 | c|sockets | 38,798 | <p>You can try <code>ioctl</code>. FIONREAD tells you how many bytes are immediately readable. If this is the same as the buffer size (which you might be able to retrieve and/or set with another icotl call), then the buffer is full. Likewise, if you can write as many bytes as the size of the output buffer, then the output buffer is empty. </p>
<p>I don't how widely supported FIONREAD, FIONWRITE, and SIOCGIFBUFS (or equivalents) are. I'm not sure I've ever used any of them, although I've a sneaky feeling I've used similar functionality on Symbian for some reason or other.</p>
<p>Whether the call needs kernel mode to compute this is platform-specific. Vaguely trying to avoid system calls is not a valid optimisation technique.</p>
<p>A basic BSD-style sockets interface doesn't say anything much about read and write buffers. When does it matter whether the send buffer is empty? It certainly doesn't mean that all the data has been received at the other endpoint of the socket - it could be sitting in some router somewhere. Likewise, "your" read buffer being full doesn't guarantee that a write at the other end will block.</p>
<p>Generally speaking, you just read/write as much as you can and let the sockets layer handle the complexity. If you're seeing a lot of I/O completed with tiny sizes then maybe there's some performance problem. But remember that a stream socket will send/receive a packet at a time, containing a block of data. Unless TCP_NODELAY is set, it's not as though bytes are arriving by ones at the NIC, and you might end up making one read call per byte. They're arriving in packets, so most likely will become readable all at once, perhaps 1k-ish at a time. You're unlikely to be able to speed things up by holding off reading until there's a lot to read. In fact you might make it worse, because by the time your endpoint's read buffer is full, there's a risk that incoming data is being discarded because there's nowhere to store it, resulting in delays and re-sends.</p> |
2,050,790 | How to correctly use lists? | <p>Brief background: Many (most?) contemporary programming languages in widespread use have at least a handful of ADTs [abstract data types] in common, in particular,</p>
<ul>
<li><p><strong>string</strong> (a sequence comprised of characters)</p></li>
<li><p><strong>list</strong> (an ordered collection of values), and</p></li>
<li><p><strong>map-based type</strong> (an unordered array that maps keys to values)</p></li>
</ul>
<p>In the R programming language, the first two are implemented as <code>character</code> and <code>vector</code>, respectively.</p>
<p>When I began learning R, two things were obvious almost from the start: <code>list</code> is the most important data type in R (because it is the parent class for the R <code>data.frame</code>), and second, I just couldn't understand how they worked, at least not well enough to use them correctly in my code.</p>
<p>For one thing, it seemed to me that R's <code>list</code> data type was a straightforward implementation of the map ADT (<code>dictionary</code> in Python, <code>NSMutableDictionary</code> in Objective C, <code>hash</code> in Perl and Ruby, <code>object literal</code> in Javascript, and so forth).</p>
<p>For instance, you create them just like you would a Python dictionary, by passing key-value pairs to a constructor (which in Python is <code>dict</code> not <code>list</code>):</p>
<pre><code>x = list("ev1"=10, "ev2"=15, "rv"="Group 1")
</code></pre>
<p>And you access the items of an R List just like you would those of a Python dictionary, e.g., <code>x['ev1']</code>. Likewise, you can retrieve just the <em>'keys'</em> or just the <em>'values'</em> by: </p>
<pre><code>names(x) # fetch just the 'keys' of an R list
# [1] "ev1" "ev2" "rv"
unlist(x) # fetch just the 'values' of an R list
# ev1 ev2 rv
# "10" "15" "Group 1"
x = list("a"=6, "b"=9, "c"=3)
sum(unlist(x))
# [1] 18
</code></pre>
<p>but R <code>list</code>s are also <strong><em>unlike</em></strong> other map-type ADTs (from among the languages I've learned anyway). My guess is that this is a consequence of the initial spec for S, i.e., an intention to design a data/statistics DSL [domain-specific language] from the ground-up. </p>
<p><em>three</em> significant differences between R <code>list</code>s and mapping types in other languages in widespread use (e.g,. Python, Perl, JavaScript):</p>
<p><em>first</em>, <code>list</code>s in R are an <em>ordered</em> collection, just like vectors, even though the values are keyed (ie, the keys can be any hashable value not just sequential integers). Nearly always, the mapping data type in other languages is <em>unordered</em>.</p>
<p><em>second</em>, <code>list</code>s can be returned from functions even though you never passed in a <code>list</code> when you called the function, and <em>even though</em> the function that returned the <code>list</code> doesn't contain an (explicit) <code>list</code> constructor (Of course, you can deal with this in practice by wrapping the returned result in a call to <code>unlist</code>):</p>
<pre><code>x = strsplit(LETTERS[1:10], "") # passing in an object of type 'character'
class(x) # returns 'list', not a vector of length 2
# [1] list
</code></pre>
<p>A <em>third</em> peculiar feature of R's <code>list</code>s: it doesn't seem that they can be members of another ADT, and if you try to do that then the primary container is coerced to a <code>list</code>. E.g.,</p>
<pre><code>x = c(0.5, 0.8, 0.23, list(0.5, 0.2, 0.9), recursive=TRUE)
class(x)
# [1] list
</code></pre>
<p>my intention here is not to criticize the language or how it is documented; likewise, I'm not suggesting there is anything wrong with the <code>list</code> data structure or how it behaves. All I'm after is to correct is my understanding of how they work so I can correctly use them in my code. </p>
<p>Here are the sorts of things I'd like to better understand:</p>
<ul>
<li><p>What are the rules which determine when a function call will return a <code>list</code> (e.g., <code>strsplit</code> expression recited above)?</p></li>
<li><p>If I don't explicitly assign names to a <code>list</code> (e.g., <code>list(10,20,30,40)</code>) are the default names just sequential integers beginning with 1? (I assume, but I am far from certain that the answer is yes, otherwise we wouldn't be able to coerce this type of <code>list</code> to a vector w/ a call to <code>unlist</code>.)</p></li>
<li><p>Why do these two different operators, <code>[]</code>, and <code>[[]]</code>, return the <em>same</em> result?</p>
<p><code>x = list(1, 2, 3, 4)</code></p>
<p>both expressions return "1":</p>
<p><code>x[1]</code></p>
<p><code>x[[1]]</code></p></li>
<li><p>why do these two expressions <strong>not</strong> return the same result?</p>
<p><code>x = list(1, 2, 3, 4)</code></p>
<p><code>x2 = list(1:4)</code></p></li>
</ul>
<p>Please don't point me to the R Documentation (<a href="http://www.inside-r.org/r-doc/base/list" rel="noreferrer"><code>?list</code></a>, <a href="http://cran.r-project.org/doc/manuals/r-devel/R-intro.html#Lists" rel="noreferrer"><code>R-intro</code></a>)--I have read it carefully and it does not help me answer the type of questions I recited just above.</p>
<p>(lastly, I recently learned of and began using an R Package (available on CRAN) called <a href="http://mran.revolutionanalytics.com/packages/info/?hash" rel="noreferrer"><code>hash</code></a> which implements <em>conventional</em> map-type behavior via an S4 class; I can certainly recommend this Package.)</p> | 2,051,159 | 13 | 3 | null | 2010-01-12 17:08:50.06 UTC | 184 | 2022-06-15 16:15:53.18 UTC | 2022-06-15 16:15:53.18 UTC | null | 5,784,757 | null | 66,549 | null | 1 | 344 | r|list|data-structures|language-features|abstract-data-type | 214,091 | <p>Just to address the last part of your question, since that really points out the difference between a <code>list</code> and <code>vector</code> in R:</p>
<blockquote>
<p>Why do these two expressions not return the same result?</p>
<p>x = list(1, 2, 3, 4); x2 = list(1:4)</p>
</blockquote>
<p>A list can contain any other class as each element. So you can have a list where the first element is a character vector, the second is a data frame, etc. In this case, you have created two different lists. <code>x</code> has four vectors, each of length 1. <code>x2</code> has 1 vector of length 4:</p>
<pre><code>> length(x[[1]])
[1] 1
> length(x2[[1]])
[1] 4
</code></pre>
<p>So these are completely different lists.</p>
<p>R lists are very much like <a href="http://en.wikipedia.org/wiki/Hash_table" rel="noreferrer">a hash map</a> data structure in that each index value can be associated with any object. Here's a simple example of a list that contains 3 different classes (including a function):</p>
<pre><code>> complicated.list <- list("a"=1:4, "b"=1:3, "c"=matrix(1:4, nrow=2), "d"=search)
> lapply(complicated.list, class)
$a
[1] "integer"
$b
[1] "integer"
$c
[1] "matrix"
$d
[1] "function"
</code></pre>
<p>Given that the last element is the search function, I can call it like so:</p>
<pre><code>> complicated.list[["d"]]()
[1] ".GlobalEnv" ...
</code></pre>
<p>As a final comment on this: it should be noted that a <code>data.frame</code> is really a list (from the <code>data.frame</code> documentation):</p>
<blockquote>
<p>A data frame is a list of variables of the same number of rows with unique row names, given class ‘"data.frame"’</p>
</blockquote>
<p>That's why columns in a <code>data.frame</code> can have different data types, while columns in a matrix cannot. As an example, here I try to create a matrix with numbers and characters:</p>
<pre><code>> a <- 1:4
> class(a)
[1] "integer"
> b <- c("a","b","c","d")
> d <- cbind(a, b)
> d
a b
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
[4,] "4" "d"
> class(d[,1])
[1] "character"
</code></pre>
<p>Note how I cannot change the data type in the first column to numeric because the second column has characters:</p>
<pre><code>> d[,1] <- as.numeric(d[,1])
> class(d[,1])
[1] "character"
</code></pre> |
1,746,613 | Bitwise operation and usage | <p>Consider this code:</p>
<pre><code>x = 1 # 0001
x << 2 # Shift left 2 bits: 0100
# Result: 4
x | 2 # Bitwise OR: 0011
# Result: 3
x & 1 # Bitwise AND: 0001
# Result: 1
</code></pre>
<p>I can understand the arithmetic operators in Python (and other languages), but I never understood 'bitwise' operators quite well. In the above example (from a Python book), I understand the left-shift but not the other two.</p>
<p>Also, what are bitwise operators actually used for? I'd appreciate some examples.</p> | 1,746,642 | 18 | 2 | null | 2009-11-17 04:37:05.827 UTC | 86 | 2022-09-03 18:56:46.55 UTC | 2014-10-25 12:39:22.543 UTC | null | 63,550 | null | 172,637 | null | 1 | 109 | python|binary|operators|bit-manipulation | 150,390 | <p>Bitwise operators are operators that work on multi-bit values, but conceptually one bit at a time.</p>
<ul>
<li><code>AND</code> is 1 only if <em>both</em> of its inputs are 1, otherwise it's 0.</li>
<li><code>OR</code> is 1 if <em>one or both</em> of its inputs are 1, otherwise it's 0.</li>
<li><code>XOR</code> is 1 only if <em>exactly one</em> of its inputs are 1, otherwise it's 0.</li>
<li><code>NOT</code> is 1 only if its input is 0, otherwise it's 0.</li>
</ul>
<p>These can often be best shown as truth tables. Input possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the inputs.</p>
<pre><code>AND | 0 1 OR | 0 1 XOR | 0 1 NOT | 0 1
----+----- ---+---- ----+---- ----+----
0 | 0 0 0 | 0 1 0 | 0 1 | 1 0
1 | 0 1 1 | 1 1 1 | 1 0
</code></pre>
<p>One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:</p>
<pre><code> 201: 1100 1001
AND 15: 0000 1111
------------------
IS 9 0000 1001
</code></pre>
<p>The zero bits in 15 in that case effectively act as a filter, forcing the bits in the result to be zero as well.</p>
<p>In addition, <code>>></code> and <code><<</code> are often included as bitwise operators, and they "shift" a value respectively right and left by a certain number of bits, throwing away bits that roll of the end you're shifting towards, and feeding in zero bits at the other end.</p>
<p>So, for example:</p>
<pre><code>1001 0101 >> 2 gives 0010 0101
1111 1111 << 4 gives 1111 0000
</code></pre>
<p>Note that the left shift in Python is unusual in that it's not using a fixed width where bits are discarded - while many languages use a fixed width based on the data type, Python simply expands the width to cater for extra bits. In order to get the discarding behaviour in Python, you can follow a left shift with a bitwise <code>and</code> such as in an 8-bit value shifting left four bits:</p>
<pre><code>bits8 = (bits8 << 4) & 255
</code></pre>
<p>With that in mind, another example of bitwise operators is if you have two 4-bit values that you want to pack into an 8-bit one, you can use all three of your operators (<code>left-shift</code>, <code>and</code> and <code>or</code>):</p>
<pre><code>packed_val = ((val1 & 15) << 4) | (val2 & 15)
</code></pre>
<ul>
<li>The <code>& 15</code> operation will make sure that both values only have the lower 4 bits.</li>
<li>The <code><< 4</code> is a 4-bit shift left to move <code>val1</code> into the top 4 bits of an 8-bit value.</li>
<li>The <code>|</code> simply combines these two together.</li>
</ul>
<p>If <code>val1</code> is 7 and <code>val2</code> is 4:</p>
<pre><code> val1 val2
==== ====
& 15 (and) xxxx-0111 xxxx-0100 & 15
<< 4 (left) 0111-0000 |
| |
+-------+-------+
|
| (or) 0111-0100
</code></pre> |
33,565,949 | Add row to data frame with dplyr | <p>I have this sample data:</p>
<pre><code>cvar <- c("2015-11-01","2015-11-02","All")
nvar1 <- c(12,10,5)
nvar2 <- c(7,5,6)
data <- cbind.data.frame(cvar,nvar1,nvar2)
</code></pre>
<p>And I just want to add a new row to the data.frame containing the sums of nvar1 & nvar2 and a character, so with base R I would just use</p>
<pre><code>data[nrow(data)+1,] <- c("add",sum(data[,2]),sum(data[,3]))
</code></pre>
<p>or something more clever with lapply, but just to show you what I'm looking for.</p>
<p>I would like this simple command within the pipe environment, so data %>% ... gives me the above outcome. </p>
<p>Appreciate any help, thank you.</p> | 33,566,086 | 5 | 5 | null | 2015-11-06 11:37:38.573 UTC | 5 | 2020-02-23 10:02:05.16 UTC | 2015-11-06 11:40:26.33 UTC | null | 4,564,247 | null | 5,069,119 | null | 1 | 31 | r|dplyr | 66,103 | <p>Something like this then maybe:</p>
<pre><code>data %>%
rbind(c("add",sum(nvar1),sum(nvar2)))
# cvar nvar1 nvar2
#1 2015-11-01 12 7
#2 2015-11-02 10 5
#3 All 5 6
#4 add 27 18
</code></pre>
<p>Edit:</p>
<p>According to your comment, this will work:</p>
<pre><code>data %>%
mutate(nvar3 = nvar1) %>%
rbind(c("add",sum(nvar1),sum(nvar2),sum(.$nvar3)))
</code></pre>
<p>Using the <code>.</code> will allow <code>rbind</code> to find <code>nvar3</code> </p>
<p>Edit2:</p>
<p>Provide the new row as a list and it will maintain the column classes:</p>
<pre><code>> str(
+ data %>%
+ mutate(nvar3 = nvar1) %>%
+ rbind(list("add",sum(nvar1),sum(nvar2),sum(.$nvar3)))
+ )
'data.frame': 4 obs. of 4 variables:
$ cvar : chr "2015-11-01" "2015-11-02" "All" "add"
$ nvar1: num 12 10 5 27
$ nvar2: num 7 5 6 18
$ nvar3: num 12 10 5 27
</code></pre> |
8,519,128 | Can Sweave produce many pdfs automatically? | <p>I analyze measurements from many cities (hundreds), and need to create separate reports per city (in Adobe pdf-format).</p>
<p>My process is like this:</p>
<ol>
<li>First RStudio to prepare the data to be shown, saved in X.Rda.</li>
<li>In X.Rnw (RStudio) I read X.Rda, select one city, and produce the tables and plots.</li>
<li>In RStudio I press "Compile PDF" and the city-report X.pdf is produced.</li>
<li>I go to step 2, choose another city, and so on.</li>
</ol>
<p>This is very tedious, and looks perfect for a for-loop per city, but how can it be done?</p>
<p>Thank you r-contributors!</p>
<p>/Chris</p> | 8,524,060 | 2 | 2 | null | 2011-12-15 11:10:17.47 UTC | 16 | 2014-02-12 09:19:31.837 UTC | 2013-01-03 20:40:55.567 UTC | null | 559,676 | null | 626,666 | null | 1 | 21 | r|sweave|knitr | 3,246 | <p>You can use something like a <code>for</code> loop with a global variable changing, which controls which city you want to weave into the report; see the other post <a href="https://stackoverflow.com/q/8434371/559676">Run Sweave or knitr with objects from existing R session</a></p>
<p>The code will be like (suppose <code>cities</code> is a character vector, and I use the <a href="http://yihui.github.com/knitr" rel="nofollow noreferrer"><code>knitr</code></a> package as an example because you can specify the filename of the output):</p>
<pre><code>for (city in cities) {
knit('city_template.Rnw', output = paste('report_', city, '.tex', sep = ''))
}
</code></pre>
<p>Inside <code>city_template.Rnw</code>, you have a chunk like</p>
<pre><code><<do-my-job>>=
make_plot(city, ...)
whatever(city, ...)
@
</code></pre>
<p>Then you will get a series of tex files named by the cities, and the rest of your job is to compile them to PDF (not possible for RStudio to compile multiple tex files, AFAIK, but it is trivial to do it in command line or in R with <code>texi2dvi()</code>).</p>
<p>There is one thing you need to be careful -- you have to use a different figure prefix (the option <code>fig.path</code>) for each output file, otherwise different cities can override each other's figure output. In <code>knitr</code>, this can be done by like this:</p>
<pre><code><<setup, echo=FALSE>>=
opts_chunk$set(fig.path = paste('my-prefix-', city, sep = ''))
@
</code></pre>
<p>I believe this should be safe to produce many reports with a loop.</p>
<p>BTW, you can certainly achieve the same goal with Sweave; perhaps you will know why I developed <code>knitr</code> later (this is off-topic, so I won't expand here).</p> |
8,938,841 | underscore.js nested templates | <p>Is it possible to somehow take a DOM element from a underscore template and use it as another template?</p>
<p>The idea is that my app needs to render a document that contains a loop with items and a summary. I need to occasionaly re-render only the summary or a few items, so I cannot just re-render the whole document.</p>
<p>However, I would like to keep it simple for the app users to create their own templates for the document and I think that keeping everything in one file for a document would make it easier.</p>
<p>I'm trying to use something like this:</p>
<pre><code><script type="text/template" id="document-template">
<div id="document">
<h1><%= name %></h1>
<ul class="items">
<% _.each(items, function(item) { %>
<li><%= item %></li>
<% }); %>
</ul>
<div id="summary">
<p>Total items: <%= totalitems %></p>
</div>
</div>
</script>
</code></pre>
<p>Now, I can easily do this var <code>documentTemplate = _.template($('#document-template').html());</code> to turn this into a document template, but I would like to turn the summary part into a template and a list item into a template as well.</p>
<p>Can I do something like this:</p>
<pre><code>var summaryTemplate = _.template($('#document-template #summary').html());
var itemTemplate = _.template($('#document-template .items li').html());
</code></pre>
<p>PS. Actually I am loading the template from an external file using jQuery's $.get. This way I will get the document-template in one big string. From there, I can do just <code>documentTemplate = _.template(loadedString);</code>.</p>
<p>Now, if I could just extract the #summary element from the string, it should work. But when I try to convert the string to DOM element ( <code>var domElement = $(loadedString)</code>)
(so I could do this: <code>summaryTemplate = _.template($('#summary',domElement).html());</code>, it won't work, because underscore won't recognize the <%= %> tags anymore.</p> | 13,649,447 | 5 | 2 | null | 2012-01-20 08:55:20.303 UTC | 14 | 2022-09-22 00:18:30.607 UTC | 2012-01-20 09:09:26.603 UTC | null | 895,511 | null | 895,511 | null | 1 | 47 | templates|underscore.js | 20,269 | <p>You can pass the nested template as a variable in the template assignments to the main template, e.g.:</p>
<p>HTML:</p>
<pre><code><script type="text/template" id="sub_template">
<article>
<h1>id: <%= id %><h1>
</article>
</script>
<script type="text/template" id="main_template">
<% for (var i = 0; i < num; i++) { %>
<%= renderSub({id:i}) %>
<% } %>
</script>
</code></pre>
<p>JS:</p>
<pre><code> var renderSub = _.template( $('#sub_template').remove().text() ),
renderMain = _.template( $('#main_template').remove().text() );
renderMain({num:5, renderSub:renderSub});
</code></pre> |
17,733,805 | Php - replace base color of transparent png image | <p>I have searched a lot and I found only few solutions (on google and stackoverflow so please don't mark this one as a duplicate unless there's really duplicate question), but problems are hard edges. Is there any proper way of changing base color of, let's say black shape png image with transparent background but to preserve soft edges?</p>
<p>This is an example image:</p>
<p><img src="https://i.stack.imgur.com/zUAyh.png" alt="enter image description here"></p>
<p>I want it to look like this:</p>
<p><img src="https://i.stack.imgur.com/JXeJs.png" alt="enter image description here"></p>
<p>but the solutions I found give me this one:</p>
<p><img src="https://i.stack.imgur.com/rE2t6.png" alt="enter image description here"></p>
<p>Since I will be using this on my localhost, only for personal use, any php library that could help achieve this is appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>This is the function that gives me 3rd image:</p>
<pre><code>function LoadPNG($imgname)
{
$im = imagecreatefrompng ($imgname);
imagetruecolortopalette($im,false, 255);
$index = imagecolorclosest ( $im, 0,0,0 ); // GET BLACK COLOR
imagecolorset($im,$index,0,150,255); // SET COLOR TO BLUE
$name = basename($imgname);
imagepng($im, getcwd()."/tmp/$name" ); // save image as png
imagedestroy($im);
}
$dir = getcwd()."/img/";
$images = glob($dir."/*.png",GLOB_BRACE);
foreach($images as $image) {
LoadPNG($image);
}
</code></pre>
<p>Originally, this function was a solution for GIF images (palette of 255 colors) so I guess that's why there are hard edges. I am looking for a solution (improvement to this script) to preserve transparency and soft edges of PNG image.</p>
<p><strong>EDIT 2:</strong></p>
<p>I have found an interesting approach using html5 canvas and javascript here:
<a href="http://users7.jabry.com/overlord/mug.html" rel="nofollow noreferrer">http://users7.jabry.com/overlord/mug.html</a></p>
<p>Maybe someone could have an idea how to translate this into PHP if even possible.</p>
<p><strong>NEW SOLUTION</strong></p>
<p>In answers</p> | 17,754,831 | 6 | 5 | null | 2013-07-18 21:01:56.417 UTC | 8 | 2020-06-19 07:11:31.463 UTC | 2013-07-19 07:57:31.013 UTC | null | 1,589,168 | null | 1,589,168 | null | 1 | 11 | php|image|colors|png|transparency | 9,000 | <p>This code doesn't exemplify the problem, but transforms colors like this:</p>
<p><img src="https://i.stack.imgur.com/4xUTk.jpg" alt="enter image description here"></p>
<p>Uses the ALPHA channel of an image to determines coloring. For other results, just play around with <code>imagecolorallocatealpha()</code>:</p>
<pre><code>function colorizeBasedOnAplhaChannnel( $file, $targetR, $targetG, $targetB, $targetName ) {
$im_src = imagecreatefrompng( $file );
$width = imagesx($im_src);
$height = imagesy($im_src);
$im_dst = imagecreatefrompng( $file );
// Note this:
// Let's reduce the number of colors in the image to ONE
imagefilledrectangle( $im_dst, 0, 0, $width, $height, 0xFFFFFF );
for( $x=0; $x<$width; $x++ ) {
for( $y=0; $y<$height; $y++ ) {
$alpha = ( imagecolorat( $im_src, $x, $y ) >> 24 & 0xFF );
$col = imagecolorallocatealpha( $im_dst,
$targetR - (int) ( 1.0 / 255.0 * $alpha * (double) $targetR ),
$targetG - (int) ( 1.0 / 255.0 * $alpha * (double) $targetG ),
$targetB - (int) ( 1.0 / 255.0 * $alpha * (double) $targetB ),
$alpha
);
if ( false === $col ) {
die( 'sorry, out of colors...' );
}
imagesetpixel( $im_dst, $x, $y, $col );
}
}
imagepng( $im_dst, $targetName);
imagedestroy($im_dst);
}
unlink( dirname ( __FILE__ ) . '/newleaf.png' );
unlink( dirname ( __FILE__ ) . '/newleaf1.png' );
unlink( dirname ( __FILE__ ) . '/newleaf2.png' );
$img = dirname ( __FILE__ ) . '/leaf.png';
colorizeBasedOnAplhaChannnel( $img, 0, 0, 0xFF, 'newleaf1.png' );
colorizeBasedOnAplhaChannnel( $img, 0xFF, 0, 0xFF, 'newleaf2.png' );
?>
Original
<img src="leaf.png">
<br />
<img src="newleaf1.png">
<br />
<img src="newleaf2.png">
</code></pre> |
17,925,904 | How to use complex number "i" in C++ | <p>I am coding a simple DFT algorithm now and I want to use the complex number i in complex exponential. I saw somebody use <code>#include<complex></code> and <code>#include<cmath></code>, and then they used the overloaded symbol <code>I</code> such as <code>exp(2*I)</code> . But it seems it doesn't work in my visual studio compiler. So, can anyone give a simple example of using complex exponential? Thanks!</p> | 17,926,277 | 6 | 7 | null | 2013-07-29 13:52:34.103 UTC | 5 | 2022-07-12 21:23:58.327 UTC | null | null | null | null | 2,586,769 | null | 1 | 9 | c++|overloading|complex-numbers|complextype | 49,264 | <p>Here is a short complete example:</p>
<pre><code>#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
typedef complex<double> dcomp;
int main() {
dcomp i;
dcomp a;
double pi;
pi = 2 * asin(1);
i = -1;
i = sqrt(i);
a = exp(pi*i) + 1.+0i;
cout << "i is " << i << "and Euler was right: exp(i pi) + 1 = " << a << endl;
}
</code></pre>
<p>Tested with g++</p> |
6,629,576 | Make css nth-child() only affect visible | <p>Is there a way to only affect visible elements with this css?</p>
<pre><code>table.grid tr.alt:nth-child(odd)
{
background:#ebeff4;
}
table.grid tr.alt:nth-child(even)
{
background:#ffffff;
}
</code></pre>
<p>If i use a <code>$('select some tr:s').hide()</code> that hides some of the rows i get a mix of odd and even styling but all in a mixup.</p> | 6,630,023 | 3 | 1 | null | 2011-07-08 19:38:54.733 UTC | 3 | 2014-07-30 20:53:33.813 UTC | 2014-05-07 07:11:58.527 UTC | null | 540,460 | null | 540,460 | null | 1 | 44 | jquery|css|css-selectors | 20,677 | <p>I ended up using the solution Rodaine suggested in his comment, after the show/hide i do this:</p>
<pre><code>$('.alt:visible:odd').css('background', '#EBEFF4');
$('.alt:visible:even').css('background', '#FFFFFF');
</code></pre>
<p>In my case the setting of background broke my hover, this was solved with <code>!important</code> to make the hover background stick.</p>
<pre><code>table.grid tr.hover:hover
{
cursor:pointer;
background:#D2E0E9 !important;
}
</code></pre> |
6,520,231 | How to force browser to download file? | <p>Everything works fine, but only if file is small, about 1MB, when I tried it with bigger files, like 20MB my browser display it, instead of force to download, I tried many headers so far, now my code looks:</p>
<pre><code>PrintWriter out = response.getWriter();
String fileName = request.getParameter("filename");
File f= new File(fileName);
InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
while(din.available() > 0){
out.print(din.readLine());
out.print("\n");
}
response.setContentType("application/force-download");
response.setContentLength((int)f.length());
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
in.close();
bin.close();
din.close();
</code></pre> | 6,520,353 | 3 | 5 | null | 2011-06-29 11:55:53.757 UTC | 14 | 2014-11-25 19:21:38.317 UTC | 2013-02-11 23:44:13.857 UTC | null | 318,465 | null | 779,195 | null | 1 | 56 | java|servlets|jakarta-ee | 114,135 | <p>You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.</p>
<p>Therefore, your method should be written as follows (this won't compile as it is a mere representation):</p>
<pre><code>response.setContentType("application/force-download");
response.setContentLength((int)f.length());
//response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);
InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
while(din.available() > 0){
out.print(din.readLine());
out.print("\n");
}
</code></pre>
<p>The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.</p>
<p>You may also refer to the Java EE API documentation for <a href="http://download.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#setContentType%28java.lang.String%29" rel="noreferrer">ServletResponse.setContentType</a> to understand this behavior:</p>
<blockquote>
<p>Sets the content type of the response being sent to the client, <strong>if the response has not been committed yet.</strong> The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.</p>
<p>This method may be called repeatedly to change content type and character encoding. <strong>This method has no effect if called after the response has been committed.</strong></p>
<p>...</p>
</blockquote> |
6,619,360 | Cannot convert 'this' pointer from 'const Line' to 'Line &' explanation? | <p>This method:</p>
<pre><code>bool Point::Intersects(const Line& line) const {
return (line.ContainsPoint(*this, false));
}
</code></pre>
<p>causes this error: cannot convert 'this' pointer from 'const Line' to 'Line &'
This change:</p>
<pre><code>bool Point::Intersects(const Line& line) const {
return const_cast<Line&>(line).ContainsPoint(*this, false);
}
</code></pre>
<p>fixes the error, but doesn't seem the right way to fix the issue. Why is the original method considered an error?</p>
<p>If it helps, <code>ContainsPoint(const Point& point, bool isInfinite)</code> is non-const and all methods it calls are non-const as well.</p> | 6,619,476 | 3 | 1 | null | 2011-07-08 02:29:13.55 UTC | 15 | 2018-03-26 22:50:47.233 UTC | 2013-04-15 15:45:16.963 UTC | null | 1,675,954 | null | 421,178 | null | 1 | 58 | c++|compiler-errors | 68,035 | <p>You actually provided the answer yourself, in a sense.</p>
<p>In your <code>Intersects</code> method, the parameter <code>line</code> is declared <code>const</code>. This restricts how you can use this variable. Specifically, you can only call <code>const</code> methods on it, and you can only pass it to methods expecting a <code>const</code> Line object.</p>
<p>However, you pointed out that <code>ContainsPoint</code> is not declared <code>const</code>. So it does not satisfy the requirement mention above (i.e. calling a non-<code>const</code> method on a <code>const</code> object is not allowed). This is why the original method generates the error, and it also explains why your second version works, since the restriction is alleviated via the <code>const_cast</code>.</p>
<p>The real problem is in the declaration of <code>ContainsPoint</code> (and probably also with whatever methods it calls, as they are also non-<code>const</code>). There appears to be a large design flaw here. Since the purpose of <code>ContainsPoint</code> is to check whether or not a <code>Point</code> is on a <code>Line</code>, side-effects will be unexpected. So there should be no reason for it to not be a <code>const</code> method. In fact (and your example shows this), users of <code>Line</code> would <em>expect</em> <code>ContainsPoint</code> to be a <code>const</code> method. Therefore, the real solution is to change the design of the <code>Line</code> class so that methods like <code>ContainsPoint</code> are declared <code>const</code>, and only methods which clearly change the state of an instance are left non-<code>const</code></p> |
6,940,384 | How to deal with symbol collisions between statically linked libraries? | <p>One of the most important rules and best practices when writing a library, is putting all symbols of the
library into a library specific namespace. C++ makes this easy, due to the <code>namespace</code> keyword. In
C the usual approach is to prefix the identifiers with some library specific prefix.</p>
<p>Rules of the C standard put some constraints on those (for safe compilation): A C compiler may look at only the first
8 characters of an identifier, so <code>foobar2k_eggs</code> and <code>foobar2k_spam</code> may be interpreted as the same
identifiers validly – however every modern compiler allows for arbitrary long identifiers, so in our times
(the 21st century) we should not have to bother about this.</p>
<p>But what if you're facing some libraries of which you cannot change the symbol names / idenfiers? Maybe you got
only a static binary and the headers or don't want to, or are not allowed to adjust and recompile yourself.</p> | 6,940,389 | 3 | 1 | null | 2011-08-04 11:14:17.66 UTC | 60 | 2017-06-17 21:18:37.103 UTC | 2017-05-30 09:08:59.43 UTC | null | 1,594,913 | null | 524,368 | null | 1 | 94 | c|static|libraries|collision|symbols | 39,354 | <p>At least in the case of <strong>static</strong> libraries you can work around it quite conveniently.</p>
<p>Consider those headers of libraries <em>foo</em> and <em>bar</em>. For the sake of this tutorial I'll also give you the source files</p>
<h3>examples/ex01/foo.h</h3>
<pre><code>int spam(void);
double eggs(void);
</code></pre>
<h3>examples/ex01/foo.c (this may be opaque/not available)</h3>
<pre><code>int the_spams;
double the_eggs;
int spam()
{
return the_spams++;
}
double eggs()
{
return the_eggs--;
}
</code></pre>
<h3>example/ex01/bar.h</h3>
<pre><code>int spam(int new_spams);
double eggs(double new_eggs);
</code></pre>
<h3>examples/ex01/bar.c (this may be opaque/not available)</h3>
<pre><code>int the_spams;
double the_eggs;
int spam(int new_spams)
{
int old_spams = the_spams;
the_spams = new_spams;
return old_spams;
}
double eggs(double new_eggs)
{
double old_eggs = the_eggs;
the_eggs = new_eggs;
return old_eggs;
}
</code></pre>
<p>We want to use those in a program foobar</p>
<h3>example/ex01/foobar.c</h3>
<pre><code>#include <stdio.h>
#include "foo.h"
#include "bar.h"
int main()
{
const int new_bar_spam = 3;
const double new_bar_eggs = 5.0f;
printf("foo: spam = %d, eggs = %f\n", spam(), eggs() );
printf("bar: old spam = %d, new spam = %d ; old eggs = %f, new eggs = %f\n",
spam(new_bar_spam), new_bar_spam,
eggs(new_bar_eggs), new_bar_eggs );
return 0;
}
</code></pre>
<p>One problem becomes apparent immediately: C doesn't know overloading. So we have two times two functions with
identical name but of different signature. So we need some way to distinguish those. Anyway, lets see what a
compiler has to say about this:</p>
<pre><code>example/ex01/ $ make
cc -c -o foobar.o foobar.c
In file included from foobar.c:4:
bar.h:1: error: conflicting types for ‘spam’
foo.h:1: note: previous declaration of ‘spam’ was here
bar.h:2: error: conflicting types for ‘eggs’
foo.h:2: note: previous declaration of ‘eggs’ was here
foobar.c: In function ‘main’:
foobar.c:11: error: too few arguments to function ‘spam’
foobar.c:11: error: too few arguments to function ‘eggs’
make: *** [foobar.o] Error 1
</code></pre>
<p>Okay, this was no surprise, it just told us, what we already knew, or at least suspected.</p>
<p>So can we somehow resolve that identifer collision without modifying the original libraries'
source code or headers? In fact we can.</p>
<p>First lets resolve the compile time issues. For this we surround the header includes with a
bunch of preprocessor <code>#define</code> directives that prefix all the symbols exported by the library.
Later we do this with some nice cozy wrapper-header, but just for the sake of demonstrating
what's going on were doing it verbatim in the <em>foobar.c</em> source file:</p>
<h3>example/ex02/foobar.c</h3>
<pre><code>#include <stdio.h>
#define spam foo_spam
#define eggs foo_eggs
# include "foo.h"
#undef spam
#undef eggs
#define spam bar_spam
#define eggs bar_eggs
# include "bar.h"
#undef spam
#undef eggs
int main()
{
const int new_bar_spam = 3;
const double new_bar_eggs = 5.0f;
printf("foo: spam = %d, eggs = %f\n", foo_spam(), foo_eggs() );
printf("bar: old spam = %d, new spam = %d ; old eggs = %f, new eggs = %f\n",
bar_spam(new_bar_spam), new_bar_spam,
bar_eggs(new_bar_eggs), new_bar_eggs );
return 0;
}
</code></pre>
<p>Now if we compile this...</p>
<pre><code>example/ex02/ $ make
cc -c -o foobar.o foobar.c
cc foobar.o foo.o bar.o -o foobar
bar.o: In function `spam':
bar.c:(.text+0x0): multiple definition of `spam'
foo.o:foo.c:(.text+0x0): first defined here
bar.o: In function `eggs':
bar.c:(.text+0x1e): multiple definition of `eggs'
foo.o:foo.c:(.text+0x19): first defined here
foobar.o: In function `main':
foobar.c:(.text+0x1e): undefined reference to `foo_eggs'
foobar.c:(.text+0x28): undefined reference to `foo_spam'
foobar.c:(.text+0x4d): undefined reference to `bar_eggs'
foobar.c:(.text+0x5c): undefined reference to `bar_spam'
collect2: ld returned 1 exit status
make: *** [foobar] Error 1
</code></pre>
<p>... it first looks like things got worse. But look closely: Actually the compilation stage
went just fine. It's just the linker which is now complaining that there are symbols colliding
and it tells us the location (source file and line) where this happens. And as we can see
those symbols are unprefixed.</p>
<p>Let's take a look at the symbol tables with the <strong>nm</strong> utility:</p>
<pre><code>example/ex02/ $ nm foo.o
0000000000000019 T eggs
0000000000000000 T spam
0000000000000008 C the_eggs
0000000000000004 C the_spams
example/ex02/ $ nm bar.o
0000000000000019 T eggs
0000000000000000 T spam
0000000000000008 C the_eggs
0000000000000004 C the_spams
</code></pre>
<p>So now we're challenged with the exercise to prefix those symbols in some opaque binary. Yes, I know
in the course of this example we have the sources and could change this there. But for now, just assume
you have only those <em>.o</em> files, or a <em>.a</em> (which actually is just a bunch of <em>.o</em>).</p>
<h3><em>objcopy</em> to the rescue</h3>
<p>There is one tool particularily interesting for us: <strong>objcopy</strong></p>
<p>objcopy works on temporary files, so we can use it as if it were operating in-place. There is one
option/operation called <em>--prefix-symbols</em> and you have 3 guesses what it does.</p>
<p>So let's throw this fella onto our stubborn libraries:</p>
<pre><code>example/ex03/ $ objcopy --prefix-symbols=foo_ foo.o
example/ex03/ $ objcopy --prefix-symbols=bar_ bar.o
</code></pre>
<p><em>nm</em> shows us that this seemed to work:</p>
<pre><code>example/ex03/ $ nm foo.o
0000000000000019 T foo_eggs
0000000000000000 T foo_spam
0000000000000008 C foo_the_eggs
0000000000000004 C foo_the_spams
example/ex03/ $ nm bar.o
000000000000001e T bar_eggs
0000000000000000 T bar_spam
0000000000000008 C bar_the_eggs
0000000000000004 C bar_the_spams
</code></pre>
<p>Lets try linking this whole thing:</p>
<pre><code>example/ex03/ $ make
cc foobar.o foo.o bar.o -o foobar
</code></pre>
<p>And indeed, it worked:</p>
<pre><code>example/ex03/ $ ./foobar
foo: spam = 0, eggs = 0.000000
bar: old spam = 0, new spam = 3 ; old eggs = 0.000000, new eggs = 5.000000
</code></pre>
<p>Now I leave it as an exercise to the reader to implement a tool/script that automatically extracts the
symbols of a library using <em>nm</em>, writes a wrapper header file of the structure </p>
<pre><code>/* wrapper header wrapper_foo.h for foo.h */
#define spam foo_spam
#define eggs foo_eggs
/* ... */
#include <foo.h>
#undef spam
#undef eggs
/* ... */
</code></pre>
<p>and applies the symbol prefix to the static library's object files using <em>objcopy</em>.</p>
<h2>What about shared libraries?</h2>
<p>In principle the same could be done with shared libraries. However shared libraries, the name tells it,
are shared among multiple programs, so messing with a shared library in this way is not such a good idea.</p>
<p>You will not get around writing a trampoline wrapper. Even worse you cannot link against the shared library
on the object file level, but are forced to do dynamic loading. But this deserves its very own article.</p>
<p>Stay tuned, and happy coding.</p> |
6,355,787 | How to pass ArrayList<HashMap<String, String>>from one activity to another | <p>How i can pass Array List from one Activity to another my array list is shown as follows</p>
<pre><code>ArrayList<HashMap<String, String>>
</code></pre> | 6,356,045 | 4 | 0 | null | 2011-06-15 09:40:57.203 UTC | 12 | 2014-09-20 13:01:59.75 UTC | 2014-09-20 13:01:59.75 UTC | null | 759,866 | null | 730,600 | null | 1 | 15 | android | 23,758 | <p>Use <a href="https://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20java.io.Serializable%29" rel="noreferrer"><code>putExtra(String, Serializable)</code></a> to pass the value in an Intent and <a href="https://developer.android.com/reference/android/content/Intent.html#getSerializableExtra(java.lang.String)" rel="noreferrer"><code>getSerializableExtra(String)</code></a> method to retrieve the data.</p>
<p><strong>Passing an <code>ArrayList<HashMap<String, String>></code> from Activity A to Activity B</strong></p>
<pre><code>Intent intent = new Intent(this, B.class);
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("sunil", "sahoo");
ArrayList<HashMap<String, String>> arl = new ArrayList<HashMap<String, String>>();
arl.add(hm);
intent.putExtra("arraylist", arl);
startActivityForResult(intent, 500);
</code></pre>
<p><strong>Retrieve the data in Activity B</strong></p>
<pre><code>ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
System.out.println("...serialized data.."+arl);
</code></pre> |
23,827,014 | invalid new-expression of abstract class type | <p>I am currently writing a raytracer for a university class.
In order to load Scenes from files I wrote an sdfloader to read sdf files and create scenes therefor.</p>
<p>if I now want to compile the loader i get the following error:</p>
<pre><code>rc/sdf_loader.cpp: In member function 'void SDFloader::add_shape(std::istringstream&)':
src/sdf_loader.cpp:95:58: error: invalid new-expression of abstract class type 'box'
&scene_.materials[mat]));
^
</code></pre>
<p>I tried to find a solution but failed.</p>
<p>The sdf_loader class looks like the following:</p>
<pre><code>class SDFloader {
public:
SDFloader();
~SDFloader();
Scene const& scene() const;
void read(std::string file);
private:
void add_material(std::istringstream&);
void add_shape(std::istringstream&);
void add_light(std::istringstream&);
void add_camera(std::istringstream&);
void apply_transformation(std::istringstream&);
private:
Scene scene_;
};
</code></pre>
<p>in my implementation of the sdf loader i wrote the method read():</p>
<pre><code>void SDFloader::add_shape(std::istringstream& iss) {
std::string name;
iss >> name;
if(name == "box") {
double x1,y1,z1,x2,y2,z2;
std::string mat;
iss >> name >> x1 >> y1 >> z1 >> x2 >> y2 >> z2 >> mat;
scene_.shapes.insert(new box(point(x1,y1,z1),
point(x2,y2,z2),
name,
&scene_.materials[mat]));
}
</code></pre>
<p>and for every other shape the same calls.</p>
<p>Where is the Problem in my code? I really don't see it</p>
<p>I am using <code>g++-4.9 - std=c++0x</code> to compile and link everything</p> | 23,827,093 | 4 | 2 | null | 2014-05-23 10:36:49.087 UTC | 7 | 2018-02-01 19:49:21.977 UTC | 2016-01-13 18:31:45.637 UTC | null | 1,841,194 | null | 3,622,299 | null | 1 | 37 | c++|compiler-errors|abstract-class | 141,975 | <blockquote>
<p>invalid new-expression of abstract class type 'box'</p>
</blockquote>
<p>There is nothing unclear about the error message. Your class <code>box</code> has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.</p>
<p>If this is a bug, fix your box class by implementing the missing member(s). </p>
<p>If it's by design, derive from box, implement the missing member(s) and use the derived class.</p> |
18,719,517 | How do I use the UISearchBar and UISearchDisplayController | <p>I have an app which displays quite a lot of data in a <code>UITableView</code>. I already added the <code>UISearchBar</code> and <code>UISearchDisplayController</code> in Interface Builder to the <code>UITableView</code>. But I do not know how to use it. If someone could provide a quick solution to this, I would be grateful. I just require it to work as you type to find matches of the search query in the <code>UITableView</code> cells (or from an array).</p>
<p><strong>UPDATE 1</strong>: Here's the code from the<code>numberOfRowsInSection</code> method:</p>
<pre><code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isSearching) {
return [searchResults count];
}
else {
if (section == 0) {
return 1;
}
else if (section == 1) {
return [basicQuantities count];
}
else if (section == 2) {
return [physicalQuantities count];
}
}
return nil;
}
</code></pre> | 18,719,797 | 2 | 2 | null | 2013-09-10 12:54:21.657 UTC | 21 | 2015-07-04 08:00:21.073 UTC | 2013-09-11 13:11:17.133 UTC | null | 2,232,413 | null | 2,232,413 | null | 1 | 26 | ios|objective-c|uitableview|uisearchbar|uisearchdisplaycontroller | 59,695 | <ul>
<li>First add the <strong>UISearchDisplayController</strong> to your table view</li>
<li>Then set its delegate.</li>
<li>Implement the following methods.</li>
</ul>
<p><a href="https://www.dropbox.com/s/jg0f2bx7e30ld22/Search%20Table%20Sample.zip?dl=0"><strong>Demo Project</strong></a></p>
<p><strong>In your .h File</strong></p>
<pre><code> @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UITableView *tblContentList;
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchBarController;
</code></pre>
<p><strong>In your .m File</strong></p>
<p><strong>Filling the sample data (Optional Only For Demo Purpose)</strong></p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
contentList = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"iPod", @"iPod touch", @"iMac", @"Mac Pro", @"iBook",@"MacBook", @"MacBook Pro", @"PowerBook", nil];
filteredContentList = [[NSMutableArray alloc] init];
}
</code></pre>
<p><strong>Now implement the Table View Delegate and Datasource</strong></p>
<pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (isSearching) {
return [filteredContentList count];
}
else {
return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (isSearching) {
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [contentList objectAtIndex:indexPath.row];
}
return cell;
}
</code></pre>
<p><strong>Search Function Responsible For Searching</strong></p>
<pre><code>- (void)searchTableList {
NSString *searchString = searchBar.text;
for (NSString *tempStr in contentList) {
NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame) {
[filteredContentList addObject:tempStr];
}
}
}
</code></pre>
<p><strong>Search Bar Implementation</strong></p>
<pre><code>- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(@"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
// [self.tblContentList reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[self searchTableList];
}
</code></pre> |
15,979,828 | Loop through an ArrayList of HashMaps Java | <pre><code>ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();
HashMap<String, Integer> check = new HashMap<String, Integer>();
</code></pre>
<p>I have some number of hashmaps in my array list and I want to compare the hashmaps for duplicates like this 0,1 0,2 0,3 0,4....1,2 1,3 1,4.....2,3 2,4 etc.</p>
<p>I was doing a nested for loop to so this but got stuck on how to access the hashmaps and tried this </p>
<pre><code>for (int a =0; a<myList.size();a++){
for(int b=a+1; b<myList.size();b++){
for (String key : myList[a].check.keySet())
}
}
</code></pre>
<p>But this does not work. How do I acess all the keys of my hashmap if their in the arraylist? How can I accomplish this?</p> | 15,979,869 | 2 | 1 | null | 2013-04-12 19:55:14.06 UTC | 2 | 2013-04-12 20:21:35.997 UTC | null | null | null | null | 1,546,412 | null | 1 | 6 | java|arraylist|hashmap | 38,151 | <p>the <code>[]</code> operator can only be used on arrays. List has a <code>get(int index)</code> method to get the element at a given index:</p>
<pre><code>for (String key : myList.get(a).keySet()) {
...
}
</code></pre>
<p>Java classes are documented: <a href="http://docs.oracle.com/javase/6/docs/api/" rel="noreferrer">http://docs.oracle.com/javase/6/docs/api/</a></p> |
15,524,275 | How to put listview inside a fragment | <p>How can I put a list view into a fragment? I use the default project setup with fixed tab.</p>
<p>It doesn't seem to work, and my app crashes.</p>
<p>Main activity</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.app.ListFragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
public final static String PREFS_NAME = "UserData";
@Override
protected void onCreate(Bundle savedInstanceState) {
//Only for safe mode
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/***********************************USER***************************/
//Get User info (if exist)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String id = settings.getString("id", "");
String pass = settings.getString("pass", "");
SectionsPagerAdapter mSectionsPagerAdapter;
//Else create New User
if (id == "")
{
System.out.println("Create New User...");
UserRegistration.CreateUser(getApplicationContext());
}
/**** OTHER*****/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 5 total pages.
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
case 4:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
/***********************************CONTEST INC**********************
String xmlURL;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
xmlURL = URL;
System.out.println("Case 1");
Document doc = XMLfunctions.XMLfromString(XMLfunctions.getXML(xmlURL));
NodeList nodes = doc.getElementsByTagName("contest");
for (int i = 0; i < nodes.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", XMLfunctions.getValue(e, "name"));
map.put("subtitle",XMLfunctions.getValue(e, "subtitle"));
mylist.add(map);
System.out.println(mylist);
}
//new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, android.R.id.text1, actions);
ListAdapter adapter = new SimpleAdapter(this.getActivity(), mylist , R.layout.contest_list,
new String[] { "name", "subtitle" },
new int[] { R.id.item_title, R.id.item_subtitle });
ListFragment.setListAdapter(adapter);
final ListView lv = getApplication().getActivity().getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
/*************************************END CONTEST*********************/
ContestList.GetList(getActivity(), 1, "mm", "njk");
//TextView dummyTextView = (TextView) rootView
// .findViewById(R.id.section_label);
String sectionNumb = Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER));
int cat1;
cat1 = Integer.parseInt(sectionNumb);
switch (cat1)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
return rootView;
}
}
}
</code></pre>
<p>ContestList class</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ContestList {
public final static String PREFS_NAME = "UserData";
public static String GetList(Context context, int type, String id, String pass)
{
String xmlURL;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
xmlURL = URL;
System.out.println("Case 1");
Document doc = XMLfunctions.XMLfromString(XMLfunctions.getXML(xmlURL));
NodeList nodes = doc.getElementsByTagName("contest");
for (int i = 0; i < nodes.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", XMLfunctions.getValue(e, "name"));
map.put("subtitle",XMLfunctions.getValue(e, "subtitle"));
mylist.add(map);
System.out.println(mylist);
}
//new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, android.R.id.text1, actions);
ListAdapter adapter = new SimpleAdapter(context, mylist , R.layout.contest_list,
new String[] { "name", "subtitle" },
new int[] { R.id.item_title, R.id.item_subtitle });
((ListActivity) context).setListAdapter(adapter);
final ListView lv = ((ListActivity) context).getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
//Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
return "OK";
}
public String adapter(ListAdapter adapter)
{/*
setListAdapter(adapter);
final ListView lv = getApplication().getActivity().getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});*/
return "OK";
}
}
</code></pre>
<p>activity_main layout:</p>
<pre><code> <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
</code></pre>
<p>Fragment_main_dummy layout:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
<TextView
android:id="@+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="2dp"
android:textSize="20dp" />
<TextView
android:id="@+id/item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="13dp" />
</code></pre>
<p></p>
<p>Someone know why my app crash? or have an alternative for put a listview inside a fragment?</p>
<p>Thanks</p>
<p>EDIT: </p>
<p>Error log</p>
<pre><code>03-20 12:53:31.219: E/AndroidRuntime(3104): FATAL EXCEPTION: main
03-20 12:53:31.219: E/AndroidRuntime(3104): java.lang.ClassCastException: com.time2win.MainActivity cannot be cast to android.app.ListActivity
03-20 12:53:31.219: E/AndroidRuntime(3104): at com.time2win.ContestList.GetList(ContestList.java:50)
03-20 12:53:31.219: E/AndroidRuntime(3104): at com.time2win.MainActivity$DummySectionFragment.onCreateView(MainActivity.java:241)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.view.ViewPager.populate(ViewPager.java:1012)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.view.ViewPager.populate(ViewPager.java:881)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1366)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-20 12:53:31.219: E/AndroidRuntime(3104): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.View.measure(View.java:15513)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.Choreographer.doFrame(Choreographer.java:532)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.os.Handler.handleCallback(Handler.java:725)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.os.Looper.loop(Looper.java:137)
03-20 12:53:31.219: E/AndroidRuntime(3104): at android.app.ActivityThread.main(ActivityThread.java:5039)
03-20 12:53:31.219: E/AndroidRuntime(3104): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 12:53:31.219: E/AndroidRuntime(3104): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 12:53:31.219: E/AndroidRuntime(3104): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 12:53:31.219: E/AndroidRuntime(3104): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 12:53:31.219: E/AndroidRuntime(3104): at dalvik.system.NativeStart.main(Native Method)
</code></pre> | 15,524,540 | 4 | 1 | null | 2013-03-20 13:00:07.59 UTC | 3 | 2014-11-19 10:09:58.187 UTC | 2013-03-20 14:50:07.047 UTC | null | 1,204,143 | null | 2,190,057 | null | 1 | 6 | android|listview|crash|fragment | 38,816 | <p>you could use ListFragment for that. it's nicely explained in the docs:</p>
<p><a href="http://developer.android.com/reference/android/app/ListFragment.html">http://developer.android.com/reference/android/app/ListFragment.html</a></p>
<p>also Vogela has tutorial on this:</p>
<p><a href="http://www.vogella.com/articles/AndroidListView/article.html#listfragments">http://www.vogella.com/articles/AndroidListView/article.html#listfragments</a></p> |
15,845,632 | Adding PreferenceFragment to FragmentPagerAdapter | <p>I am trying to add a <code>PreferenceFragment</code> to a <code>FragmentPagerAdapter</code>. </p>
<p>My class extends <code>FragmentActivity</code>, I have tried <code>FragmentTransaction</code>, as shown below as well as trying to add to the container and can't seem to get anything to work. <em>No</em> errors are thrown, in fact nothing happens.</p>
<p><strong>Main Activity:</strong></p>
<pre class="lang-java prettyprint-override"><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
</code></pre>
<p><strong>activity_main.xml:</strong></p>
<pre class="lang-xml prettyprint-override"><code><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
</android.support.v4.view.ViewPager>
</code></pre>
<p><strong>My Options menu selection:</strong></p>
<pre class="lang-java prettyprint-override"><code>android.app.FragmentManager fm;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
JJSettings settings = new JJSettings();
fm = getFragmentManager();
FragmentTransaction fragTrans = fm.beginTransaction();
// I also tried `replace()` here as well. Same 'nothing happens' result.
fragTrans.add(settings, "settings");
fragTrans.commit();
return true;
case R.id.menu_help:
menuHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p><strong>My settings</strong> <code>Fragment</code><strong>:</strong></p>
<pre class="lang-java prettyprint-override"><code>public class JJSettings extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
</code></pre>
<p>My preference would be to stick with <code>Fragments</code> if possible, meaning I'd rather not extend <code>PreferenceActivity</code> or take the user to another Activity that calls the <code>PreferenceFragment</code>, if at all possible. I'm just hoping I missed something in my research.</p>
<hr>
<p><strong>Edit</strong></p>
<pre><code>public class SectionsPagerAdapter extends FragmentPagerAdapter {
private int _count = 2;
public SectionsPagerAdapter(FragmentManager fm) { super(fm); }
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new JJMainFragment();
case 1:
return new JJPendingFragment();
default:
return null;
}
}
public void setCount(int count) { this._count = count; }
@Override
public int getCount() { return this._count; }
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.c_list).toUpperCase(Locale.ENGLISH);
case 1:
return getString(R.string.c_pending).toUpperCase(Locale.ENGLISH);
}
return null;
}
}
</code></pre> | 16,286,631 | 2 | 2 | null | 2013-04-06 00:23:50.427 UTC | 10 | 2019-01-16 12:51:48.743 UTC | 2013-04-06 00:37:24.587 UTC | null | 1,134,705 | null | 1,134,705 | null | 1 | 11 | android|android-fragmentactivity | 12,771 | <p><a href="https://stackoverflow.com/questions/13501424/fragmentpageradapter-exists-only-in-android-support-v4-app-and-not-android-app">This answer</a> led me to the solution of using the v13 support library, which includes a FragmentPagerAdapter that uses bona-fide android.app.Fragments so it can support the PreferenceFragment.</p>
<p>Assuming you use Eclipse and run the new app wizard with the "Scrollable Tabs + Swipe" Navigation (which gives you the v4 pager boilerplate), here are the modifications you need to make to upgrade to v13:</p>
<ul>
<li>Delete "android-support-v4.jar" file from your libs folder</li>
<li>Copy "android-support-v13.jar" from SDK_PATH\extras\android\support\v13; if it's not there, use the SDK manager to install or update "Extras/Android Support Library"</li>
</ul>
<p>Then, in the Java file:</p>
<ul>
<li>Change FragmentPagerAdapter import from v4 to v13</li>
<li>Change FragmentActivity to a plain Activity</li>
<li>Change calls to getSupportFragmentManager to getFragmentManager</li>
<li>Import all necessary classes from android.app instead of android.support.v4</li>
<li>(Except: you still need to use the v4 ViewPager, but it's compatible)</li>
</ul>
<p>I've copied the modified source below, verified on latest Jellybean.</p>
<p>MainActivity.java:</p>
<pre><code>package com.example.pagerwithpreferencesfragment;
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v13.app.FragmentPagerAdapter; // instead of v4.app...
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity { // no longer FragmentActivity
// these comments are now out-of-date; v13, not v4
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getFragmentManager()); // instead of getSupportFragmentMangager
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// this is just to show it compiles
if (position == 0) {
// you should really make this a public class elsewhere..
return new PreferenceFragment() {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preferences);
}
};
}
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
</code></pre>
<p>settings_preferences.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="my_category_key"
android:title="My Title">
<CheckBoxPreference
android:key="pref_key"
android:title="Title"
android:summary="Summary"
android:defaultValue="false"
/>
</PreferenceCategory>
</PreferenceScreen>
</code></pre>
<p><img src="https://i.stack.imgur.com/8anXh.png" alt="enter image description here"></p> |
953,259 | An obvious singleton implementation for .NET? | <p>I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:</p>
<pre><code>if (instance == null)
{
instance = new Foo();
}
return instance;
</code></pre>
<p>Anyone who knows what a Singleton is is familiar with the issue(you only need the if once). It's trivial but irritating.</p>
<p>So, I thought of an alternate solution, at least for .NET(although it should work anywhere
that has some equivalent to function pointers:</p>
<pre><code>public class Foo
{
private delegate Foo FooReturner();
private static Foo innerFoo;
private static FooReturner fooReturnHandler = new FooReturner(InitialFooReturner);
public static Foo Instance
{
get
{
return fooReturnHandler();
}
}
private static Foo InitialFooReturner()
{
innerFoo = new Foo();
fooReturnHandler = new FooReturner(NewFooReturner);
return innerFoo;
}
private static Foo NewFooReturner()
{
return innerFoo;
}
}
</code></pre>
<p>In short - the Instance returns a delegate method. The delegate is initially set to a method
that initializes your instance, then changes the delegate to point at a simple Return method.</p>
<p>Now, I like to think I'm not terrible at my job, but I have no pretensions about being awesome. I have not seen an example of this code anywhere.</p>
<p>Ergo, I come to the conclusion that I am missing something. Something major. Either that the whole problem is too trivial to bother thinking that much about or this does something horrible that will destroy the universe. Or I fail at searching and therefore haven't seen
the hundreds of developers using this method. Something, anyway.</p>
<p>I was hoping the good folks here at Stack Overflow could clue me in as to what(leaving aside the controversy on whether one should use a Singleton at all).</p>
<p>EDIT for clarification:</p>
<p>This is not performance code(although if the design actively degrades performance beyond the traditional model, that would be interesting to know). </p>
<p>It was written purely as proof-of-concept, and I am further aware that it is not thread-safe as it properly should be. Is there any reason why it could NOT be made thread-safe by it's very nature? </p> | 953,281 | 7 | 3 | null | 2009-06-04 21:38:21.893 UTC | 17 | 2017-08-16 20:38:27.7 UTC | 2009-06-04 22:10:06.34 UTC | null | 117,660 | null | 117,660 | null | 1 | 19 | c#|.net|singleton | 3,604 | <p><a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow noreferrer">This is the canonical, thread safe, lazy Singleton pattern in C#</a>:</p>
<pre><code>public sealed class Singleton
{
Singleton(){}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() {}
internal static readonly Singleton instance = new Singleton();
}
}
</code></pre> |
109,134 | How do you change the style of a div programmatically | <p>How do I change the style (color) of a div such as the following? </p>
<pre><code>"<div id=foo class="ed" style="display: <%= ((foo.isTrue) ? string.Empty : "none") %>">
<%= ((foo.isTrue) ? foo.Name: "false foo") %>"`
</code></pre> | 109,159 | 8 | 0 | null | 2008-09-20 19:46:42.98 UTC | 2 | 2020-05-12 22:00:40.423 UTC | 2017-10-11 03:17:05.92 UTC | null | 1,033,581 | Joe | 15,059 | null | 1 | 11 | asp.net|asp.net-mvc | 51,095 | <p>If you want to alter the color of the div with client side code (javascript) running in the browser, you do something like the following:</p>
<pre><code><script>
var fooElement = document.getElementById("foo");
fooElement.style.color = "red"; //to change the font color
</script>
</code></pre> |
731,461 | How to check for an Empty Gridview | <p>I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.</p>
<p>I want to know how to check if the gridview is empty, and the do something. </p>
<p>I have already tried:</p>
<pre><code>if(GridView.Rows.Count == 0)
{
// Do Something
}
</code></pre>
<p>but it doesn't work...</p>
<p>Any ideas?</p>
<p>Thank you.</p> | 731,489 | 8 | 0 | null | 2009-04-08 19:28:28.383 UTC | 6 | 2017-03-24 01:42:24.403 UTC | null | null | null | null | 70,398 | null | 1 | 17 | c#|asp.net|gridview|null | 89,102 | <p>Your code <em>should</em> work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.</p>
<pre><code>DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
ShowEmptyData();
}
else
{
Grid.DataSource = dt;
Grid.DataBind();
}
</code></pre> |
1,211,881 | Why is the GET method faster than POST in HTTP? | <p>I am new to web programming and just curious to know about the GET and POST methods of sending data from one page to another.</p>
<p>It is said that the GET method is faster than POST but I don't know why.
One reason I could find is that GET can take only 255 characters?
Is there any other reason? Please someone explain to me.</p> | 1,211,897 | 8 | 1 | null | 2009-07-31 10:45:17.31 UTC | 12 | 2019-03-21 20:41:11.847 UTC | 2019-03-21 20:41:11.847 UTC | null | 964,243 | null | 68,287 | null | 1 | 50 | http|post|get | 42,717 | <p>It's not much about speed. There are plenty of cases where POST is more applicable. For example, search engines will index GET URLs and browsers can bookmark them and make them show up in history. As a result, if you take actions like modifying a DB based on a GET request, it might be harmful as some bots might also traverse the URL. </p>
<p>The other case can be security issue. If you post credentials using GET, it'll get listed in browser history and server log files.</p> |
754,520 | What is the actual differences between I18n/L10n/G11n and specifically what does each mean for development? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/506743/localization-and-internationalization-whats-the-difference">Localization and internationalization, what’s the difference?</a> </p>
</blockquote>
<p>I18n/L10n/G11n all equal localization to me, but people keep making distinctions among these, especially in corporate and marketing, but I'm failing to see how these 3 tasks, from the programmer's point of view aren't the same thing, are there special requirements behind each one of these? What is some honest programmer to programmer explanations of these terms that doesn't involve global markets, in other words what's the nitty-gritty differences behind these three terms, when translated to developing (coding) software?</p>
<p>thanks!</p> | 754,557 | 8 | 0 | null | 2009-04-16 02:23:20.253 UTC | 25 | 2022-07-16 19:56:26.11 UTC | 2017-05-23 12:09:39.513 UTC | null | -1 | null | 15,124 | null | 1 | 72 | localization|internationalization|globalization | 37,482 | <p>Here's an article from the W3C: <a href="http://www.w3.org/International/questions/qa-i18n" rel="noreferrer">Localization vs. Internationalization</a></p>
<p>The short answer from them seems to be: </p>
<blockquote>
<p>Localization refers to the <strong>adaptation</strong>
of a product, application or document
content to meet the language, cultural
and other requirements of a specific
target market (a "locale").</p>
<p>Internationalization is the design and
development of a product, application
or document content that <strong>enables</strong> easy
localization for target audiences that
vary in culture, region, or language.</p>
</blockquote>
<p>So, it seems that internationalization is making the product able to be localized to a specific market. According to the W3C, globalization is another term for internationalization.</p>
<p>Personally, I use them mostly interchangeably but check out the article for more specificity of what each entails.</p> |
44,383 | Reading Email using Pop3 in C# | <p>I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in <a href="http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx?fid=341657" rel="noreferrer">CodeProject</a>. However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode.</p> | 44,393 | 8 | 0 | null | 2008-09-04 18:21:06.653 UTC | 40 | 2017-09-09 18:25:44.427 UTC | null | null | null | Eldila | 889 | null | 1 | 75 | c#|unicode|pop3 | 137,090 | <p>I've successfully used <a href="http://sourceforge.net/projects/hpop/" rel="noreferrer">OpenPop.NET</a> to access emails via POP3. </p> |
670,662 | What's the maximum value for an int in PHP? | <p>Ignoring the special libraries that allow you to work with very big numbers, what's the largest int value you can store in PHP?</p> | 670,668 | 8 | 0 | null | 2009-03-22 07:33:34.02 UTC | 17 | 2019-06-29 13:14:42.443 UTC | 2018-06-05 03:32:54.303 UTC | null | 1,897,974 | nickf | 9,021 | null | 1 | 139 | php|integer | 147,684 | <p>From the <a href="http://php.net/manual/en/language.types.integer.php" rel="noreferrer">PHP manual</a>:</p>
<blockquote>
<p>The size of an integer is
platform-dependent, although a maximum
value of about two billion is the
usual value (that's 32 bits signed).
PHP does not support unsigned
integers. Integer size can be
determined using the constant
PHP_INT_SIZE, and maximum value using
the constant PHP_INT_MAX since PHP
4.4.0 and PHP 5.0.5.</p>
<p>64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.</p>
</blockquote> |
598,672 | Squash the first two commits in Git? | <p>With <code>git rebase --interactive <commit></code> you can squash any number of commits together into a single one.</p>
<p>That's all great unless you want to squash commits into the initial commit. That seems impossible to do.</p>
<p>Are there any ways to achieve it?</p>
<hr>
<h3>Moderately related:</h3>
<p>In a related question, I managed to come up with a different approach to the need of squashing against the first commit, which is, well, to make it the second one.</p>
<p>If you're interested: <a href="https://stackoverflow.com/questions/645450/git-how-to-insert-a-commit-as-the-first-shifting-all-the-others">git: how to insert a commit as the first, shifting all the others?</a></p> | 598,788 | 9 | 3 | null | 2009-02-28 20:55:09.473 UTC | 204 | 2021-06-26 10:49:14.777 UTC | 2017-05-23 12:26:36.443 UTC | user456814 | -1 | kch | 13,989 | null | 1 | 645 | git|rebase|git-rebase|squash | 186,039 | <p>Update July 2012 (<a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.7.12.txt#L59" rel="noreferrer">git 1.7.12+</a>)</p>
<p>You now can rebase all commits up to root, and select the second commit <code>Y</code> to be squashed with the first <code>X</code>.</p>
<pre><code>git rebase -i --root master
pick sha1 X
squash sha1 Y
pick sha1 Z
</code></pre>
<blockquote>
<pre><code>git rebase [-i] --root $tip
</code></pre>
</blockquote>
<blockquote>
<p>This command can now be used to rewrite all the history leading from "<code>$tip</code>" down to the root commit.</p>
</blockquote>
<p>See <a href="https://github.com/git/git/commit/df5df20c1308f936ea542c86df1e9c6974168472" rel="noreferrer">commit df5df20c1308f936ea542c86df1e9c6974168472 on GitHub</a> from <a href="https://github.com/arachsys" rel="noreferrer">Chris Webb (<code>arachsys</code>)</a>.</p>
<p>As noted <a href="https://stackoverflow.com/questions/598672/squash-the-first-two-commits-in-git/598788?noredirect=1#comment21126753_598788">in the comments</a>, a <a href="https://stackoverflow.com/a/52937476/6309"><code>git push --force-with-lease</code></a> (safer than <code>--force</code>, as <a href="https://stackoverflow.com/users/334451/mikko-rantalainen">Mikko Mantalainen</a> <a href="https://stackoverflow.com/questions/598672/squash-the-first-two-commits-in-git/598788?noredirect=1#comment120433781_598788">remind us</a>) would be needed after any <code>rebase</code> operation, if you need to publish that rework in a remote repository.</p>
<hr />
<p>Original answer (February 2009)</p>
<p>I believe you will find different recipes for that in the SO question "<strong><a href="https://stackoverflow.com/questions/435646/how-do-i-combine-the-first-two-commits-of-a-git-repository">How do I combine the first two commits of a git repository?</a></strong>"</p>
<p><a href="https://stackoverflow.com/users/19563/charles-bailey">Charles Bailey</a> provided there the most <a href="https://stackoverflow.com/questions/435646/how-do-i-combine-the-first-two-commits-of-a-git-repository/436530#436530">detailed answer</a>, reminding us that a commit is a full tree (not just diffs from a previous states).<br />
And here the old commit (the "initial commit") and the new commit (result of the squashing) will have no common ancestor.<br />
That mean you can not "<code>commit --amend</code>" the initial commit into new one, and then rebase onto the new initial commit the history of the previous initial commit (lots of conflicts)</p>
<p>(That last sentence is no longer true with <code>git rebase -i --root <aBranch></code>)</p>
<p>Rather (with <code>A</code> the original "initial commit", and <code>B</code> a subsequent commit needed to be squashed into the initial one):</p>
<ol>
<li><p>Go back to the last commit that we want to form the initial commit (detach HEAD):</p>
<pre><code> git checkout <sha1_for_B>
</code></pre>
</li>
<li><p>Reset the branch pointer to the initial commit, but leaving the index and working tree intact:</p>
<pre><code> git reset --soft <sha1_for_A>
</code></pre>
</li>
<li><p>Amend the initial tree using the tree from 'B':</p>
<pre><code> git commit --amend
</code></pre>
</li>
<li><p>Temporarily tag this new initial commit (or you could remember the new commit sha1 manually):</p>
<pre><code> git tag tmp
</code></pre>
</li>
<li><p>Go back to the original branch (assume master for this example):</p>
<pre><code> git checkout master
</code></pre>
</li>
<li><p>Replay all the commits after B onto the new initial commit:</p>
<pre><code> git rebase --onto tmp <sha1_for_B>
</code></pre>
</li>
<li><p>Remove the temporary tag:</p>
<pre><code> git tag -d tmp
</code></pre>
</li>
</ol>
<p>That way, the "<code>rebase --onto</code>" does not introduce conflicts during the merge, since it rebases history <em>made after</em> the last commit (<code>B</code>) to be squashed into the initial one (which was <code>A</code>) to <code>tmp</code> (representing the squashed new initial commit): trivial fast-forward merges only.</p>
<p>That works for "<code>A-B</code>", but also "<code>A-...-...-...-B</code>" (any number of commits can be squashed into the initial one this way)</p> |
821,692 | What does the property "Nonatomic" mean? | <p>What does "nonatomic" mean in this code?</p>
<pre><code>@property(nonatomic, retain) UITextField *theUsersName;
</code></pre>
<p>What is the difference between atomic and nonatomic?</p>
<p>Thanks</p> | 821,836 | 9 | 5 | null | 2009-05-04 19:52:40.593 UTC | 52 | 2016-04-01 18:35:18.33 UTC | 2016-04-01 18:35:18.33 UTC | null | 1,371,853 | user100051 | null | null | 1 | 150 | ios|objective-c|iphone|cocoa|properties | 72,737 | <p>Take a look at the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html" rel="noreferrer">Apple Docs</a>.</p>
<p>Basically, if you say <code>nonatomic</code>, and you generate the accessors using <code>@synthesize</code>, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects, which can easily lead to crashes. (This is potentially a lot faster than an atomic accessor, though.)</p>
<p>If you use the default (which is <code>atomic</code>; there used to be no keyword for this, but there <a href="http://lists.apple.com/archives/objc-language/2012/Mar/msg00022.html" rel="noreferrer">is now</a>), then the <code>@synthesize</code>d methods use an object-level lock to ensure that multiple reads/writes to a single property are serialized. As the Apple docs point out, <strong>this doesn't mean the whole object is thread-safe</strong>, but the individual property reads/writes are.</p>
<p>Of course, if you implement your own accessors rather than using <code>@synthesize</code>, I think these declarations do nothing except express your intent as to whether the property is implemented in a threadsafe manner.</p> |
871,858 | PHP Pass variable to next page | <p>It seems pretty simple but I can't find a good way to do it.</p>
<p>Say in the first page I create a variable</p>
<pre><code>$myVariable = "Some text";
</code></pre>
<p>And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).</p>
<p>How can I achieve this?</p>
<p>Thanks!</p> | 872,522 | 9 | 1 | null | 2009-05-16 06:58:45.773 UTC | 126 | 2021-06-23 10:23:22.48 UTC | 2017-07-18 19:15:16.627 UTC | null | 62,642 | null | 62,642 | null | 1 | 227 | php|variables|session | 959,448 | <p>HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. <em>Except</em> if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.</p>
<p><strong>Session:</strong></p>
<pre><code>//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
</code></pre>
<p>Remember to run the <code>session_start();</code> statement on both these pages before you try to access the <code>$_SESSION</code> array, and also before any output is sent to the browser.</p>
<p><strong>Cookie:</strong></p>
<pre><code>//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
</code></pre>
<p>The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.</p>
<p><strong>GET and POST</strong></p>
<p>You can add the variable in the link to the next page:</p>
<pre><code><a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>
</code></pre>
<p>This will create a GET variable. </p>
<p>Another way is to include a hidden field in a form that submits to page two:</p>
<pre><code><form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
</code></pre>
<p>And then on page two:</p>
<pre><code>//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
</code></pre>
<p>Just change the method for the form to <code>post</code> if you want to do it via post. Both are equally insecure, although GET is easier to hack.</p>
<p>The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.</p> |
1,207,983 | in general, should every table in a database have an identity field to use as a PK? | <p>This seems like a duplicate even as I ask it, but I searched and didn't find it. It seems like a good question for SO -- even though I'm sure I can find it on many blogs etc. out there. SO will have more of a debate than you can get on a blog. </p>
<p>I'm running into an issue with a join: getting back too many records. I think of this as "expansion". I added a table to the set of joins and the number of rows expanded, way too much. Usually when this happens I add a select of all the ID fields that are involved in the join. That way it's pretty obvious where the expansion is happening and I can change the ON of the join to fix it. Except in this case, the table that I added doesn't have an ID field. To me, this is a problem. But perhaps I'm wrong. </p>
<p>The question: should every table in a database have an IDENTITY field that's used as the PK? Are there any drawbacks to having an ID field in every table? What if you're reasonably sure this table will never be used in a PK/FK relationship? </p>
<p>Related, but not duplicate: <a href="https://stackoverflow.com/questions/932913/when-having-an-identity-column-is-not-a-good-idea">When having an identity column is not a good idea?</a></p>
<p>Apparently this debate has been <a href="http://en.wikipedia.org/wiki/Surrogate_key" rel="noreferrer">going on for a while</a>. Shoulda known. </p>
<p><a href="https://stackoverflow.com/questions/63090/surrogate-vs-natural-business-keys">This post</a> (surrogate vs. natural keys) is also relevant.</p> | 1,208,025 | 10 | 0 | null | 2009-07-30 17:08:59.31 UTC | 26 | 2016-08-25 21:08:57.843 UTC | 2017-05-23 12:02:53.007 UTC | null | -1 | null | 30,946 | null | 1 | 61 | sql|database|database-design | 47,461 | <p>There are two concepts that are close but should not be confused: <code>IDENTITY</code> and <code>PRIMARY KEY</code></p>
<p>Every table (except for the rare conditions) should have a <code>PRIMARY KEY</code>, that is a value or a set of values that uniquely identify a row.</p>
<p>See <a href="https://stackoverflow.com/questions/840162/should-each-and-every-table-have-a-primary-key"><strong>here</strong></a> for discussion why.</p>
<p><code>IDENTITY</code> is a property of a column in <code>SQL Server</code> which means that the column will be filled automatically with incrementing values.</p>
<p>Due to the nature of this property, the values of this column are inherently <code>UNIQUE</code>.</p>
<p>However, no <code>UNIQUE</code> constraint or <code>UNIQUE</code> index is automatically created on <code>IDENTITY</code> column, and after issuing <code>SET IDENTITY_INSERT ON</code> it's possible to insert duplicate values into an <code>IDENTITY</code> column, unless it had been explicity <code>UNIQUE</code> constrained.</p>
<p>The <code>IDENTITY</code> column should not necessarily be a <code>PRIMARY KEY</code>, but most often it's used to fill the surrogate <code>PRIMARY KEY</code>s</p>
<p>It may or may not be useful in any particular case.</p>
<p>Therefore, the answer to your question:</p>
<blockquote>
<p>The question: should every table in a database have an IDENTITY field that's used as the PK?</p>
</blockquote>
<p>is this:</p>
<h3>No. There are cases when a database table should NOT have an <code>IDENTITY</code> field as a <code>PRIMARY KEY</code>.</h3>
<p>Three cases come into my mind when it's not the best idea to have an <code>IDENTITY</code> as a <code>PRIMARY KEY</code>:</p>
<ul>
<li>If your <code>PRIMARY KEY</code> is composite (like in many-to-many link tables)</li>
<li>If your <code>PRIMARY KEY</code> is natural (like, a state code)</li>
<li>If your <code>PRIMARY KEY</code> should be unique across databases (in this case you use <code>GUID</code> / <code>UUID</code> / <code>NEWID</code>)</li>
</ul>
<p>All these cases imply the following condition:</p>
<h3>You shouldn't have <code>IDENTITY</code> when you care for the values of your <code>PRIMARY KEY</code> and explicitly insert them into your table.</h3>
<p><strong>Update:</strong></p>
<p>Many-to-many link tables should have the pair of <code>id</code>'s to the table they link as the composite key.</p>
<p>It's a natural composite key which you already have to use (and make <code>UNIQUE</code>), so there is no point to generate a surrogate key for this.</p>
<p>I don't see why would you want to reference a <code>many-to-many</code> link table from any other table except the tables they link, but let's assume you have such a need.</p>
<p>In this case, you just reference the link table by the composite key.</p>
<p>This query:</p>
<pre><code>CREATE TABLE a (id, data)
CREATE TABLE b (id, data)
CREATE TABLE ab (a_id, b_id, PRIMARY KEY (a_id, b_id))
CREATE TABLE business_rule (id, a_id, b_id, FOREIGN KEY (a_id, b_id) REFERENCES ab)
SELECT *
FROM business_rule br
JOIN a
ON a.id = br.a_id
</code></pre>
<p>is much more efficient than this one:</p>
<pre><code>CREATE TABLE a (id, data)
CREATE TABLE b (id, data)
CREATE TABLE ab (id, a_id, b_id, PRIMARY KEY (id), UNIQUE KEY (a_id, b_id))
CREATE TABLE business_rule (id, ab_id, FOREIGN KEY (ab_id) REFERENCES ab)
SELECT *
FROM business_rule br
JOIN a_to_b ab
ON br.ab_id = ab.id
JOIN a
ON a.id = ab.a_id
</code></pre>
<p>, for obvious reasons.</p> |
572,593 | What are the best Javascript/Flash frameworks to render graphs or charts from data? | <p>Ideally I'd like to do as little preparation data work on the server as possible. The less I have to do to prep the data from the database to make a given chart, the happier I am and the more view I can make in the time.</p>
<p>Some of the things I'd like to chart are, for example:</p>
<ul>
<li>The distribution of a series of response times</li>
<li>The number of occurrences per category (basic bar chart)</li>
</ul>
<p>I'm sure there are others I haven't thought of yet.</p>
<p>Anything that helps me get from a series such as:</p>
<p>[1, 2, 2, 2, 3, 4, 5, 5, 3, 1] or more likely something like [1.2, 3.2, 3.1, 1.1, 4.3, 3.4] where it isn't just a case of counting the frequency of the item</p>
<p>to an actual distribution would be great.</p>
<p>Thanks.</p>
<p><strong>EDIT:</strong> To clarify I guess I'm asking for more than just charting APIs, a search on Yahoo or Stack Overflow already finds answers to that. I'm looking for something that can help me turn data into visualizations with the least effort. So with the series above, something that could map it directly into some standard distributions such as a Gaussian distribution.</p> | 573,143 | 11 | 0 | null | 2009-02-21 07:38:45.843 UTC | 15 | 2016-05-23 21:44:16.873 UTC | 2009-02-23 16:04:15.47 UTC | sh1mmer | 53,569 | sh1mmer | 53,569 | null | 1 | 9 | javascript|flash|statistics|charts|visualization | 4,655 | <p>I like <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">Google Charts API</a>. It is brain-dead simple to use. You generate your data in the URL for an image, and the Google server spits back the GIF with the chart in it. You don't need JavaScript or Flash.</p> |
1,080,442 | How do I convert a Stream into a byte[] in C#? | <p>Is there a simple way or method to convert a <code>Stream</code> into a <code>byte[]</code> in C#?</p> | 1,080,445 | 12 | 2 | null | 2009-07-03 18:41:52.297 UTC | 74 | 2022-04-28 23:16:47.533 UTC | 2022-04-28 23:16:47.533 UTC | null | 3,241,128 | null | 6,068 | null | 1 | 450 | c#|arrays|inputstream | 590,102 | <p>Call next function like</p>
<pre><code>byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);
</code></pre>
<p>Function:</p>
<pre><code>public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if(stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if(stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
</code></pre> |
516,237 | When should I use typedef in C++? | <p>In my years of C++ (MFC) programming in I never felt the need to use <code>typedef</code>, so I don't really know what is it used for. Where should I use it? Are there any real situations where the use of <code>typedef</code> is preferred? Or is this really more a C-specific keyword?</p> | 516,253 | 13 | 2 | null | 2009-02-05 14:59:52.147 UTC | 33 | 2021-04-03 11:18:31.757 UTC | 2018-04-14 20:37:43.213 UTC | user8389458 | null | djeidot | 4,880 | null | 1 | 77 | c++|typedef | 62,001 | <h2>Template Metaprogramming</h2>
<p><code>typedef</code> is <em>necessary</em> for many <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="noreferrer">template metaprogramming</a> tasks -- whenever a class is treated as a "compile-time type function", a <code>typedef</code> is used as a "compile-time type value" to obtain the resulting type. E.g. consider a simple metafunction for converting a pointer type to its base type:</p>
<pre><code>template<typename T>
struct strip_pointer_from;
template<typename T>
struct strip_pointer_from<T*> { // Partial specialisation for pointer types
typedef T type;
};
</code></pre>
<p>Example: the type expression <code>strip_pointer_from<double*>::type</code> evaluates to <code>double</code>. Note that template metaprogramming is not commonly used outside of library development.</p>
<h2>Simplifying Function Pointer Types</h2>
<p><code>typedef</code> is <em>helpful</em> for giving a short, sharp alias to complicated function pointer types:</p>
<pre><code>typedef int (*my_callback_function_type)(int, double, std::string);
void RegisterCallback(my_callback_function_type fn) {
...
}
</code></pre> |
79,490 | linux uptime history | <p>How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.</p>
<p>Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.</p>
<p>Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.</p> | 79,540 | 14 | 2 | null | 2008-09-17 02:59:11.737 UTC | 6 | 2020-06-02 06:33:10.923 UTC | 2009-04-08 19:23:37.897 UTC | Jas | 60,261 | Jas | 777 | null | 1 | 39 | linux | 48,921 | <p>You could create a simple script which runs uptime and dumps it to a file.</p>
<pre><code>uptime >> uptime.log
</code></pre>
<p>Then set up a cron job for it.</p> |
319,728 | When to use the Bridge pattern and how is it different from the Adapter pattern? | <p>Has anyone ever used the <a href="https://www.dofactory.com/net/bridge-design-pattern" rel="nofollow noreferrer">Bridge pattern</a> in a real world application? If so, how did you use it? Is it me, or is it just the <a href="https://www.dofactory.com/net/adapter-design-pattern" rel="nofollow noreferrer">Adapter pattern</a> with a little dependency injection thrown into the mix? Does it really deserve its own pattern?</p> | 319,751 | 14 | 1 | null | 2008-11-26 04:12:44.347 UTC | 101 | 2022-05-06 14:53:33.667 UTC | 2022-04-29 22:45:06.343 UTC | null | 2,326,961 | Charles Graham | 7,705 | null | 1 | 168 | design-patterns|adapter|bridge | 91,924 | <p>A classic example of the Bridge pattern is used in the definition of shapes in an UI environment (see the <a href="http://en.wikipedia.org/wiki/Bridge_pattern" rel="noreferrer">Bridge pattern Wikipedia entry</a>). The Bridge pattern is a <a href="http://today.java.net/pub/a/today/2004/10/29/patterns.html" rel="noreferrer">composite</a> of the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="noreferrer">Template</a> and <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">Strategy</a> patterns.</p>
<p>It is a common view some aspects of the Adapter pattern in the Bridge pattern. However, to quote from <a href="http://www.informit.com/articles/article.aspx?p=30297" rel="noreferrer">this article</a>:</p>
<blockquote>
<p>At first sight, the Bridge pattern looks a lot like the Adapter pattern in that a class is used to convert one kind of interface to another. However, the intent of the Adapter pattern is to make one or more classes' interfaces look the same as that of a particular class. The Bridge pattern is designed to separate a class's interface from its implementation so you can vary or replace the implementation without changing the client code.</p>
</blockquote> |
890,440 | Obstructed folders in Subversion | <p>What the heck does "obstructed" mean when you try to check into Subversion? I see two folders in red with text status of "obstructed." I don't see what this means anywhere in the docs.</p>
<p>When I try the <code>cleanup</code> command, I get "folder name is not a working directory." This is a folder I just created in VS, and when I try to add it to Subversion it gives me that error. All other folders are fine.</p> | 890,466 | 17 | 1 | null | 2009-05-20 21:49:53.497 UTC | 22 | 2019-12-11 08:58:19.517 UTC | 2012-05-28 19:32:39.707 UTC | null | 122,607 | null | 93,468 | null | 1 | 132 | svn | 95,878 | <p>it occurs when you have deleted or moved the .svn subdirectories (without going through SVN commands), so SVN has a corrupted view of the working copy. </p>
<p>Try a cleanup first, and if that doesn't solve it, revert (or update) the directory to restore the subdirectory .svn folders.</p> |
688,760 | How to create a UTF-8 string literal in Visual C++ 2008 | <p>In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.</p>
<pre><code>printf("Chinese (Traditional)");
printf("中国語 (繁体)");
printf("중국어 (번체)");
printf("Chinês (Tradicional)");
</code></pre>
<p>I have saved the file in UTF-8 format with the UTF-8 BOM. However compiling with VC2008 results in:</p>
<pre><code>warning C4566: character represented by universal-character-name '\uC911'
cannot be represented in the current code page (932)
warning C4566: character represented by universal-character-name '\uAD6D'
cannot be represented in the current code page (932)
etc.
</code></pre>
<p>The characters causing these warnings are corrupted. The ones that do fit the locale (in this case 932 = Japanese) are converted to the locale encoding, i.e. Shift-JIS.</p>
<p>I cannot find a way to get VC++ 2008 to compile this for me. Note that it doesn't matter what locale I use in the source file. There doesn't appear to be a locale that says "I know what I'm doing, so don't f$%##ng change my string literals". In particular, the useless UTF-8 pseudo-locale doesn't work.</p>
<pre><code>#pragma setlocale(".65001")
=> error C2175: '.65001' : invalid locale
</code></pre>
<p>Neither does "C":</p>
<pre><code>#pragma setlocale("C")
=> see warnings above (in particular locale is still 932)
</code></pre>
<p>It appears that VC2008 forces all characters into the specified (or default) locale, and that locale cannot be UTF-8. I do not want to change the file to use escape strings like "\xbf\x11..." because the same source is compiled using gcc which can quite happily deal with UTF-8 files.</p>
<p>Is there any way to specify that compilation of the source file should leave string literals untouched?</p>
<p>To ask it differently, what compile flags can I use to specify backward compatibility with VC2003 when compiling the source file. i.e. do not change the string literals, use them byte for byte as they are.</p>
<p><b>Update</b></p>
<p>Thanks for the suggestions, but I want to avoid wchar. Since this app deals with strings in UTF-8 exclusively, using wchar would then require me to convert all strings back into UTF-8 which should be unnecessary. All input, output and internal processing is in UTF-8. It is a simple app that works fine as is on Linux and when compiled with VC2003. I want to be able to compile the same app with VC2008 and have it work. </p>
<p>For this to happen, I need VC2008 to not try to convert it to my local machine's locale (Japanese, 932). I want VC2008 to be backward compatible with VC2003. I want a locale or compiler setting that says strings are used as is, essentially as opaque arrays of char, or as UTF-8. It looks like I might be stuck with VC2003 and gcc though, VC2008 is trying to be too smart in this instance.</p> | 696,026 | 18 | 2 | null | 2009-03-27 06:48:29.72 UTC | 24 | 2021-07-06 19:54:29.733 UTC | 2009-03-29 03:29:56.093 UTC | brofield | 31,423 | brofield | 31,423 | null | 1 | 69 | c++|visual-c++|utf-8 | 56,102 | <p>Update:</p>
<p>I've decided that there is no guaranteed way to do this. The solution that I present below works for English version VC2003, but fails when compiling with Japanese version VC2003 (or perhaps it is Japanese OS). In any case, it cannot be depended on to work. Note that even declaring everything as L"" strings didn't work (and is painful in gcc as described below). </p>
<p>Instead I believe that you just need to bite the bullet and move all text into a data file and load it from there. I am now storing and accessing the text in INI files via <a href="http://code.jellycan.com/simpleini/" rel="noreferrer">SimpleIni</a> (cross-platform INI-file library). At least there is a guarantee that it works as all text is out of the program.</p>
<p>Original:</p>
<p>I'm answering this myself since only Evan appeared to understand the problem. The answers regarding what Unicode is and how to use wchar_t are not relevant for this problem as this is not about internationalization, nor a misunderstanding of Unicode, character encodings. I appreciate your attempt to help though, apologies if I wasn't clear enough.</p>
<p>The problem is that I have source files that need to be cross-compiled under a variety of platforms and compilers. The program does UTF-8 processing. It doesn't care about any other encodings. I want to have string literals in UTF-8 like currently works with gcc and vc2003. How do I do it with VC2008? (i.e. backward compatible solution). </p>
<p>This is what I have found:</p>
<p>gcc (v4.3.2 20081105):</p>
<ul>
<li>string literals are used as is (raw strings)</li>
<li>supports UTF-8 encoded source files</li>
<li>source files must not have a UTF-8 BOM</li>
</ul>
<p>vc2003:</p>
<ul>
<li>string literals are used as is (raw strings)</li>
<li>supports UTF-8 encoded source files</li>
<li>source files may or may not have a UTF-8 BOM (it doesn't matter)</li>
</ul>
<p>vc2005+:</p>
<ul>
<li>string literals are massaged by the compiler (no raw strings)</li>
<li>char string literals are re-encoded to a specified locale</li>
<li>UTF-8 is not supported as a target locale</li>
<li>source files must have a UTF-8 BOM</li>
</ul>
<p>So, the simple answer is that for this particular purpose, VC2005+ is broken and does not supply a backward compatible compile path. The only way to get Unicode strings into the compiled program is via UTF-8 + BOM + wchar which means that I need to convert all strings back to UTF-8 at time of use.</p>
<p>There isn't any simple cross-platform method of converting wchar to UTF-8, for instance, what size and encoding is the wchar in? On Windows, UTF-16. On other platforms? It varies. See the <a href="http://icu-project.org/docs/papers/unicode_wchar_t.html" rel="noreferrer">ICU project</a> for some details.</p>
<p>In the end I decided that I will avoid the conversion cost on all compilers other than vc2005+ with source like the following. </p>
<pre><code>#if defined(_MSC_VER) && _MSC_VER > 1310
// Visual C++ 2005 and later require the source files in UTF-8, and all strings
// to be encoded as wchar_t otherwise the strings will be converted into the
// local multibyte encoding and cause errors. To use a wchar_t as UTF-8, these
// strings then need to be convert back to UTF-8. This function is just a rough
// example of how to do this.
# define utf8(str) ConvertToUTF8(L##str)
const char * ConvertToUTF8(const wchar_t * pStr) {
static char szBuf[1024];
WideCharToMultiByte(CP_UTF8, 0, pStr, -1, szBuf, sizeof(szBuf), NULL, NULL);
return szBuf;
}
#else
// Visual C++ 2003 and gcc will use the string literals as is, so the files
// should be saved as UTF-8. gcc requires the files to not have a UTF-8 BOM.
# define utf8(str) str
#endif
</code></pre>
<p>Note that this code is just a simplified example. Production use would need to clean it up in a variety of ways (thread-safety, error checking, buffer size checks, etc).</p>
<p>This is used like the following code. It compiles cleanly and works correctly in my tests on gcc, vc2003, and vc2008:</p>
<pre><code>std::string mText;
mText = utf8("Chinese (Traditional)");
mText = utf8("中国語 (繁体)");
mText = utf8("중국어 (번체)");
mText = utf8("Chinês (Tradicional)");
</code></pre> |
307,291 | How does the Google "Did you mean?" Algorithm work? | <p>I've been developing an internal website for a portfolio management tool. There is a lot of text data, company names etc. I've been really impressed with some search engines ability to very quickly respond to queries with "Did you mean: xxxx".</p>
<p>I need to be able to intelligently take a user query and respond with not only raw search results but also with a "Did you mean?" response when there is a highly likely alternative answer etc</p>
<p>[I'm developing in <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> (VB - don't hold it against me! )]</p>
<p>UPDATE:
OK, how can I mimic this without the millions of 'unpaid users'?</p>
<ul>
<li>Generate typos for each 'known' or 'correct' term and perform lookups?</li>
<li>Some other more elegant method?</li>
</ul> | 307,344 | 18 | 5 | null | 2008-11-20 23:34:51.913 UTC | 295 | 2018-05-10 20:23:13.267 UTC | 2010-12-06 22:53:28.537 UTC | Oscar Reyes | 86,542 | Harry | 30,576 | null | 1 | 461 | algorithm|machine-learning|nlp|spell-checking|text-search | 98,695 | <p>Here's the explanation directly from the source ( almost ) </p>
<h2><strong><a href="http://www.youtube.com/watch?v=syKY8CrHkck#t=22m03s" rel="noreferrer">Search 101!</a></strong></h2>
<p>at min 22:03</p>
<p>Worth watching!</p>
<p>Basically and according to Douglas Merrill former CTO of Google it is like this:</p>
<p>1) You write a ( misspelled ) word in google </p>
<p>2) You don't find what you wanted ( don't click on any results )</p>
<p>3) You realize you misspelled the word so you rewrite the word in the search box.</p>
<p>4) You find what you want ( you click in the first links ) </p>
<p>This pattern multiplied millions of times, shows what are the most common misspells and what are the most "common" corrections. </p>
<p>This way Google can almost instantaneously, offer spell correction in every language.</p>
<p>Also this means if overnight everyone start to spell night as "nigth" google would suggest that word instead. </p>
<p><strong>EDIT</strong></p>
<p>@ThomasRutter: Douglas describe it as "statistical machine learning". </p>
<p>They know who correct the query, because they know which query comes from which user ( using cookies ) </p>
<p>If the users perform a query, and only 10% of the users click on a result and 90% goes back and type another query ( with the corrected word ) and this time that 90% clicks on a result, then they know they have found a correction. </p>
<p>They can also know if those are "related" queries of two different, because they have information of all the links they show. </p>
<p>Furthermore, they are now including the context into the spell check, so they can even suggest different word depending on the context. </p>
<p>See this <a href="http://www.youtube.com/watch?v=v_UyVmITiYQ#t=44m06s" rel="noreferrer">demo of google wave</a> ( @ 44m 06s ) that shows how the context is taken into account to automatically correct the spelling.</p>
<p><a href="http://www.youtube.com/watch?v=Sx3Fpw0XCXk" rel="noreferrer">Here</a> it is explained how that natural language processing works.</p>
<p>And finally here is an awesome demo of what can be done adding automatic <a href="http://www.youtube.com/watch?v=v_UyVmITiYQ#t=1h12m47s" rel="noreferrer">machine translation</a> ( @ 1h 12m 47s ) to the mix. </p>
<p><sub>
I've added anchors of minute and seconds to the videos to skip directly to the content, if they don't work, try reloading the page or scrolling by hand to the mark.
</sub></p> |
113,423 | Good Secure Backups Developers at Home | <p>What is a good, secure, method to do backups, for programmers who do research & development at home and cannot afford to lose any work?</p>
<p>Conditions:</p>
<ol>
<li><p>The backups must ALWAYS be within reasonably easy reach.</p></li>
<li><p>Internet connection cannot be guaranteed to be always available.</p></li>
<li><p>The solution must be either FREE or priced within reason, and subject to 2 above.</p></li>
</ol>
<hr>
<h2>Status Report</h2>
<p>This is for now only considering free options.</p>
<p>The following <strong>open-source projects</strong> are suggested in the answers (here & elsewhere):</p>
<ul>
<li><a href="http://backuppc.sourceforge.net/" rel="nofollow noreferrer">BackupPC</a> is a high-performance,
enterprise-grade system for backing
up Linux, WinXX and MacOSX PCs and
laptops to a server's disk.</li>
<li><a href="http://savannah.nongnu.org/projects/storebackup" rel="nofollow noreferrer">Storebackup</a> is a backup utility
that stores files on other disks.</li>
<li><a href="http://deekayen.net/mybackware" rel="nofollow noreferrer">mybackware</a>: These scripts were
developed to create SQL dump files
for basic disaster recovery of small
MySQL installations.</li>
<li><a href="http://www.bacula.org/en/" rel="nofollow noreferrer">Bacula</a> is [...] to manage
backup, recovery, and verification
of computer data across a network of
computers of different kinds. In
technical terms, it is a network
based backup program.</li>
<li><a href="http://www.metatrontech.com/projects/" rel="nofollow noreferrer">AutoDL 2 and Sec-Bk</a>: AutoDL 2
is a scalable transport independant
automated file transfer system. It
is suitable for uploading files from
a staging server to every server on
a production server farm [...]
Sec-Bk is a set of simple utilities
to securely back up files to a
remote location, even a public
storage location.</li>
<li><a href="http://www.rsnapshot.org/" rel="nofollow noreferrer">rsnapshot</a> is a filesystem
snapshot utility for making backups
of local and remote systems.</li>
<li><a href="http://schapiro.org/schlomo/projects/rbme.php" rel="nofollow noreferrer">rbme</a>: Using rsync for backups
[...] you get perpetual incremental
backups that appear as full backups
(for each day) and thus allow easy
restore or further copying to tape
etc.</li>
<li><a href="http://www.nongnu.org/duplicity/" rel="nofollow noreferrer">Duplicity</a> backs directories by
producing encrypted tar-format
volumes and uploading them to a
remote or local file server. [...]
uses librsync, [for] incremental
archives</li>
<li><a href="http://github.com/slashmais/simplebup" rel="nofollow noreferrer">simplebup</a>, to do real-time backup of files under active development, as they are modified. This tool can also be used for monitoring of other directories as well. It is intended as on-the-fly automated backup, and not as a version control. It is very easy to use.</li>
</ul>
<p><strong>Other Possibilities:</strong></p>
<p>Using a Distributed Version Control System (DVCS) such as <a href="http://git.or.cz/" rel="nofollow noreferrer">Git</a>(/<a href="http://www.gnome.org/~newren/eg/" rel="nofollow noreferrer">Easy Git</a>), <a href="http://bazaar-vcs.org/" rel="nofollow noreferrer">Bazaar</a>, <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a> answers the need to have the backup available locally. </p>
<p>Use free online storage space as a remote backup, e.g.: compress your work/backup directory and mail it to your gmail account.</p>
<p><strong>Strategies</strong></p>
<p>See <a href="https://stackoverflow.com/questions/113423/good-secure-backups-developers-at-home/2383368#2383368">crazyscot's answer</a></p> | 113,432 | 23 | 2 | 2008-10-03 16:50:30.207 UTC | 2008-09-22 06:16:04.473 UTC | 29 | 2014-08-09 18:45:36.833 UTC | 2017-05-23 12:02:53.363 UTC | A. Rex | -1 | slashmais | 15,161 | null | 1 | 36 | security|backup | 3,606 | <p>usb hard disk + <a href="http://samba.anu.edu.au/rsync/" rel="nofollow noreferrer">rsync</a> works for me</p>
<p>(see <a href="http://www.itefix.no/i2/node/10650" rel="nofollow noreferrer">here</a> for a Win32 build)</p> |
261,963 | How can I iterate over an enum? | <p>I just noticed that you can not use standard math operators on an <code>enum</code> such as <code>++</code> or <code>+=</code>.</p>
<p>So what is the best way to iterate through all of the values in a C++ <code>enum</code>?</p> | 261,986 | 28 | 6 | null | 2008-11-04 13:55:29.943 UTC | 72 | 2022-05-24 19:07:37.303 UTC | 2022-03-17 00:04:40.26 UTC | null | 2,287,576 | Adam | 1,366 | null | 1 | 396 | c++|enums | 431,847 | <p>The typical way is as follows:</p>
<pre><code>enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
</code></pre>
<p>Please note, the enum <code>Last</code> is meant to be skipped by the iteration. Utilizing this "fake" <code>Last</code> enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum.
If you want to add more enums later, just add them before Last. The loop in this example will still work. </p>
<p>Of course, this breaks down if the enum values are specified:</p>
<pre><code>enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
</code></pre>
<p>This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.</p>
<pre><code>switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
</code></pre>
<p>If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.</p> |
1,319,772 | How to determine why visual studio might be skipping projects when building a solution | <p>I am debugging someone else's work and the solution is quite large. When I try to build the entire thing, several projects within the solution don't build and just skip. Viewing the output window during the build process says:</p>
<blockquote>
<p>1>------ Skipped Rebuild All: Project: pr1lib ------</p>
</blockquote>
<p>How can I determine why these builds were skipped? I am unable to find additional output.</p>
<p>This is with VS2008 and the solution is comprised of c# and c++ code.</p> | 1,319,782 | 37 | 4 | null | 2009-08-23 22:37:57.16 UTC | 11 | 2021-12-12 07:22:24.373 UTC | 2018-04-09 21:44:31.78 UTC | null | 41,956 | null | 127,257 | null | 1 | 121 | visual-studio|msbuild | 100,163 | <p>Right click the solution, choose Properties and then Configuration Properties. Here you can choose which projects to build.</p>
<p>[<strong>edit</strong>]:<br>
See Kdt's comment: ... when I looked in configuration properties ... the project build target was configured for "Mixed Platforms" while the solution was set to build "Any CPU". </p>
<p>*When this problem happened to me, The main project only had 'Any CPU' and it set the child dll to 'any CPU' too, however, I'd deleted that profile and left only 'x86'. Picking x86 for just the dll make it start working<br>
[/edit]</p> |
6,668,008 | How do I break out of a map/collect and return whatever has been collected up to that point? | <p>I'm rewriting this question in code:</p>
<pre><code>many = 1000
# An expensive method.
#
# It returns some data or nil if no result is available.
expensive_method = lambda do
rand(5) == 0 ? nil : "foo"
end
# Now, let's collect some data and stop collecting when no more data is
# available.
# This is concise but doesn't work.
collection = many.times.map do
expensive_method.call || break
end
puts collection.is_a? Array # false
# This is less concise but works.
collection = []
many.times do
collection << (expensive_method.call || break)
end
puts collection.is_a? Array # true
# My inner Rubyist ponders: Is it possible to accomplish this more concisely
# using map?
</code></pre> | 37,999,319 | 6 | 3 | null | 2011-07-12 16:56:24.89 UTC | 4 | 2021-05-10 17:12:28.903 UTC | 2011-07-14 11:37:06.603 UTC | null | 185,245 | null | 185,245 | null | 1 | 30 | ruby | 15,912 | <p>Instead of using <code>map</code> directly, build up your own collection and then use the fact that <code>break</code> returns a value to abort early:</p>
<pre><code>result =
[0, 1, 2, 1, 0].each_with_object([]) { |val, accumulator|
if val < 2
accumulator << val
else
break accumulator
end
}
result # => [0, 1]
</code></pre>
<p>If we did just <code>break</code> (instead of <code>break accumulator</code>) then <code>nil</code> would be implicitly returned and <code>result</code> would just be set to <code>nil</code>.</p>
<p>This solution has the advantage of only allocating a single accumulator Array and only having to loop once.</p> |
6,932,369 | InputStream from a URL | <p>How do I get an InputStream from a URL?</p>
<p>for example, I want to take the file at the url <code>wwww.somewebsite.com/a.txt</code> and read it as an InputStream in Java, through a servlet.</p>
<p>I've tried</p>
<pre><code>InputStream is = new FileInputStream("wwww.somewebsite.com/a.txt");
</code></pre>
<p>but what I got was an error:</p>
<pre><code>java.io.FileNotFoundException
</code></pre> | 6,932,394 | 6 | 2 | null | 2011-08-03 19:48:09.173 UTC | 16 | 2019-03-19 15:36:00.813 UTC | 2015-08-21 03:25:27.723 UTC | null | 207,421 | null | 873,433 | null | 1 | 142 | java|url|inputstream | 192,258 | <p>Use <a href="http://download.oracle.com/javase/6/docs/api/java/net/URL.html#openStream%28%29" rel="noreferrer"><code>java.net.URL#openStream()</code></a> with a proper URL (including the protocol!). E.g.</p>
<pre><code>InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests">Using java.net.URLConnection to fire and handle HTTP requests</a></li>
</ul> |
6,846,544 | How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list | <p>I am configuring an MVC 3 project to work on a local install of IIS and came across the following 500 error:</p>
<blockquote>
<p>Handler "PageHandlerFactory-Integrated" has a bad module
"ManagedPipelineHandler" in its module list.</p>
</blockquote>
<p>It turns out that this is because ASP.Net was not completely installed with IIS even though I checked that box in the "Add Feature" dialog. To fix this, I simply ran the following command at the command prompt</p>
<pre><code>%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
</code></pre>
<p>If I had been on a 32 bit system, it would have looked like the following:</p>
<pre><code>%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
</code></pre>
<p>My question is, is there a way to install IIS on a windows 7 box to use .NET 4.0 (MVC 3) without taking this extra step?</p> | 10,541,165 | 19 | 2 | null | 2011-07-27 14:59:17.587 UTC | 117 | 2019-12-13 21:40:40.443 UTC | 2016-11-10 08:58:17.473 UTC | null | 4,054,186 | null | 525,780 | null | 1 | 545 | asp.net-mvc|iis-7|configuration|asp.net-4.0 | 320,310 | <p>It turns out that this is because ASP.Net was not completely installed with IIS even though I checked that box in the "Add Feature" dialog. To fix this, I simply ran the following command at the command prompt</p>
<pre><code>%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
</code></pre>
<p>If I had been on a 32 bit system, it would have looked like the following:</p>
<pre><code>%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
</code></pre>
<p><strong>Remeber to run the command prompt as administrator (<kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>ENTER</kbd>)</strong></p> |
15,987,321 | Joining multiple tables in SQL | <p>Can sombody Explains me about joins?</p>
<p>Inner join selects common data based on where condition.</p>
<p>Left outer join selects all data from left irrespective of common but takes common data from right table and vice versa for Right outer. </p>
<p>I know the basics but question stays when it comes to join for than 5, 8, 10 tables. </p>
<p>Suppose I have 10 tables to join. If I have inner join with the first 5 tables and now try to apply a left join with the 6th table, now how the query will work? </p>
<p>I mean to say now the result set of first 5 tables will be taken as left table and the 6th one will be considerded as Right table? Or only Fifth table will be considered as left and 6th as right? Please help me regarding this.</p> | 15,988,226 | 5 | 2 | null | 2013-04-13 11:33:00.46 UTC | 13 | 2021-03-07 13:04:11.937 UTC | 2013-04-16 06:19:00.513 UTC | null | 73,226 | null | 2,254,504 | null | 1 | 19 | sql|sql-server|join | 102,434 | <p>When joining multiple tables the output of each join logically forms a virtual table that goes into the next join.</p>
<p>So in the example in your question the composite result of joining the first 5 tables would be treated as the left hand table.</p>
<p>See <a href="http://www.sql.co.il/books/insidetsql2008/Logical%20Query%20Processing%20Poster.pdf">Itzik Ben-Gan's Logical Query Processing Poster</a> for more about this. </p>
<p>The virtual tables involved in the joins can be controlled by positioning the <code>ON</code> clause. For example</p>
<pre><code>SELECT *
FROM T1
INNER JOIN T2
ON T2.C = T1.C
INNER JOIN T3
LEFT JOIN T4
ON T4.C = T3.C
ON T3.C = T2.C
</code></pre>
<p>is equivalent to <code>(T1 Inner Join T2) Inner Join (T3 Left Join T4)</code></p> |
15,680,463 | Change IPython/Jupyter notebook working directory | <p>When I open a Jupyter notebook (formerly IPython) it defaults to <code>C:\Users\USERNAME</code>.</p>
<p>How can I change this so to another location?</p> | 15,682,400 | 32 | 1 | null | 2013-03-28 11:20:53.937 UTC | 116 | 2022-06-05 15:27:22.587 UTC | 2020-01-06 02:00:32.48 UTC | null | 6,042,824 | null | 390,388 | null | 1 | 291 | ipython|jupyter-notebook|jupyter | 646,284 | <p><code>jupyter notebook --help-all</code> could be of help:</p>
<pre><code>--notebook-dir=<Unicode> (NotebookManager.notebook_dir)
Default: u'/Users/me/ipynbs'
The directory to use for notebooks.
</code></pre>
<p>For example:</p>
<pre><code>jupyter notebook --notebook-dir=/Users/yourname/folder1/folder2/
</code></pre>
<p>You can of course set it in your profiles if needed, you might need to escape backslash in Windows.</p>
<p>Note that this will override whatever path you might have set in a jupyter_notebook_config.py file. (Where you can set a variable <code>c.NotebookApp.notebook_dir</code> that will be your default startup location.)</p> |
15,981,197 | Postgresql: ERROR: type "citext" does not exist | <p>I have read other posts, when searching, an answer to this question.</p>
<p>I am using PostgreSQL 9.1, and created extension 'citext' using <code>CREATE EXTENSION citext</code>, but when I try to create any columns of type 'citext', it throws this error</p>
<blockquote>
<p>ERROR: type "citext" does not exist </p>
</blockquote>
<p>I researched but did not find any concrete answers? Any idea why?</p> | 15,981,374 | 4 | 0 | null | 2013-04-12 21:32:54.053 UTC | 12 | 2019-10-20 18:52:37.683 UTC | 2019-01-21 13:09:12.173 UTC | null | 330,315 | null | 1,251,918 | null | 1 | 97 | postgresql-9.1 | 42,078 | <p>Ok figured it out. I have several databases and <code>CREATE EXTENSION citext</code> has to be run for each db to install the extension in that DB. You must do on psql prompt:</p>
<pre><code>psql =# \c db_1
CREATE EXTENSION citext;
psql =# \c db_2
CREATE EXTENSION citext;
</code></pre>
<p>Hope it helps others. Thank you.</p> |
10,316,567 | How do I create a Tab Control with no Tab Header in Windows form? | <p>I have created a Windows form using a Tab Control, but it has a header with it. I want to hide it. I am not able to do it using any properties of the Tab Control. Is there any property defined for hiding the tab header for the Tab Control without going through the code?</p> | 10,346,520 | 5 | 4 | null | 2012-04-25 13:20:28.093 UTC | 14 | 2018-03-02 18:49:20.813 UTC | 2018-03-02 18:49:20.813 UTC | null | 429,091 | null | 991,120 | null | 1 | 39 | c#|.net|winforms | 44,391 | <p>Use following code to hide the tabs or set these properties in design.</p>
<pre><code> tabControl.Appearance = TabAppearance.FlatButtons;
tabControl.ItemSize = new Size(0, 1);
tabControl.SizeMode = TabSizeMode.Fixed;
</code></pre> |
33,140,417 | How to fix div position while scrolling? | <p>I want to scroll div2 on mouse scroll without scrolling div1 and div3. What I want is when I scroll, position of div1 and div3 should be fixed. In our example when I scroll all the div scrolls , meaning div1 and div3 goes away from the screen. So I want to fix position of those divs. I have tried to achieve that using css(look at jsFiddle link), but failed. Kindly give some suggestions how can I able to scroll only div2 whereas div1 and div3's position should not be changed.
Thanks in advance.</p>
<blockquote>
<p>Link Demo : <a href="http://jsfiddle.net/patelsumit5192/sucx1t6z/" rel="nofollow noreferrer"><code>Demo</code></a></p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Div1 {
border: 1px solid #ddd;
width: 24%;
background-color: white;
float: left;
border: 2px solid #c00;
margin-right: 5px;
min-height: 50px;
}
.Div2 {
min-height: 1000px;
width: 45%;
margin-right: 5px;
overflow: auto;
background-color: green;
float: left
}
.Div3 {
border: 1px solid #ddd;
width: 24%;
background-color: white;
float: left;
border: 2px solid #c00;
min-height: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width: 100%; min-height: 200px;">
<div class="Div1">
Div1
</div>
<div class="Div2">Div2</div>
<div class="Div3">
Div3
</div>
</div></code></pre>
</div>
</div>
</p> | 33,140,910 | 3 | 6 | null | 2015-10-15 05:19:24.637 UTC | 6 | 2017-12-05 05:27:31.797 UTC | 2017-10-16 06:59:22.56 UTC | null | 2,873,907 | null | 2,873,907 | null | 1 | 3 | html|css | 53,519 | <p>Try this one , you can get your solution.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Div1 {
border: 1px solid #ddd;
width: 24%;
background-color: white;
float: left;
border: 2px solid #c00;
margin-right: 5px;
min-height: 50px;
position: fixed;
}
.Div2 {
min-height: 1000px;
width: 45%;
margin-right: 5px;
overflow: auto;
background-color: green;
position: absolute;
left: 28.5%;
}
.Div3 {
border: 1px solid #ddd;
width: 24%;
background-color: white;
border: 2px solid #c00;
min-height: 50px;
position: fixed;
right: 0px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width: 100%; min-height: 200px;">
<div class="Div1"> Div1</div>
<div class="Div2">Div2</div>
<div class="Div3"> Div3 </div>
</div></code></pre>
</div>
</div>
</p>
<p>This may helps you , and this is the <a href="http://jsfiddle.net/sucx1t6z/1/" rel="nofollow noreferrer">JS Fiddle DEMO</a></p> |
13,513,302 | How to set image on Texture in Unity 3d | <p>I am new to Unity 3D and I want to do just little task: to set image on a <code>Texture</code> instance in Unity 3D. I don't know how to do this at runtime, and I also would like to know how I set its transparency low.</p>
<p>I don't need Texture2D - I just need Texture. My image is in <code>.png</code> format. I also want set an image from my documents directory on to this texture. </p> | 13,519,375 | 3 | 0 | null | 2012-11-22 13:00:51.44 UTC | null | 2021-05-30 07:23:09.82 UTC | 2020-07-03 11:17:30.113 UTC | null | 588,306 | null | 1,471,676 | null | 1 | 8 | unity3d|textures | 49,329 | <ul>
<li><p>First import your image into your project by simply dropping it in your project window.</p>
</li>
<li><p>Select the image once it's in the project window and make sure that it is set to a Texture Type of Texture in your inspector.</p>
</li>
<li><p>Next, create a new material by right clicking in your project window.</p>
</li>
<li><p>Next you want to assign your image to this material and you can go about doing this by dragging and dropping your image (which is in the project window) on to your newly created material. In recent versions of Unity, you will need to drop it on the square to the left of "Albedo".</p>
</li>
<li><p>Then click on the new material and in your inspector window it should show you that your image is the active texture and the shader should be set to diffuse by default.</p>
</li>
<li><p>To activate transparency you'll want to change the shader type by clicking on the shader drop down menu in the inspector window and selecting Transparent/Diffuse (or any of the transparency options depending on what look you're going for).</p>
</li>
<li><p>After this to change it's transparency, simply click on the main color swatch and there should be a new window that opens giving you all kinds of modifiers (with 4 horizontal sliders to adjust Red, Green, Blue & Alpha).</p>
</li>
<li><p>Adjust the Alpha slider to affect the transparency of your material.</p>
</li>
</ul>
<p>Now, whenever you need to make a call to your material at runtime (e.g if you wanted to change the texture applied to a gameobject), simply do so by using:</p>
<pre><code>renderer.material
</code></pre>
<p>This will affect the material off the gameObject that the script is attached to. So for example, if you wanted to <a href="http://docs.unity3d.com/Documentation/ScriptReference/Material-mainTexture.html" rel="noreferrer"><strong>change the texture</strong></a> at runtime from script you could say:</p>
<pre><code>// Assign the texture exposed in the inspector the renderer's material
var texture : Texture;
renderer.material.mainTexture = texture;
</code></pre>
<p>And if you wanted to change the alpha channel:</p>
<pre><code>renderer.material.color.a = 0 // For example
</code></pre>
<p>Hope this helps. Let me know if anything needs clarifying.</p> |
13,670,152 | Why is #clone() not in the Cloneable interface? | <p>I was reading up on performing a deep-copy of an array correctly, however I was confused about how the <code>#clone()</code> is implemented. It is a member of the <code>java.lang.Object</code> class, and yet if you read the javadocs:</p>
<blockquote>
<p>First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown.</p>
</blockquote>
<p>So why define the <code>clone</code> method there in the first place? Surely if a method can only be used when an interface is present, you'd put the method in the interface. The <code>Cloneable</code> interface itself is empty; it is just a marker interface used by Java to ensure that using the <code>clone</code> method is legal.</p>
<p>Doing it this way also removes the ability to make use of generics to ensure type safety:</p>
<pre><code>class Foo implements Cloneable { // Valid.
@Override
public Object clone() throws CloneNotSupportedException {
// ...
}
}
class TypeSafeFoo implements Cloneable<TypeSafeFoo> { // Not valid.
@Override
public TypeSafeFoo clone() throws CloneNotSupportedException {
// ...
}
}
</code></pre>
<p>Why has Java done it this way? I'm sure they have legitimate reasons, but I can't seem to figure it out.</p> | 13,670,653 | 3 | 2 | null | 2012-12-02 14:22:16.733 UTC | 12 | 2013-06-27 09:10:52.363 UTC | null | null | null | null | 1,847,261 | null | 1 | 18 | java | 5,075 | <p>The cloning contract in Java dictates that each <code>clone</code> implementation must first obtain the cloned instance from <code>super.clone()</code>. This creates a chain that always ends with the call to <code>Object.clone</code>, and that method contains "magical" native-level code that makes a binary copy of the underlying raw <code>struct</code> which represents the Java object. If this mechanism didn't exist, <code>clone</code> would fail to be polymorphic: the <code>Object.clone</code> method produces an instance of whatever class it is called on; this cannot be reproduced without native code.</p>
<p>This is why the <code>Object.clone</code> method could not have been avoided. <code>Cloneable</code> <strong>could</strong> have contained a <code>clone</code> method, but it would create issues regarding the <code>throws</code> clause. The way it stands you are free to declare <code>clone</code> with no declared exceptions, or to declare arbitrary exceptions. This flexibility would not be possible if the method was already declared in the interface.</p>
<p>Bear in mind that Generics would be of little use for cloning: imagine <code>protected T clone()</code> in <code>Object</code>: where would <code>T</code> come from? Would we need <code>Object<T></code> and force <strong>each and every class in Java universe</strong> to be parameterized on itself, and all this just to make this semi-deprecated mechanism work a tiny bit better? Keep also in mind that this code is perfectly legal:</p>
<pre><code>public class TheMightyOne implements Cloneable {
@Override public TheMightyOne clone() {
return (TheMightyOne) super.clone();
}
}
</code></pre>
<p>You can call it:</p>
<pre><code>TheMightyOne one = new TheMightyOne();
TheMightyOne two = one.clone(); // do downcasts needed
</code></pre> |
13,229,235 | Django admin page Removing 'Group' | <p>How do I delete the model groups admin page? I want to show that by default, the group model. Thank you very much in advance.</p> | 13,229,260 | 2 | 0 | null | 2012-11-05 09:29:57.737 UTC | 6 | 2020-12-01 15:35:18.503 UTC | null | null | null | user1799680 | null | null | 1 | 31 | django | 16,174 | <p>Use the <code>unregister</code> method : </p>
<p>Add to the admin.py file :</p>
<pre><code>from django.contrib import admin
from django.contrib.auth.models import Group
admin.site.unregister(Group)
</code></pre> |
24,141,610 | CGSize sizeWithAttributes in Swift | <p>In objective-C I was able to use:</p>
<pre><code> CGSize stringsize =
[strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
</code></pre>
<p>But in Swift Language I didn't found any solution for this situation.</p>
<p>Any Help?</p> | 52,360,939 | 6 | 4 | null | 2014-06-10 12:57:49.53 UTC | 9 | 2019-07-03 12:40:41.863 UTC | 2018-11-22 12:17:26.213 UTC | null | 5,620,447 | null | 1,565,924 | null | 1 | 53 | ios|swift|cgsize | 46,145 | <p>Just one line solution:</p>
<p><code>yourLabel.intrinsicContentSize.width</code> for Objective-C / Swift</p>
<p>This will work even your label text have custom text spacing.</p> |
45,571,101 | How can I Display a JavaScript ES6 Map Object to Console? | <p>I'm using <a href="http://repl.it/languages/javascript" rel="noreferrer">repl.it/languages/javascript</a>.</p>
<p>Do I have to convert it to an object before I print it out?</p>
<p>I've tried </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> const mapObject = new Map();
mapObject.set(1, 'hello');
console.log(JSON.stringify(mapObject));
console.log(mapObject);</code></pre>
</div>
</div>
</p>
<p>The results are always empty object.</p>
<p>When I use </p>
<pre><code>console.log([...mapObject]);
</code></pre>
<p>It prints out an array format.</p> | 45,571,513 | 6 | 7 | null | 2017-08-08 14:30:13.277 UTC | 3 | 2021-11-07 00:04:58.65 UTC | 2020-12-20 00:56:31.87 UTC | null | 11,705,601 | null | 244,330 | null | 1 | 27 | javascript|dictionary|ecmascript-6|console.log|ecmascript-2016 | 45,640 | <p><strong>Note: This answer is only relevant to the repl.it sandbox environment OP is using</strong></p>
<p>Since you said in the comments that you're using <a href="https://repl.it/languages/javascript" rel="noreferrer">repl.it</a>, there's a trick you can use to write your own "logging strategy". </p>
<p>Note that you shouldn't use this trick in production, mainly because it edits a native prototype. In some Node environment, in your own code, it could be useful though.</p>
<p>The idea is to create an <code>inspect</code> method for <code>Map</code> that iterates over the <code>entries</code>:</p>
<pre><code>Map.prototype.inspect = function() {
return `Map(${mapEntriesToString(this.entries())})`
}
function mapEntriesToString(entries) {
return Array
.from(entries, ([k, v]) => `\n ${k}: ${v}`)
.join("") + "\n";
}
</code></pre>
<p>You can see that repl.it supports it <strong><a href="https://repl.it/KBcn" rel="noreferrer">here</a></strong></p>
<pre><code>console.log(new Map([["a", 1], ["b", 2]]));
// Logs:
/*
Map(
a: 1
b: 2
)
*/
</code></pre> |
16,420,669 | How to solve the Error: Inconsistent accessibility: parameter type for generic c# interface? | <p>On writting this code into my project i am getting the error that </p>
<blockquote>
<p>Error 1 Inconsistent accessibility: field type <code>'System.Collections.Generic.List<Jain_milan.Childrendata>'</code> is less accessible than field <code>'Jain_milan.addchild.m_children'</code><br>
Error 2 Inconsistent accessibility: parameter type <code>'System.Collections.Generic.List<Jain_milan.Childrendata>'</code> is less accessible than method <code>'Jain_milan.addchild.addchild(System.Collections.Generic.List<Jain_milan.Childrendata>)'</code> </p>
</blockquote>
<pre><code>namespace Jain_milan
{
public partial class addchild : Form
{
List<Label> label = new List<Label>();
List<TextBox> textbox = new List<TextBox>();
List<ComboBox> combobox = new List<ComboBox>();
List<DateTimePicker> datetimepicker = new List<DateTimePicker>();
public List<Childrendata> m_children = new List<Childrendata>();
public addchild(List<Childrendata> children)
{
InitializeComponent();
this.m_children = children; //Initialize the same List as sent by Mainform
}
</code></pre> | 16,420,800 | 5 | 4 | null | 2013-05-07 13:44:48.927 UTC | 3 | 2018-10-19 20:20:13.213 UTC | 2013-05-07 17:18:54.19 UTC | null | 20,335 | null | 2,214,972 | null | 1 | 13 | c# | 50,972 | <p>Without posting your entire relevant code i'll try a hunch:</p>
<p>the class <strong>Childrendata</strong> is declared as not-public and (as we can see) the variable <strong>m_children</strong> is public </p>
<p>Threfore a public variable cannot expose a less accessible type, in this case, <strong>Childrendata</strong> </p>
<p>Additionally, what you might want is to turn <strong>m_children</strong> private as well as this is usually the best practice</p> |
16,450,680 | Splitting String with delimiter | <p>I am currently trying to split a string <code>1128-2</code> so that I can have two separate values. For example, value1: 1128 and value2: 2, so that I can then use each value separately. I have tried <code>split()</code> but with no success. Is there a specific way Grails handles this, or a better way of doing it?</p> | 16,450,805 | 6 | 1 | null | 2013-05-08 21:40:31.897 UTC | 18 | 2020-04-24 09:22:40.683 UTC | 2018-06-08 13:06:15.013 UTC | null | 241,135 | null | 1,168,299 | null | 1 | 106 | string|groovy|split | 313,579 | <p>Try:</p>
<pre><code>def (value1, value2) = '1128-2'.tokenize( '-' )
</code></pre> |
16,194,054 | Is async HttpClient from .Net 4.5 a bad choice for intensive load applications? | <p>I recently created a simple application for testing the HTTP call throughput that can be generated in an asynchronous manner vs a classical multithreaded approach.</p>
<p>The application is a able to perform a predefined number of HTTP calls and at the end it displays the total time needed to perform them. During my tests, all HTTP calls were made to my local IIS sever and they retrieved a small text file (12 bytes in size).</p>
<p>The most important part of the code for the asynchronous implementation is listed below:</p>
<pre><code>public async void TestAsync()
{
this.TestInit();
HttpClient httpClient = new HttpClient();
for (int i = 0; i < NUMBER_OF_REQUESTS; i++)
{
ProcessUrlAsync(httpClient);
}
}
private async void ProcessUrlAsync(HttpClient httpClient)
{
HttpResponseMessage httpResponse = null;
try
{
Task<HttpResponseMessage> getTask = httpClient.GetAsync(URL);
httpResponse = await getTask;
Interlocked.Increment(ref _successfulCalls);
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedCalls);
}
finally
{
if(httpResponse != null) httpResponse.Dispose();
}
lock (_syncLock)
{
_itemsLeft--;
if (_itemsLeft == 0)
{
_utcEndTime = DateTime.UtcNow;
this.DisplayTestResults();
}
}
}
</code></pre>
<p>The most important part of the multithreading implementation is listed below:</p>
<pre><code>public void TestParallel2()
{
this.TestInit();
ServicePointManager.DefaultConnectionLimit = 100;
for (int i = 0; i < NUMBER_OF_REQUESTS; i++)
{
Task.Run(() =>
{
try
{
this.PerformWebRequestGet();
Interlocked.Increment(ref _successfulCalls);
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedCalls);
}
lock (_syncLock)
{
_itemsLeft--;
if (_itemsLeft == 0)
{
_utcEndTime = DateTime.UtcNow;
this.DisplayTestResults();
}
}
});
}
}
private void PerformWebRequestGet()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.KeepAlive = true;
response = (HttpWebResponse)request.GetResponse();
}
finally
{
if (response != null) response.Close();
}
}
</code></pre>
<p>Running the tests revealed that the multithreaded version was faster. It took it around 0.6 seconds to complete for 10k requests, while the async one took around 2 seconds to complete for the same amount of load. This was a bit of a surprise, because I was expecting the async one to be faster. Maybe it was because of the fact that my HTTP calls were very fast. In a real world scenario, where the server should perform a more meaningful operation and where there should also be some network latency, the results might be reversed.</p>
<p>However, what really concerns me is the way HttpClient behaves when the load is increased. Since it takes it around 2 seconds to deliver 10k messages, I thought it would take it around 20 seconds to deliver 10 times the number of messages, but running the test showed that it needs around 50 seconds to deliver the 100k messages. Furthermore, it usually takes it more than 2 minutes to deliver 200k messages and often, a few thousands of them (3-4k) fail with the following exception:</p>
<blockquote>
<p>An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.</p>
</blockquote>
<p>I checked the IIS logs and operations that failed never got to the server. They failed within the client. I ran the tests on a Windows 7 machine with the default range of ephemeral ports of 49152 to 65535. Running netstat showed that around 5-6k ports were being used during tests, so in theory there should have been many more available. If the lack of ports was indeed the cause of the exceptions it means that either netstat didn't properly report the situation or HttClient only uses a maximum number of ports after which it starts throwing exceptions.</p>
<p>By contrast, the multithread approach of generating HTTP calls behaved very predictable. I took it around 0.6 seconds for 10k messages, around 5.5 seconds for 100k messages and as expected around 55 seconds for 1 million messages. None of the messages failed. Further more, while it ran, it never used more than 55 MB of RAM (according to Windows Task Manager). The memory used when sending messages asynchronously grew proportionally with the load. It used around 500 MB of RAM during the 200k messages tests.</p>
<p>I think there are two main reasons for the above results. The first one is that HttpClient seems to be very greedy in creating new connections with the server. The high number of used ports reported by netstat means that it probably doesn't benefit much from HTTP keep-alive.</p>
<p>The second is that HttpClient doesn't seem to have a throttling mechanism. In fact this seems to be a general problem related to async operations. If you need to perform a very large number of operations they will all be started at once and then their continuations will be executed as they are available. In theory this should be ok, because in async operations the load is on external systems but as proved above this is not entirely the case. Having a big number of requests started at once will increase the memory usage and slow down the entire execution.</p>
<p>I managed to obtain better results, memory and execution time wise, by limiting the maximum number of asynchronous requests with a simple but primitive delay mechanism:</p>
<pre><code>public async void TestAsyncWithDelay()
{
this.TestInit();
HttpClient httpClient = new HttpClient();
for (int i = 0; i < NUMBER_OF_REQUESTS; i++)
{
if (_activeRequestsCount >= MAX_CONCURENT_REQUESTS)
await Task.Delay(DELAY_TIME);
ProcessUrlAsyncWithReqCount(httpClient);
}
}
</code></pre>
<p>It would be really useful if HttpClient included a mechanism for limiting the number of concurrent requests. When using the Task class (which is based on the .Net thread pool) throttling is automatically achieved by limiting the number of concurrent threads.</p>
<p>For a complete overview, I have also created a version of the async test based on HttpWebRequest rather than HttpClient and managed to obtain much better results. For a start, it allows setting a limit on the number of concurrent connections (with ServicePointManager.DefaultConnectionLimit or via config), which means that it never ran out of ports and never failed on any request (HttpClient, by default, is based on HttpWebRequest, but it seems to ignore the connection limit setting).</p>
<p>The async HttpWebRequest approach was still about 50 - 60% slower than the multithreading one, but it was predictable and reliable. The only downside to it was that it used a huge amount of memory under big load. For example it needed around 1.6 GB for sending 1 million requests. By limiting the number of concurrent requests (like I did above for HttpClient) I managed to reduce the used memory to just 20 MB and obtain an execution time just 10% slower than the multithreading approach.</p>
<p>After this lengthy presentation, my questions are: Is the HttpClient class from .Net 4.5 a bad choice for intensive load applications? Is there any way to throttle it, which should fix the problems I mention about? How about the async flavor of HttpWebRequest?</p>
<p><strong>Update (thanks @Stephen Cleary)</strong></p>
<p>As it turns out, HttpClient, just like HttpWebRequest (on which it is based by default), can have its number of concurrent connections on the same host limited with ServicePointManager.DefaultConnectionLimit. The strange thing is that according to <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx" rel="noreferrer">MSDN</a>, the default value for the connection limit is 2. I also checked that on my side using the debugger which pointed that indeed 2 is the default value. However, it seems that unless explicitly setting a value to ServicePointManager.DefaultConnectionLimit, the default value will be ignored. Since I didn't explicitly set a value for it during my HttpClient tests I thought it was ignored.</p>
<p>After setting ServicePointManager.DefaultConnectionLimit to 100 HttpClient became reliable and predictable (netstat confirms that only 100 ports are used). It is still slower than async HttpWebRequest (by about 40%), but strangely, it uses less memory. For the test which involves 1 million requests, it used a maximum of 550 MB, compared to 1.6 GB in the async HttpWebRequest.</p>
<p>So, while HttpClient in combination ServicePointManager.DefaultConnectionLimit seem to ensure reliability (at least for the scenario where all the calls are being made towards the same host), it still looks like its performance is negatively impacted by the lack of a proper throttling mechanism. Something that would limit the concurrent number of requests to a configurable value and put the rest in a queue would make it much more suitable for high scalability scenarios.</p> | 16,528,153 | 3 | 9 | null | 2013-04-24 14:03:04.927 UTC | 78 | 2016-11-28 16:58:11.083 UTC | 2013-04-24 16:04:51.347 UTC | null | 425,166 | null | 425,166 | null | 1 | 132 | c#|asynchronous|.net-4.5|async-await|dotnet-httpclient | 47,556 | <p>Besides the tests mentioned in the question, I recently created some new ones involving much fewer HTTP calls (5000 compared to 1 million previously) but on requests that took much longer to execute (500 milliseconds compared to around 1 millisecond previously). Both tester applications, the synchronously multithreaded one (based on HttpWebRequest) and asynchronous I/O one (based on HTTP client) produced similar results: about 10 seconds to execute using around 3% of the CPU and 30 MB of memory. The only difference between the two testers was that the multithreaded one used 310 threads to execute, while the asynchronous one just 22. So in an application that would have combined both I/O bound and CPU bound operations the asynchronous version would have produced better results because there would have been more CPU time available for the threads performing CPU operations, which are the ones that actually need it (threads waiting for I/O operations to complete are just wasting).</p>
<p>As a conclusion to my tests, asynchronous HTTP calls are not the best option when dealing with very fast requests. The reason behind that is that when running a task that contains an asynchronous I/O call, the thread on which the task is started is quit as soon the as the asynchronous call is made and the rest of the task is registered as a callback. Then, when the I/O operation completes, the callback is queued for execution on the first available thread. All this creates an overhead, which makes fast I/O operations to be more efficient when executed on the thread that started them.</p>
<p>Asynchronous HTTP calls are a good option when dealing with long or potentially long I/O operations because it doesn't keep any threads busy on waiting for the I/O operations to complete. This decreases the overall number of threads used by an application allowing more CPU time to be spent by CPU bound operations. Furthermore, on applications that only allocate a limited number of threads (like it is the case with web applications), asynchronous I/O prevents thread pool thread depletion, which can happen if performing I/O calls synchronously.</p>
<p>So, async HttpClient is not a bottleneck for intensive load applications. It is just that by its nature it is not very well suited for very fast HTTP requests, instead it is ideal for long or potentially long ones, especially inside applications that only have a limited number of threads available. Also, it is a good practice to limit concurrency via ServicePointManager.DefaultConnectionLimit with a value that high enough to ensure a good level of parallelism, but low enough to prevent ephemeral port depletion. You can find more details on the tests and conclusions presented for this question <a href="http://www.ducons.com/blog/tests-and-thoughts-on-asynchronous-io-vs-multithreading">here</a>.</p> |
29,291,020 | Automatically scroll to bottom as the page loads | <p>I have a php script that shows a log of its actions as the script proceeds. The log is getting quite long, up to the point where it will echo its information past the bottom of the page, adding a scrollbar to the page.</p>
<p>If I want to see the rest of the log, I have to manually scroll down. I can make the page go to say... process.php#bottom but I can't just insert a <code><a name="bottom" /></code> after each log item and expect the browser to keep jumping to the bottom, can I?</p>
<p>Is there a a javascript function, or other easy method, that will automatically scroll the page to the bottom as soon as this isn't the case?</p>
<p>I don't mind if it overrides the user's ability to scroll, as the script will redirect back to the main script after 3 seconds at the end anyway.</p>
<p>I do not necessarily need a full script, if you just have pointers, but those that provide a full working script will obviously get their answer accepted over those that just give pointers.</p>
<p>If you don't have an idea of what I mean by the log, you can use the following script to simulate what my script does:</p>
<pre><code><?php
for( $iLineNumber=0 ; $iLineNumber <100 ; $iLineNumber++ )
{
echo $iLineNumber , ' - This is a test. <br />';
sleep(1);
}
?>
</code></pre>
<p>Basically, as the script loads and sleeps every second, when it hit the bottom of the page, it should automatically scroll down every second.</p> | 29,291,223 | 5 | 6 | null | 2015-03-26 23:57:52.553 UTC | 2 | 2021-10-21 21:05:43.123 UTC | null | null | null | null | 3,536,324 | null | 1 | 6 | javascript|php|html | 40,323 | <p>This works: </p>
<pre><code><script>
setTimeout(printSomething, 1000);
function printSomething(){
for(var i=0; i<10; i++){
document.write("Hello World\n");
document.write("<br>");
}
window.scrollTo(0,document.body.scrollHeight);
setTimeout(printSomething, 1000);
}
</script>
</code></pre> |
22,118,984 | How to convert automatically list of objects to JSONArray with Gson library in java? | <p>Lets say I have following list of custom object: <code>ArrayList<GroupItem></code> where <code>GroupItem</code> is some class that has <code>int</code> and <code>String</code> variables. </p>
<p>I tried so far <code>Gson</code> library but it's not exactly what I want.</p>
<pre><code>ArrayList<GroupItem> groupsList = /* ... */
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(groupsList, new TypeToken<ArrayList<GroupItem>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
</code></pre>
<p>My goal is to get <code>JSONArray</code> (org.Json.JSONArray) somehow. Any ideas?</p>
<p><strong>[EDIT]</strong></p>
<p>My project is Android with Cordova that has API based on <code>org.Json.JSONArray</code></p>
<p>ANd I thought to write some generic way to convert instances to <code>JSONArray</code> / <code>JSONObject</code> </p>
<p>Thanks,</p> | 22,120,059 | 5 | 2 | null | 2014-03-01 19:07:30.887 UTC | null | 2020-01-24 18:24:59.41 UTC | 2014-03-01 19:16:27.31 UTC | null | 3,021,358 | null | 3,021,358 | null | 1 | 11 | java|json|gson | 68,433 | <p>This way is worked for me:</p>
<p>Convert all list to String.</p>
<pre><code>String element = gson.toJson(
groupsList,
new TypeToken<ArrayList<GroupItem>>() {}.getType());
</code></pre>
<p>Create <code>JSONArray</code> from String:</p>
<pre><code> JSONArray list = new JSONArray(element);
</code></pre> |
19,491,336 | How to get URL parameter using jQuery or plain JavaScript? | <p>I have seen lots of jQuery examples where parameter size and name are unknown.</p>
<p>My URL is only going to ever have 1 string:</p>
<pre><code>http://example.com?sent=yes
</code></pre>
<p>I just want to detect:</p>
<ol>
<li>Does <code>sent</code> exist?</li>
<li>Is it equal to "yes"?</li>
</ol> | 21,903,119 | 34 | 6 | null | 2013-10-21 09:55:33.79 UTC | 248 | 2022-07-31 16:14:53.073 UTC | 2020-05-25 10:13:39.523 UTC | null | 4,217,744 | null | 1,002,758 | null | 1 | 758 | jquery|url|parameters|query-string|querystringparameter | 1,589,613 | <p>Best solution <a href="http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery" rel="noreferrer">here</a>.</p>
<pre><code>var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
</code></pre>
<p>And this is how you can use this function assuming the URL is,<br />
<code>http://dummy.com/?technology=jquery&blog=jquerybyexample</code>.</p>
<pre><code>var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
</code></pre> |
17,335,649 | How to specify column names while reading an Excel file using Pandas? | <p>I read an Excel Sheet into a pandas DataFrame this way:</p>
<pre><code>import pandas as pd
xl = pd.ExcelFile("Path + filename")
df = xl.parse("Sheet1")
</code></pre>
<p>the first cell's value of each column is selected as the column name for the dataFrame, I want to specify my own column names, How do I do this?</p> | 17,335,951 | 5 | 0 | null | 2013-06-27 06:05:25.433 UTC | 7 | 2022-03-07 18:28:30.527 UTC | null | null | null | null | 4,168,397 | null | 1 | 20 | python|pandas | 82,057 | <p>call <code>.parse</code> with <code>header=None</code> keyword argument.</p>
<pre><code>df = xl.parse("Sheet1", header=None)
</code></pre> |
17,567,344 | Detect left/right-swipe on touch-devices, but allow up/down-scrolling | <p>I need to detect and react to left/right-swipes, but want to give the user the ability to scroll on the same element, so as long as he moves his finger only left/right with a maximum up/down movement of X pixels, it should not scroll, but when he exceeds X, it should scroll.</p>
<p>So what I did is:</p>
<pre><code>var startX, startY, $this = $(this);
function touchmove(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
var deltaX = touches[0].pageX - startX;
var deltaY = touches[0].pageY - startY;
if (Math.abs(deltaY) > 50) {
$this.html('X: ' + deltaX + '<br> Y: ' + deltaY + '<br>TRUE');
$this.unbind('touchmove', touchmove);
return true;
} else {
$this.html('X: ' + deltaX + '<br> Y: ' + deltaY);
event.preventDefault();
}
}
}
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
startX = touches[0].pageX;
startY = touches[0].pageY;
$this.bind('touchmove', touchmove);
}
//event.preventDefault();
}
</code></pre>
<p>But I doesn't restore the ability to scroll in the "if" case... </p>
<p>Thanks for any tips.</p> | 17,567,696 | 5 | 3 | null | 2013-07-10 09:41:56.07 UTC | 21 | 2018-12-17 23:05:18.787 UTC | 2013-07-10 12:40:49.347 UTC | null | 1,988,765 | null | 1,988,765 | null | 1 | 31 | javascript|jquery|touch|swipe | 53,280 | <p>I wrote my own touch handler events.maybe this helps you</p>
<p>it checks for:</p>
<p>fast click : 'fc'</p>
<p>swipe left : 'swl'</p>
<p>swipe right : 'swr'</p>
<p>swipe up : 'swu'</p>
<p>swipe down : 'swd'</p>
<p>each check initializes it's correspondent event.but you can scroll and do whatever else you do normally. you just have some new events. </p>
<p>you need swl swr, I aslo suggest to use fc (fastclick) for click events... it's much faster than normal click.</p>
<pre><code>window.onload = function() {
(function(d) {
var
ce = function(e, n) {
var a = document.createEvent("CustomEvent");
a.initCustomEvent(n, true, true, e.target);
e.target.dispatchEvent(a);
a = null;
return false
},
nm = true,
sp = {
x: 0,
y: 0
},
ep = {
x: 0,
y: 0
},
touch = {
touchstart: function(e) {
sp = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
},
touchmove: function(e) {
nm = false;
ep = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
}
},
touchend: function(e) {
if (nm) {
ce(e, 'fc')
} else {
var x = ep.x - sp.x,
xr = Math.abs(x),
y = ep.y - sp.y,
yr = Math.abs(y);
if (Math.max(xr, yr) > 20) {
ce(e, (xr > yr ? (x < 0 ? 'swl' : 'swr') : (y < 0 ? 'swu' : 'swd')))
}
};
nm = true
},
touchcancel: function(e) {
nm = false
}
};
for (var a in touch) {
d.addEventListener(a, touch[a], false);
}
})(document);
//EXAMPLE OF USE
var h = function(e) {
console.log(e.type, e)
};
document.body.addEventListener('fc', h, false); // 0-50ms vs 500ms with normal click
document.body.addEventListener('swl', h, false);
document.body.addEventListener('swr', h, false);
document.body.addEventListener('swu', h, false);
document.body.addEventListener('swd', h, false);
}
</code></pre>
<p>in this case h is my handler for every type of event and i add the handlers to the body.</p>
<p>for what i understand your question you just have to write</p>
<pre><code>YOURELEMENT.addEventListener('swr',YOURSWIPERIGHTFUNCTION,false);
YOURELEMENT.addEventListener('swl',YOURSWIPELEFTFUNCTION,false);
</code></pre>
<p>to handle multiple elements and the same function... just add one handler.</p>
<p>so if you have</p>
<pre><code><ul id="ul"><li>1</li><li>2</li><li>3</li></ul>
</code></pre>
<p>you do:</p>
<pre><code>var deleteli=function(e){
var li=e.target;
console.log('deleting '+li.textContent);
}
document.getElementById('ul').addEventListener('swl',deleteli,false);
</code></pre>
<p>same for fc & swr</p>
<p>there is a bug in ios: don't use alert() .. it will execute 2 times.</p> |
17,584,202 | Google Spreadsheet Formula to Use Current Row in Function | <p>I want to calculate the product of two different columns (e.g., A & B) for each row on my spreadsheet. For a single row, this would work by using <code>=PRODUCT(A1:B1)</code>, but I can't figure out how to get the function to use the current row instead of a manually entered row. I know you can get a reference to the current row using <code>ROW()</code>, but I get an error when I try something like <code>PRODUCT(AROW():BROW())</code>.</p> | 17,594,628 | 2 | 1 | null | 2013-07-11 02:43:48.81 UTC | 14 | 2021-12-10 21:49:28.94 UTC | null | null | null | null | 1,478,512 | null | 1 | 64 | google-sheets | 102,003 | <p>If you copy the formula you quoted into another row, or fill it down using Ctrl+D, it will automatically change the reference to the row you are copying/filling to. This is called a "relative reference". If you use the formula <code>=PRODUCT($A$1:$B$1)</code>, this is called an "absolute reference", which will not change if copied elsewhere.</p>
<p>You can also use the following formula in any row:</p>
<p><code>=A:A*B:B</code></p>
<p>which will return the product of the two values in the row the formula is invoked.</p> |
17,298,313 | Python Pandas: Convert Rows as Column headers | <p>I have the following dataframe:</p>
<pre><code>Year Country medal no of medals
1896 Afghanistan Gold 5
1896 Afghanistan Silver 4
1896 Afghanistan Bronze 3
1896 Algeria Gold 1
1896 Algeria Silver 2
1896 Algeria Bronze 3
</code></pre>
<p>I want it this way.</p>
<pre><code>Year Country Gold Silver Bronze
1896 Afghanistan 5 4 3
1896 Algeria 1 2 3
</code></pre>
<p>Stack/Unstack dont seem to work.</p> | 17,298,454 | 2 | 0 | null | 2013-06-25 13:12:10.197 UTC | 43 | 2022-09-15 22:11:11.067 UTC | null | null | null | null | 1,948,860 | null | 1 | 101 | python|pandas | 152,018 | <p>You're looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.pivot.pivot_table.html" rel="noreferrer"><code>pivot_table</code></a>:</p>
<pre><code>In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')
In [12]: medals
Out[12]:
medal Bronze Gold Silver
Year Country
1896 Afghanistan 3 5 4
Algeria 3 1 2
</code></pre>
<p>and if you want to reorder the columns:</p>
<pre><code>In [12]: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)
Out[12]:
medal Gold Silver Bronze
Year Country
1896 Afghanistan 5 4 3
Algeria 1 2 3
</code></pre> |
17,548,751 | How to write a SQL DELETE statement with a SELECT statement in the WHERE clause? | <p>Database: Sybase Advantage 11</p>
<p>On my quest to normalize data, I am trying to delete the results I get from this <code>SELECT</code> statement:</p>
<pre><code>SELECT tableA.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
;
</code></pre>
<p>This is the <code>DELETE</code> statement I have come up with:</p>
<pre><code>DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'))
;
</code></pre>
<p>I continuously get this error when I try to run this statement:</p>
<pre><code>ERROR IN SCRIPT: poQuery: Error 7200: AQE Error: State = S0000; NativeError = 2124;
[iAnywhere Solutions][Advantage SQL Engine]Invalid operand for operator: = Boolean value
cannot be operated with non-Boolean value.
</code></pre>
<p>I have also tried this statement:</p>
<pre><code>DELETE FROM tableA
INNER JOIN tableB u on (u.qlabel = tableA.entityrole AND u.fieldnum = tableA.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR tableA.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
;
</code></pre>
<p>Which results in:</p>
<pre><code>ERROR IN SCRIPT: poQuery: Error 7200: AQE Error: State = 42000; NativeError = 2117;
[iAnywhere Solutions][Advantage SQL Engine] Unexpected token: INNER -- Expecting semicolon.
-- Location of error in the SQL statement is: 23 (line: 2 column: 1)
</code></pre>
<p>Could someone aid me in properly constructing a DELETE query that will result in the proper data being removed? </p> | 17,576,164 | 6 | 1 | null | 2013-07-09 12:56:30.283 UTC | 19 | 2021-03-02 19:57:20.467 UTC | 2017-05-03 03:55:37.97 UTC | null | 15,168 | null | 2,564,450 | null | 1 | 104 | sql|select|where-clause|advantage-database-server|sql-delete | 539,253 | <p>You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key. </p>
<pre><code>DELETE FROM tableA
WHERE ROWID IN
( SELECT q.ROWID
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
</code></pre> |
37,035,300 | How to determine the default location for openssl.cnf? | <h1>Background</h1>
<p>I'm writing a bash script that will use openssl to generate a certificate signing request with <em>X509v3 extension compliant</em> subject alternative names.</p>
<p>Since there's no command line option for this, <a href="http://blog.endpoint.com/2014/10/openssl-csr-with-alternative-names-one.html?m=1#c5955230974051418639" rel="noreferrer">a solution</a> has been to use the <code>-config</code> option in conjunction with the <code>-reqexts</code> option by appending the SAN values inline to the default configuration file.</p>
<pre><code>openssl req -new -sha256 -key domain.key -subj "/C=US/ST=CA/O=Acme, Inc./CN=example.com" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=DNS:example.com,DNS:www.example.com")) -out domain.csr
</code></pre>
<h1>Question</h1>
<p>My problem is portability. While <a href="https://stackoverflow.com/questions/21477210/correct-location-of-openssl-cnf-file">a similar question</a> assures me that this works in my Ubuntu environment because the default configuration file is <code>/etc/ssl/openssl.cnf</code>, unfortunately this won't work everywhere, with Windows being the obvious example.</p>
<p><em>How do I <strong>programmatically</strong> determine the full path to the openssl <strong>default</strong> configuration file?</em></p>
<h1>What I've Tried</h1>
<p>There's a glaring hint in the <a href="https://www.openssl.org/docs/man1.1.0/apps/req.html" rel="noreferrer">documentation</a></p>
<blockquote>
<p>-config filename<br>
this allows an alternative configuration file to be specified, this overrides <strong>the compile time filename</strong> or any specified in the OPENSSL_CONF environment variable.</p>
</blockquote>
<p>I've read the <a href="https://www.openssl.org/docs/man1.1.0/apps/config.html" rel="noreferrer">config documentation</a> and searched the <a href="https://github.com/openssl/openssl" rel="noreferrer">source code</a>, but I can't discover the mechanism by which it chooses from where to load the "compile time" default config file. If I could find that, then I would prefer to load it as a variable into the script instead of the hard-coded path.</p>
<p>Moreover, my <code>$OPENSSL_CONF</code> variable is empty.</p>
<h2>A Bad Alternative</h2>
<p>Currently my script checks these conditions, and uses the first one that evaluates to true:</p>
<ol>
<li><code>$OPENSSL_CONF</code> variable is populated, and file exists</li>
<li><code>/etc/ssl/openssl.cnf</code> exists</li>
</ol>
<p>If neither of those are true, then it includes a copy of a standard configuration. This is undesirable because it would in effect override custom settings established by the client. I want to use the environment's conditions completely, and simply add the SAN section as an addendum.</p>
<p>I could further extend this chain with the paths of the usual suspects or even a system search. But in the event that multiple exist, then I have no assurance of which is in fact used by openssl as a default.</p> | 37,042,289 | 2 | 2 | null | 2016-05-04 18:27:43.87 UTC | 7 | 2019-01-21 00:52:58.743 UTC | 2017-06-29 09:48:50.093 UTC | user948581 | null | null | 4,233,593 | null | 1 | 23 | bash|openssl | 55,014 | <blockquote>
<p>How do I programmatically determine the full path to the openssl default configuration file?</p>
</blockquote>
<p>Programmatically, its as easy as using the <code>OPENSSLDIR</code> macro from <code>opensslconf.h</code>:</p>
<pre class="lang-none prettyprint-override"><code>$ cat /usr/local/ssl/darwin/include/openssl/opensslconf.h | grep OPENSSLDIR
#if defined(HEADER_CRYPTLIB_H) && !defined(OPENSSLDIR)
#define OPENSSLDIR "/usr/local/ssl/darwin"
</code></pre>
<hr>
<blockquote>
<p>How to determine the default location for openssl.cnf?</p>
</blockquote>
<p>Here's more information to help fill in the gaps from the other Stack Overflow question. It depends on the OpenSSL installation you are using.</p>
<p>Here's the short answer... The library and programs look for <code>openssl.cnf</code> in <code>OPENSSLDIR</code>. <code>OPENSSLDIR</code> is a configure option, and its set with <code>--openssldir</code>.</p>
<p>I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):</p>
<pre class="lang-none prettyprint-override"><code># Apple
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"
# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"
# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"
</code></pre>
<p>Here's the longer answer... It is kind of buried in OpenSSL source code for <code>apps.c</code>, <code>load_config</code> and what happens when <code>cnf</code> is <code>NULL</code> (i.e., no <code>-config</code> option or <code>OPENSSL_CONF</code> envar). When <code>cnf</code> is <code>NULL</code> and no overrides, then <code>OPENSSLDIR</code> is used.</p>
<pre class="lang-c prettyprint-override"><code>int load_config(BIO *err, CONF *cnf)
{
static int load_config_called = 0;
if (load_config_called)
return 1;
load_config_called = 1;
if (!cnf)
cnf = config;
if (!cnf)
return 1;
OPENSSL_load_builtin_modules();
if (CONF_modules_load(cnf, NULL, 0) <= 0) {
BIO_printf(err, "Error configuring OpenSSL\n");
ERR_print_errors(err);
return 0;
}
return 1;
}
</code></pre>
<hr>
<blockquote>
<p>... this works in my Ubuntu environment because the default configuration file is <code>/etc/ssl/openssl.cnf</code>, unfortunately this won't work everywhere, with Windows being the obvious example.</p>
</blockquote>
<p>This may still be a problem for you on Windows. You should be OK if you build OpenSSL from sources yourself; modulo their long filename handling in Windows (also see <a href="http://rt.openssl.org/Ticket/Display.html?id=4490&user=guest&password=guest" rel="noreferrer">Issue #4490: "nmake install" fails "Destination must be a directory at .\util\copy.pl line 39" on</a>).</p>
<p>Folks like <a href="http://slproweb.com/products/Win32OpenSSL.html" rel="noreferrer">Shinning Light and Win32 OpenSSL</a> provide installers, and OpenSSL <em>may not</em> be installed in the directory the packager envisioned. I've even seen Unix directories like <code>/usr/local</code> appear on Windows machines.</p>
<p>For Windows, your safest bet is probably set the <code>OPENSSL_CONF</code> environmental variable to override broken paths and path handling bugs.</p>
<hr>
<p>Also, I'm not aware of a <code>CONF_*</code> or <code>NCONF_*</code> API call that gives you the effective directory at runtime. Here, the effective directory would be the configuration directory plus things like <code>OPENSSL_CONF</code> overrides. Now open on the OpenSSL User list: <a href="https://mta.openssl.org/pipermail/openssl-users/2016-May/003664.html" rel="noreferrer">Get effective OPENSSLDIR path at runtime?</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.