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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,406,457 | Load an image from URL as base64 string | <p>I am trying to load an image as a base 64 string so that i can show it in a html like this:</p>
<pre><code> <html><body><img src="data:image/jpeg;base64,/></img></body></html>
</code></pre>
<p>Heres my code so far, but it does not really work:</p>
<pre><code> public async static Task<string> getImage(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "data:image/jpg;charset=base64";
request.Credentials = new NetworkCredential(user, pw);
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
StreamReader sr = new StreamReader(response.GetResponseStream());
return sr.ReadToEnd();
}
</code></pre>
<p>I tried using this method i found elsewhere to encode the return-String as base64, but when placing it in a html the image just shows the typical placeholder.</p>
<pre><code> public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
</code></pre>
<p>EDIT:</p>
<p>Here is how the html looks:
<a href="https://i.stack.imgur.com/MTrS4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MTrS4.png" alt="enter image description here"></a></p> | 35,406,675 | 3 | 8 | null | 2016-02-15 10:06:33.633 UTC | 8 | 2020-10-14 03:19:13.713 UTC | 2018-05-19 20:29:02.467 UTC | null | 6,750,540 | null | 4,545,369 | null | 1 | 12 | c#|url|xamarin|base64 | 34,801 | <p>It seems to me that you need to separate the base64 part, which is only needed in your HTML, from fetching the data from the response. Just fetch the data from the URL as binary data and convert that to base64. Using <code>HttpClient</code> makes this simple:</p>
<pre><code>public async static Task<string> GetImageAsBase64Url(string url)
{
var credentials = new NetworkCredential(user, pw);
using (var handler = new HttpClientHandler { Credentials = credentials })
using (var client = new HttpClient(handler))
{
var bytes = await client.GetByteArrayAsync(url);
return "image/jpeg;base64," + Convert.ToBase64String(bytes);
}
}
</code></pre>
<p>This assumes the image always <em>will</em> be a JPEG. If it could sometimes be a different content type, you may well want to fetch the response as an <code>HttpResponse</code> and use that to propagate the content type.</p>
<p>I suspect you may want to add caching here as well :)</p> |
13,746,153 | How to get row id from row Index in table using JavaScript | <p>Suppose this is my table:</p>
<pre><code><table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
</code></pre>
<p>How can I get row id using the row index from a table?</p>
<p>Above is just an example where id is static but in my case my id is dynamic, so I can't use
<code>document.getElementById()</code>.</p> | 13,746,314 | 3 | 3 | null | 2012-12-06 14:51:02.81 UTC | 2 | 2012-12-06 15:22:35.877 UTC | 2012-12-06 15:02:53.103 UTC | null | 1,689,607 | null | 1,878,670 | null | 1 | 9 | javascript|html | 84,463 | <p>Assuming you have only one table on your page:</p>
<pre><code>document.getElementsByTagName("tr")[index].id;
</code></pre>
<p><strong>Preferably</strong> though, you'd give your <code>table</code> a <code>id</code>, though, and get your row like this:</p>
<pre><code><table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
</code></pre>
<pre><code>var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
</code></pre>
<p>This way, you can be certain you don't get any interference, if you have multiple tables in your page.</p> |
13,602,190 | java.lang.SecurityException: Requires VIBRATE permission on Jelly Bean 4.2 | <p>Since yesterday I have an issue on Android 4.2 when I receive push notifications it requires the permission even if i don't set it to vibrate</p>
<pre><code>Notification notification = new Notification(icon, notificationItem.message, when);
notification.setLatestEventInfo(context, "App", notificationItem.message,
PendingIntent.getActivity(context, 0, intent, 0));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager nm =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationItem.notificationID, notification);
</code></pre>
<p>the exception is raised by nm.notify</p>
<p>I have this issue in two different apps and i never modify the code</p> | 13,716,428 | 3 | 6 | null | 2012-11-28 09:48:48.22 UTC | 8 | 2015-03-14 05:47:39.097 UTC | 2012-11-28 11:08:17.623 UTC | null | 1,466,188 | null | 633,938 | null | 1 | 35 | android|notifications|push|android-4.2-jelly-bean | 20,958 | <p>This was a bug in Android 4.2 due to a change in the notification vibration policy; the permission bug was fixed by <a href="https://android.googlesource.com/platform/frameworks/base/+/cc2e849" rel="noreferrer">this change</a> in 4.2.1.</p> |
13,668,881 | variable in class name jade | <p>I can't set a variable name in a class in jade:</p>
<pre><code>.flag_#{ session.locale } #{ session.locale }
</code></pre>
<p>I have:</p>
<pre><code><div class="flag_" >en</div>
</code></pre>
<p>And I'd like to have</p>
<pre><code><div class="flag_en" >en</div>
</code></pre>
<p>Thanks</p> | 13,669,249 | 5 | 0 | null | 2012-12-02 11:33:36.403 UTC | 8 | 2021-01-21 20:44:10.817 UTC | null | null | null | null | 1,860,758 | null | 1 | 38 | node.js|express|pug | 21,256 | <p>Try this (have not tested):</p>
<pre><code>div(class="flag_#{ session.locale }") session.locale
</code></pre> |
9,130,117 | nusoap simple server | <p>Hi i am using this code for nusoap server but when i call the server in web browser it shows message "This service does not provide a Web description" Here is the code</p>
<pre><code><?
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('hello');
// create the function
function hello($name)
{
if(!$name){
return new soap_fault('Client','','Put your name!');
}
$result = "Hello, ".$name;
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
</code></pre>
<p>An help ...</p> | 9,130,383 | 3 | 2 | null | 2012-02-03 14:24:23.757 UTC | 2 | 2019-07-31 10:53:06.977 UTC | null | null | null | null | 968,460 | null | 1 | 11 | php|nusoap | 49,955 | <p>Please change your code to,</p>
<pre><code><?php
//call library
require_once('nusoap.php');
$URL = "www.test.com";
$namespace = $URL . '?wsdl';
//using soap_server to create server object
$server = new soap_server;
$server->configureWSDL('hellotesting', $namespace);
//register a function that works on server
$server->register('hello');
// create the function
function hello($name)
{
if (!$name) {
return new soap_fault('Client', '', 'Put your name!');
}
$result = "Hello, " . $name;
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
</code></pre>
<p>You didnt Define namespace..</p>
<p>Please see simple example here :-</p>
<p><a href="http://patelmilap.wordpress.com/2011/09/01/soap-simple-object-access-protocol/">http://patelmilap.wordpress.com/2011/09/01/soap-simple-object-access-protocol/</a></p> |
29,594,720 | Automatic redirect after login with react-router | <p>I wanted to build a Facebook login into my <strong>react/react-router/flux</strong> application.
I have a listener registered on the login event and would like to redirect the user to <code>'/dashboard'</code> if they are logged in. How can I do that? <code>location.push</code> didn't work very well, except after reloading the page completely.</p> | 29,596,822 | 8 | 3 | null | 2015-04-12 21:12:43.617 UTC | 11 | 2021-04-20 13:44:39.787 UTC | 2018-01-28 19:37:05.07 UTC | null | 5,404,861 | null | 1,559,386 | null | 1 | 51 | reactjs|reactjs-flux|react-router | 98,013 | <blockquote>
<p><strong>React Router v0.13</strong></p>
</blockquote>
<p>The <code>Router</code> instance <a href="https://github.com/rackt/react-router/blob/master/docs/api/create.md" rel="nofollow noreferrer">returned from <code>Router.create</code></a> can be passed around (or, if inside a React component, you can get it from <a href="https://github.com/rackt/react-router/blob/master/docs/api/RouterContext.md" rel="nofollow noreferrer">the context object</a>), and contains methods <a href="https://github.com/rackt/react-router/blob/master/docs/api/RouterContext.md#transitiontoroutenameorpath-params-query" rel="nofollow noreferrer">like <code>transitionTo</code></a> that you can use to transition to a new route.</p> |
29,441,950 | How to use composer on windows? | <p>I have installed xampp on my PC. After that I installed composer using window installer. On the website they tell about composer.json which looks something like this in the example</p>
<pre><code>{
"require": {
"monolog/monolog": "1.2.*"
}
}
</code></pre>
<p>Where do I put it? How do I run it? I have searched a lot but found nothing. Any suggestion would be great.</p>
<p>I ran command prompt as administrator with following command</p>
<pre><code>C:\windows\system32>composer
</code></pre>
<p>It printed out a bunch of commands. I tried typing</p>
<pre><code>C:\windows\system32>composer install
</code></pre>
<p>I got an error that composer could not find composer.json file</p> | 29,442,140 | 1 | 4 | null | 2015-04-04 02:02:24.56 UTC | 6 | 2015-04-05 22:52:44.48 UTC | 2015-04-05 22:52:44.48 UTC | null | 1,149,495 | null | 4,699,883 | null | 1 | 18 | php|xampp|composer-php | 52,611 | <p>Okay, let's say your website is at:</p>
<pre><code>C:\xampp\htdocs\mywebsite\
</code></pre>
<p>You should put the Composer file at:</p>
<pre><code>C:\xampp\htdocs\mywebsite\composer.json
</code></pre>
<p>Then, in your terminal, use these two commands:</p>
<pre><code>cd C:\xampp\htdocs\mywebsite
composer install
</code></pre>
<p>That should be it.</p>
<p>You can do various other things with Composer. To find out what type <code>composer</code> in your terminal. It will show you a list of commands you can use.</p>
<p>If you want to know more about a command then you can use <code>composer help [COMMAND]</code>, like so:</p>
<pre><code>composer help install
</code></pre> |
16,429,862 | Creating a webRTC peer *without* a browser, with just a JavaScript interpreter | <p>I want to create a WebRTC peer that's a simple listener/recorder with no "presentation" component (i.e., no HTML/CSS). </p>
<p>If this is possible, (with the WebRTC JavaScript APIs), please tell me what <em>standalone</em> JavaScript engine I can use (I'm thinking of installing a standalone V8 engine).</p>
<p>Thank you.</p> | 55,478,195 | 6 | 10 | null | 2013-05-07 22:49:56.91 UTC | 12 | 2019-04-02 15:16:33.657 UTC | null | null | null | null | 1,363,774 | null | 1 | 35 | javascript|node.js|webrtc | 14,345 | <p>You could do this with <a href="https://developers.google.com/web/updates/2017/04/headless-chrome" rel="nofollow noreferrer">headless chrome</a>. Chrome of course has full WebRTC support, but can be started in "headless" mode, and then interacted with via the command line or their control interface.</p> |
16,311,688 | Bash convert epoch to date, showing wrong time | <p>How come date is converting to wrong time?</p>
<pre><code>result=$(ls /path/to/file/File.*)
#/path/to/file/File.1361234760790
currentIndexTime=${result##*.}
echo "$currentIndexTime"
#1361234760790
date -d@"$currentIndexTime"
#Tue 24 Oct 45105 10:53:10 PM GMT
</code></pre> | 16,311,821 | 3 | 6 | null | 2013-05-01 01:58:32.48 UTC | 13 | 2019-03-20 22:05:14 UTC | null | null | null | null | 595,833 | null | 1 | 63 | bash|date|epoch | 93,282 | <p>This particular timestamp is in milliseconds since the epoch, not the standard seconds since the epoch. Divide by 1000:</p>
<pre><code>$ date -d @1361234760.790
Mon Feb 18 17:46:00 MST 2013
</code></pre> |
16,530,532 | Rails 4: Insert Attribute Into Params | <p>In Rails 3, it was possible to insert an attribute into params like so:</p>
<pre><code>params[:post][:user_id] = current_user.id
</code></pre>
<p>I'm attempting to do something similar in Rails 4, but having no luck:</p>
<pre><code>post_params[:user_id] = current_user.id
. . . .
private
def post_params
params.require(:post).permit(:user_id)
end
</code></pre>
<p>Rails is ignoring this insertion. It doesn't throw any errors, it just quietly fails.</p> | 16,532,008 | 4 | 0 | null | 2013-05-13 20:27:27.48 UTC | 19 | 2019-06-13 20:42:21.87 UTC | 2013-05-13 21:01:56.543 UTC | null | 1,255,372 | null | 1,255,372 | null | 1 | 69 | ruby-on-rails|strong-parameters | 51,379 | <p>Found the answer <a href="https://thoughtbot.com/blog/strong-parameters-as-documentation" rel="noreferrer">here</a>. Rather than inserting the attribute from within the controller action, you can insert it into the params definition with a merge. To expand upon my previous example:</p>
<pre><code>private
def post_params
params.require(:post).permit(:some_attribute).merge(user_id: current_user.id)
end
</code></pre> |
16,458,564 | Convert character to ASCII numeric value in java | <p>I have <code>String name = "admin";</code><br />
then I do <code>String charValue = name.substring(0,1); //charValue="a"</code></p>
<p>I want to convert the <code>charValue</code> to its ASCII value (97), how can I do this in java?</p> | 16,458,580 | 22 | 2 | null | 2013-05-09 09:30:22.69 UTC | 58 | 2020-08-15 13:12:03.537 UTC | 2020-08-15 13:12:03.537 UTC | null | 12,079,719 | null | 2,315,020 | null | 1 | 220 | java|string|ascii | 1,165,205 | <p>Very simple. Just cast your <code>char</code> as an <code>int</code>.</p>
<pre><code>char character = 'a';
int ascii = (int) character;
</code></pre>
<p>In your case, you need to get the specific Character from the String first and then cast it. </p>
<pre><code>char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
</code></pre>
<p>Though cast is not required explicitly, but its improves readability.</p>
<pre><code>int ascii = character; // Even this will do the trick.
</code></pre> |
21,565,605 | Counting the frequency of an element in a data frame | <p>I have the following data frame</p>
<pre><code>SelectVar
b c e f g h j
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg
</code></pre>
<p>When applying count I get</p>
<pre><code>count(SelectVar)
b c e f g h j freq
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 1
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2 1
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg 1
</code></pre>
<p>When I apply </p>
<p>count(SelectVar==Dxa2)</p>
<pre><code> b c e f g h j freq
1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE 1
</code></pre>
<p>I can not figure out how to count the frequency of the different elements Dxa2, Dxb2... in SelectVar</p> | 21,565,701 | 2 | 4 | null | 2014-02-04 23:18:45.723 UTC | 2 | 2014-02-05 00:00:26.25 UTC | null | null | null | null | 2,011,776 | null | 1 | 5 | r | 42,459 | <p>You can turn your <code>data.frame</code> to a <code>vector</code> and then use <code>table</code></p>
<pre><code>df <- read.table(text = " b c e f g h j
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg", header = TRUE, row.names = 1)
table(unlist(df))
## Dxa2 Dxb2 Dxd2 Dxi2 tneg tpos Dxc2
## 7 4 2 2 2 1 3
</code></pre>
<p>You can turn the result to a <code>data.frame</code> too</p>
<pre><code>as.data.frame(table(unlist(df)))
## Var1 Freq
## 1 Dxa2 7
## 2 Dxb2 4
## 3 Dxd2 2
## 4 Dxi2 2
## 5 tneg 2
## 6 tpos 1
## 7 Dxc2 3
</code></pre> |
19,417,776 | How do I locate the CGRect for a substring of text in a UILabel? | <p>For a given <code>NSRange</code>, I'd like to find a <code>CGRect</code> in a <code>UILabel</code> that corresponds to the glyphs of that <code>NSRange</code>. For example, I'd like to find the <code>CGRect</code> that contains the word "dog" in the sentence "The quick brown fox jumps over the lazy dog."</p>
<p><img src="https://i.stack.imgur.com/kHGFF.png" alt="Visual description of problem"></p>
<p>The trick is, the <code>UILabel</code> has multiple lines, and the text is really <code>attributedText</code>, so it's a bit tough to find the exact position of the string.</p>
<p>The method that I'd like to write on my <code>UILabel</code> subclass would look something like this:</p>
<pre><code> - (CGRect)rectForSubstringWithRange:(NSRange)range;
</code></pre>
<hr>
<p><em>Details, for those who are interested:</em></p>
<p>My goal with this is to be able to <em>create a new UILabel with the exact appearance and position of the UILabel, that I can then animate.</em> I've got the rest figured out, but it's this step in particular that's holding me back at the moment.</p>
<p><strong>What I've done to try and solve the issue so far:</strong></p>
<ul>
<li>I'd hoped that with iOS 7, there'd be a bit of Text Kit that would solve this problem, but most every example I've seen with Text Kit focuses on <code>UITextView</code> and <code>UITextField</code>, rather than <code>UILabel</code>.</li>
<li>I've seen another question on Stack Overflow here that promises to solve the problem, but the accepted answer is over two years old, and the code doesn't perform well with attributed text.</li>
</ul>
<p><strong>I'd bet that the right answer to this involves one of the following:</strong></p>
<ul>
<li>Using a standard Text Kit method to solve this problem in a single line of code. I'd bet it would involve <code>NSLayoutManager</code> and <code>textContainerForGlyphAtIndex:effectiveRange</code></li>
<li>Writing a complex method that breaks the UILabel into lines, and finds the rect of a glyph within a line, likely using Core Text methods. My current best bet is to take apart <a href="https://stackoverflow.com/users/157142/mattt">@mattt's</a> excellent <a href="https://github.com/mattt/TTTAttributedLabel" rel="noreferrer">TTTAttributedLabel</a>, which has a method that finds a glyph at a point - if I invert that, and find the point for a glyph, that might work.</li>
</ul>
<hr>
<p>Update: Here's a github gist with the three things I've tried so far to solve this issue: <a href="https://gist.github.com/bryanjclark/7036101" rel="noreferrer">https://gist.github.com/bryanjclark/7036101</a></p> | 20,633,388 | 9 | 7 | null | 2013-10-17 03:31:53.57 UTC | 34 | 2022-06-15 21:31:32.84 UTC | 2017-05-23 12:34:20.61 UTC | null | -1 | null | 686,902 | null | 1 | 80 | ios|ios7|uilabel|textkit | 28,835 | <p>Following <a href="https://stackoverflow.com/a/19620560/1129789">Joshua's answer</a> in code, I came up with the following which seems to work well:</p>
<pre><code>- (CGRect)boundingRectForCharacterRange:(NSRange)range
{
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:[self attributedText]];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
NSRange glyphRange;
// Convert the range for glyphs.
[layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
}
</code></pre> |
17,344,061 | please wait while jenkins is restarting- waiting long | <p>I updated some plugins and restarted the jenkins but now it says:</p>
<blockquote>
<p>Please wait while Jenkins is restarting</p>
<p>Your browser will reload automatically when Jenkins is ready.</p>
</blockquote>
<p>It is taking too much time (waiting from last 40 minutes). I have only 1 project with around 20 builds. I have restarted jenkins many times and worked fine but now it stucks.
Is there any way out to kill/suspend jenkins to avoid this wait?</p> | 19,789,679 | 16 | 2 | null | 2013-06-27 13:08:39.573 UTC | 9 | 2022-08-23 22:54:20.533 UTC | null | null | null | null | 2,482,110 | null | 1 | 47 | jenkins | 56,473 | <p>I had a very similar issue when using jenkins build-in restart function. To fix it I killed the service (with crossed fingers), but somehow it kept serving the "Please wait" page. I guess it is served by a separate thread, but since i could not see any running java or jenkins processes i restarted the server to stop it. </p>
<p>After reboot jenkins worked but it was not updated. To make it work it I ran the update again and restarted the jenkins service manually - it took less than a minute and worked just fine...</p>
<p>Jenkins seems to have a number of bugs related to restarting, and at least one unresolved: <a href="https://issues.jenkins-ci.org/browse/JENKINS-18387">jenkins issue</a></p> |
17,536,652 | Gradle and Multi-Project structure | <p>I'm trying to understand how should I approach the following project setup:</p>
<pre><code>┌Top Android Project
│
├── Project 1 - (Pure Java Modules)
│ │
│ ├── Module A1
│ ├── Module B1
│ :
│ └── Module Z1
│
├── Project 2 - (Android Libraries Modules)
│ │
│ ├── Module A2
│ ├── Module B2
│ :
│ └── Module Z2
│
└── Module - Actual Android Project
</code></pre>
<p>In the current setup I have there is a build.gradle in each of the Modules, what I really hate about this setup is that all the content of the build.gradle is duplicated between modules.</p>
<p>Fact is that I would like the same logic in most of them, '<strong>Pure Java Modules</strong>' are all infra modules, which I would like to Jar the output, the JavaDoc, and sources, and deploy to some remote repository (* default).</p>
<p>On the other hand, some modules of the '<strong>Pure Java Modules</strong>' I would like to have a second agenda, for example, aside from the default* build I would like to deploy a jar with dependencies for a specific project, or something like that.</p>
<p>While building the <strong>Actual Android Project</strong>, I would like the modules to compile in the default* build, and finally to configure a default build.gradle for all of my Android projects, which are quite a few, and I would not like to duplicate that file.</p>
<p><strong>===============================================================</strong></p>
<p>I guess what I'm looking for is something like Maven parent pom, but since I don't fully understand how Gradle works, I'm opening this to you guys to share your thoughts...</p>
<p>Taking under consideration that duplicating same build file is (I dare say) unacceptable, due to the fact that I might want to change something in all the build logic of all the modules</p>
<p>What would be the best approach to handle this sort of setup?</p> | 17,538,127 | 2 | 0 | null | 2013-07-08 21:55:14.57 UTC | 39 | 2014-06-16 21:27:25.2 UTC | 2014-06-16 21:27:25.2 UTC | null | 3,337,489 | null | 348,189 | null | 1 | 61 | android|gradle|android-studio|build.gradle|multi-project | 31,877 | <p>Most of this is pretty normal to the <a href="http://www.gradle.org/docs/current/userguide/multi_project_builds.html">http://www.gradle.org/docs/current/userguide/multi_project_builds.html</a> page. However you are going to need to add </p>
<pre><code>evaluationDependsOn(':project1')
evaluationDependsOn(':project2')
</code></pre>
<p>so that gradle will evaluate project1 and project2 before module. In all the projects that contain code you will need to have an empty build.gradle file. This will also allow you to customize a project if needed.</p>
<p><strong>Example:</strong> <a href="https://github.com/ethankhall/AndroidComplexBuild">https://github.com/ethankhall/AndroidComplexBuild</a></p>
<p>Add a build.gradle at the root of your projects. So you need 4 that have useful information in it.</p>
<pre><code>/build.gradle
/settings.gradle
/project1/build.gradle
/project2/build.gradle
/module/build.gradle
</code></pre>
<p>in /build.gradle put</p>
<pre><code>dependencies {
project(":module")
}
</code></pre>
<p>in /settings.gradle put</p>
<pre><code>include ':module'
include ':project1', ':project1:A1', ':project1:B1', ':project1:Z1'
include ':project2', ':project2:A2', ':project2:B2', ':project2:Z2'
</code></pre>
<p>in /project1/build.gradle put</p>
<pre><code>apply plugin: 'java'
subprojects {
apply plugin: 'java'
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
repositories{
mavenCentral()
}
//Anything else you would need here that would be shared across all subprojects
}
</code></pre>
<p>/project2/build.gradle</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.2'
}
}
subprojects {
apply plugin: 'android-library'
android {
compileSdkVersion 17
buildToolsVersion "17.0"
}
sourceCompatibility = JavaVersion.VERSION_1_6
targetCompatibility = JavaVersion.VERSION_1_6
repositories{
mavenCentral()
}
//Anything else you would need here that would be shared across all subprojects
}
</code></pre>
<p>in /module/build.gradle put</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.2'
}
}
evaluationDependsOn(':project1')
evaluationDependsOn(':project2')
apply plugin: 'android'
android {
compileSdkVersion 17
buildToolsVersion "17.0"
}
dependencies {
compile project(":project1:A1")
compile project(":project1:B1")
compile project(":project1:Z1")
compile project(":project2:A2")
compile project(":project2:B2")
compile project(":project2:Z2")
}
</code></pre> |
18,650,697 | Cost of storing AMI | <p>I understand Amazon will charge per GB provisioned EBS storage. If I create AMI of my instance, does this mean my EBS volume will be duplicated, and hence incur additional cost?</p>
<p>Is there other cost charge in creating and storing an AMI (Amazon Machine Image)? </p> | 18,661,365 | 3 | 0 | null | 2013-09-06 05:43:13.487 UTC | 23 | 2022-02-07 21:08:46.537 UTC | null | null | null | null | 179,630 | null | 1 | 114 | amazon-web-services|amazon-ec2 | 110,773 | <p>You are only charged for the storage of the bits that make up your AMI, there are no charges for creating an AMI.</p>
<ul>
<li>EBS-backed AMIs are made up of snapshots of the EBS volumes that form the AMI. You will pay storage fees for those snapshots according to the <a href="https://aws.amazon.com/ebs/pricing/" rel="noreferrer">rates listed here</a>. Your EBS volumes are not "duplicated" until the instance is launched, at which point a volume is created from the stored snapshots and you'll pay <a href="https://aws.amazon.com/ebs/pricing/" rel="noreferrer">regular EBS volume fees</a> and <a href="https://aws.amazon.com/premiumsupport/knowledge-center/ebs-snapshot-billing/" rel="noreferrer">EBS snapshot billing</a>.</li>
<li>S3-backed AMIs have their information stored in S3 and you will pay storage fees for the data being stored in S3 according to the <a href="http://aws.amazon.com/s3/pricing/" rel="noreferrer">S3 pricing</a>, whether the instance is running or not.</li>
</ul> |
26,058,823 | Correct way of Encrypting and Decrypting an Image using AES | <p>EDIT ::: The code in the question works, but it takes around 10 seconds for getting back to the activity once the image is taken in camera. I gave up this approach and used Facebook's Conceal Library to encrypt and decrypt images. Link to Facebook's Solution : <a href="https://stackoverflow.com/questions/26140389/facebook-conceal-image-encryption-and-decryption">Facebook Conceal - Image Encryption and Decryption</a></p>
<hr>
<p>I have looked at lot of examples, but still couldn't figure out a way to get Encryption and Decryption right. I thought i got it correct when I used some random code on the internet, but while decoding, i get a BadPadding Exception. </p>
<p>So, i am trying to work it out. I am following the below question, as suggested by most people on SO (but this code shows how to encrypt a string). Can some one help me out in encrypting and decrypting the image? Will the code in the question work for images?</p>
<p>Link to the question : <a href="https://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption/992413#992413">Java 256-bit AES Password-Based Encryption</a></p>
<p>Here is what i have done till now:</p>
<p>//Global arraylist to store iv and cipher</p>
<pre><code>static ArrayList<byte[]> ivandcipher = new ArrayList<byte[]>();
</code></pre>
<p>//Generating Key</p>
<pre><code>public static SecretKey generateKey() throws NoSuchAlgorithmException {
char[] password = { 'a', 'b', 'c', 'd', 'e' };
byte[] salt = { 1, 2, 3, 4, 5 };
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = null;
try {
tmp = factory.generateSecret(spec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
yourKey = new SecretKeySpec(tmp.getEncoded(), "AES");
return yourKey;
}
</code></pre>
<p>//Encoding File</p>
<p>//byte[] fileData, contains the bitmap(image) converted to byte[]</p>
<pre><code>public static ArrayList<byte[]> encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] encrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, yourKey);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
encrypted = cipher.doFinal(fileData);
ivandcipher.clear();
ivandcipher.add(iv);
ivandcipher.add(encrypted);
return ivandcipher;
}
</code></pre>
<p>Why am i adding iv and encrypted byte[]s to ivandcipher. Because, as the answer in the link suggests, that i should be using the same iv while decryption.</p>
<p>//Decode file</p>
<p>//I call a overloaded decodeFile method inside this method.. please note</p>
<pre><code>private Bitmap decodeFile(String filename) {
try {
yourKey = generateKey();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try {
byte[] decodedData = decodeFile(yourKey, readFile(filename));
Bitmap bitmap = bytesToBitmap(decodedData);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
</code></pre>
<p>//overloaded decodeFile method</p>
<pre><code>public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(ivandcipher.get(0)));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
</code></pre>
<p>I guess the problem is with the fileData[], that i am not able to encrypt and decrypt correctly. For Strings as shown in the answer of the above link, i.e., </p>
<p><code>byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));</code></p>
<p>what should be given as parameter for cipher.doFinal()?</p>
<p>Let me know if you need any other piece of code.</p> | 26,233,976 | 3 | 3 | null | 2014-09-26 11:47:01.593 UTC | 8 | 2017-01-24 05:18:33.403 UTC | 2017-05-23 12:32:26.04 UTC | null | -1 | null | 1,777,523 | null | 1 | 0 | java|android|encryption|cryptography | 24,372 | <p>The code in the question works, but it takes around 10 seconds for getting back to the activity once the image is taken in camera. I gave up this approach and used Facebook's Conceal Library to encrypt and decrypt images. Link to Facebook's Solution : <a href="https://stackoverflow.com/questions/26140389/facebook-conceal-image-encryption-and-decryption">Facebook Conceal - Image Encryption and Decryption</a></p> |
23,063,474 | Why does this Java 8 program not compile? | <p>This program compiles fine in Java 7 (or in Java 8 with <code>-source 7</code>), but fails to compile with Java 8:</p>
<pre><code>interface Iface<T> {}
class Impl implements Iface<Impl> {}
class Acceptor<T extends Iface<T>> {
public Acceptor(T obj) {}
}
public class Main {
public static void main(String[] args) {
Acceptor<?> acceptor = new Acceptor<>(new Impl());
}
}
</code></pre>
<p>Result:</p>
<pre><code>Main.java:10: error: incompatible types: cannot infer type arguments for Acceptor<>
Acceptor<?> acceptor = new Acceptor<>(new Impl());
^
reason: inference variable T has incompatible bounds
equality constraints: Impl
upper bounds: Iface<CAP#1>,Iface<T>
where T is a type-variable:
T extends Iface<T> declared in class Acceptor
where CAP#1 is a fresh type-variable:
CAP#1 extends Iface<CAP#1> from capture of ?
1 error
</code></pre>
<p>In other words, this is a <em>backwards</em> source incompatibility between Java 7 and 8. I've gone through <a href="http://www.oracle.com/technetwork/java/javase/8-compatibility-guide-2156366.html#A999198" rel="noreferrer">Incompatibilities between Java SE 8 and Java SE 7</a> list but did not found anything that would fit my problem.</p>
<p>So, is this a bug?</p>
<p>Environment:</p>
<pre><code>$ /usr/lib/jvm/java-8-oracle/bin/java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
</code></pre> | 23,838,350 | 3 | 10 | null | 2014-04-14 15:00:19.007 UTC | 16 | 2014-05-23 21:08:33.547 UTC | 2014-04-15 08:46:02.503 UTC | null | 931,323 | null | 931,323 | null | 1 | 77 | java|generics|type-inference|java-8 | 21,288 | <p>Thanks for the report. This looks like a bug. I will take care of it and probably add a better answer once we have more information about why this is happening. I have filed this bug entry <a href="https://bugs.openjdk.java.net/browse/JDK-8043926">JDK-8043926</a>, to track it.</p> |
5,037,230 | git diff with opendiff gives "Couldn't launch FileMerge" error | <p>I have git configured to use ~/bin/opendiff-git.sh as my external diff tool. That script looks like this:</p>
<pre><code>opendiff $2 $5
</code></pre>
<p>When I try and do a git diff from the command line, I get this message:</p>
<pre><code>2011-02-18 13:58:55.532 opendiff[27959:60f] exception raised trying to run FileMerge: launch path not accessible
2011-02-18 13:58:55.535 opendiff[27959:60f] Couldn't launch FileMerge
external diff died, stopping at source/some_file.m.
</code></pre>
<p>What's going on? This has worked for many months, but stopped working recently.</p> | 6,991,161 | 3 | 0 | null | 2011-02-18 03:02:23.903 UTC | 16 | 2012-05-15 21:09:11.19 UTC | 2011-02-18 03:11:54.297 UTC | null | 86,046 | null | 86,046 | null | 1 | 13 | xcode|git|filemerge|opendiff | 9,105 | <p>So AFTER I deleted the beta developer folder to try and solve this (couldn't get the fix to work with merge tool) I stumbled upon this in the command line:</p>
<pre><code>Error: No developer directory found at /Developer Beta. Run /usr/bin/xcode-select to update the developer directory path.
</code></pre>
<p>Turns out you can set the developer path you need it to use:</p>
<pre><code>Usage: xcode-select -print-path
or: xcode-select -switch <xcode_folder_path>
or: xcode-select -version
Arguments:
-print-path Prints the path of the current Xcode folder
-switch <xcode_folder_path> Sets the path for the current Xcode folder
-version
</code></pre>
<p>Looks like installing the beta had automatically set that path to beta. To fix it, run this:</p>
<pre><code>sudo /usr/bin/xcode-select -switch /Developer
</code></pre>
<p>That fixed it for me.</p>
<h3>Update</h3>
<p>Ying's comment below was important enough to include in the answer. From Xcode 4.3 on, the location of the folder has changed to inside the application package:</p>
<pre><code>sudo /usr/bin/xcode-select -switch /Applications/Xcode.app/Contents/Developer/
</code></pre> |
5,053,501 | Put WPF control into a Windows Forms Form? | <p>How do you put a WPF control into a Windows Forms <code>Form</code>? Most likely I will be inserting my WPF control into a <code>Windows.Forms.Panel</code>.</p> | 5,053,518 | 3 | 2 | null | 2011-02-19 21:00:12.76 UTC | 5 | 2021-06-24 19:56:27.21 UTC | 2021-06-24 19:56:00.04 UTC | null | 3,195,477 | null | 476,298 | null | 1 | 31 | c#|.net|wpf|visual-studio-2008|.net-3.5 | 61,215 | <p>Put an <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.elementhost.aspx" rel="nofollow noreferrer"><strong><code>ElementHost</code></strong></a> control inside the panel. This control can then host a WPF element. From the WinForms designer, you can find this control under 'WPF Interoperability'. First you may need to add <code>WindowsFormsIntegration.dll</code> to your project's references.</p>
<p>For an example, see <a href="https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-hosting-a-wpf-composite-control-in-windows-forms" rel="nofollow noreferrer">Walkthrough: Hosting a WPF Composite Control in Windows Forms</a>.</p> |
5,175,925 | What's the time complexity of array.splice() in Google Chrome? | <p>If I remove one element from an array using splice() like so:</p>
<pre><code>arr.splice(i, 1);
</code></pre>
<p>Will this be <code>O(n)</code> in the worst case because it shifts all the elements after i? Or is it constant time, with some linked list magic underneath?</p> | 5,175,958 | 3 | 5 | null | 2011-03-03 02:16:20.147 UTC | 9 | 2021-05-18 14:45:59.307 UTC | 2011-03-03 03:08:40.933 UTC | null | 247,722 | null | 247,722 | null | 1 | 48 | javascript|google-chrome|big-o|time-complexity|v8 | 29,200 | <p>Worst case <em>should</em> be <code>O(n)</code> (copying all <code>n-1</code> elements to new array).</p>
<p>A linked list would be <code>O(1)</code> for a single deletion.</p>
<p>For those interested I've made this lazily-crafted <a href="http://jsfiddle.net/eXgkT/1/" rel="noreferrer">benchmark</a>. (<a href="http://ejohn.org/blog/accuracy-of-javascript-time/" rel="noreferrer">Please don't run on Windows XP/Vista</a>). <strike>As you can see from this though, it looks fairly constant (i.e. <code>O(1)</code>), so who knows what they're doing behind the scenes to make this crazy-fast. Note that regardless, the actual <code>splice</code> is VERY fast.</strike></p>
<p>Rerunning an <a href="http://jsfiddle.net/eXgkT/2/" rel="noreferrer">extended benchmark</a> directly in the V8 shell that suggest <code>O(n)</code>. Note though that you need huge array sizes to get a runtime that's likely to affect your code. This should be expected as if you look at the V8 code it uses <code>memmove</code> to create the new array.</p> |
25,730,830 | How to get only images in the camera roll using Photos Framework | <p>The following code loads images that are also located on iCloud or the streams images. How can we limit the search to only images in the camera roll?</p>
<pre><code>var assets = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: nil)
</code></pre> | 25,732,673 | 8 | 3 | null | 2014-09-08 18:31:59.757 UTC | 9 | 2021-07-28 18:20:32.43 UTC | 2014-09-08 21:25:18.487 UTC | null | 1,552,585 | null | 1,552,585 | null | 1 | 24 | ios|swift|photosframework | 29,887 | <p>Through some experimentation we discovered a hidden property not listed in the documentation (<code>assetSource</code>). Basically you have to do a regular fetch request, then use a predicate to filter the ones from the camera roll. This value should be 3.</p>
<p>Sample code:</p>
<pre><code>//fetch all assets, then sub fetch only the range we need
var assets = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)
assets.enumerateObjectsUsingBlock { (obj, idx, bool) -> Void in
results.addObject(obj)
}
var cameraRollAssets = results.filteredArrayUsingPredicate(NSPredicate(format: "assetSource == %@", argumentArray: [3]))
results = NSMutableArray(array: cameraRollAssets)
</code></pre> |
9,305,632 | Java: For-Each loop and references | <p>I am wondering if the following loop creates a copy of the object, rather than giving me a reference to it. The reason is, because the first example doesn't allocate my array objects, but the second does.</p>
<pre><code>MyObject objects[] = new MyObject[6];
for (MyObject o: objects) {
o = new MyObject();
}
MyObject objects[] = new MyObject[6];
for(int i = 0; i < objects.length; i++) {
objects[i] = new MyObject();
}
</code></pre> | 9,305,672 | 7 | 5 | null | 2012-02-16 04:38:50.837 UTC | 7 | 2015-07-13 09:01:33.827 UTC | 2014-07-10 06:50:25.353 UTC | null | 1,213,006 | null | 1,213,006 | null | 1 | 16 | java|object|loops|for-loop | 78,667 | <p>Java works a little bit different than many other languages. What <code>o</code> is in the first example is simply a reference to the object.</p>
<p>When you say <code>o = new MyObject()</code>, it creates a new Object of type MyObject and references <code>o</code> to that object, whereas before <code>o</code> referenced <code>objects[index]</code>.</p>
<p>That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].</p>
<p>Image: (my terrible paint skills :D)</p>
<p><img src="https://i.stack.imgur.com/yWCV2.png" alt="enter image description here"></p>
<p>Explanation:
This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you're looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.</p>
<p>o does not reference A1 or B1, but C1 or C2. When you say <code>new ...</code>, it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.</p>
<p>Let me know if I can clear things up a little.</p> |
9,512,506 | Why there is an extra "(1 row(s) affected)" | <p>The SSMS shows an extra <code>(1 row(s) affected)</code> every time when I execute <code>insert/update</code>. For example, execute the following SQL</p>
<pre><code>declare @a table (a int)
insert into @a values (1), (2)
update @a set a = 3
</code></pre>
<p>And the SSMS will display the following message.</p>
<pre>
(2 row(s) affected)
(1 row(s) affected)
(2 row(s) affected)
(1 row(s) affected)
</pre>
<p>I didn't find any database/server trigger. What could cause the extra <code>(1 row(s) affected)</code>?</p> | 9,512,615 | 3 | 5 | null | 2012-03-01 07:53:44.447 UTC | 2 | 2022-01-07 12:14:53.57 UTC | null | null | null | null | 825,920 | null | 1 | 29 | sql-server|sql-server-2008 | 19,430 | <p>That usually means you have the <code>actual execution plan</code> option turned on. The execution plan is sent as an extra rowset, resulting in an extra <code>(1 row(s) affected)</code> message.</p>
<p>To disable actual execution plan press Ctrl+M.</p> |
15,240,432 | Does __syncthreads() synchronize all threads in the grid? | <p>...or just the threads in the current warp or block?</p>
<p>Also, when the threads in a particular block encounter (in the kernel) the following line</p>
<pre><code>__shared__ float srdMem[128];
</code></pre>
<p>will they just declare this space once (per block)?</p>
<p>They all obviously operate asynchronously so if Thread 23 in Block 22 is the first thread to reach this line, and then Thread 69 in Block 22 is the last one to reach this line, Thread 69 will know that it already has been declared?</p> | 15,242,326 | 5 | 1 | null | 2013-03-06 06:25:42.73 UTC | 11 | 2021-01-08 21:41:42.647 UTC | null | null | null | null | 1,165,790 | null | 1 | 59 | cuda | 95,737 | <p>The <code>__syncthreads()</code> command is a <strong>block level</strong> synchronization barrier. That means it is safe to be used when all threads in a block reach the barrier. It is also possible to use <code>__syncthreads()</code> in conditional code but only when all threads evaluate identically such code otherwise the execution is likely to hang or produce unintended side effects <a href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#synchronization-functions" rel="noreferrer">[4]</a>.</p>
<p>Example of using <code>__syncthreads()</code>: (<a href="https://stackoverflow.com/a/8234681/2064818">source</a>)</p>
<pre><code>__global__ void globFunction(int *arr, int N)
{
__shared__ int local_array[THREADS_PER_BLOCK]; //local block memory cache
int idx = blockIdx.x* blockDim.x+ threadIdx.x;
//...calculate results
local_array[threadIdx.x] = results;
//synchronize the local threads writing to the local memory cache
__syncthreads();
// read the results of another thread in the current thread
int val = local_array[(threadIdx.x + 1) % THREADS_PER_BLOCK];
//write back the value to global memory
arr[idx] = val;
}
</code></pre>
<p>To synchronize all threads in a grid currently there is <strong>not</strong> native API call. One way of synchronizing threads on a grid level is using <strong>consecutive kernel calls</strong> as at that point all threads end and start again from the same point. It is also commonly called CPU synchronization or Implicit synchronization. Thus they are all synchronized. </p>
<p>Example of using this technique (<a href="http://www.nvidia.com/content/GTC/documents/SC09_Feng.pdf" rel="noreferrer">source</a>):</p>
<p><img src="https://i.stack.imgur.com/D5gnV.png" alt="CPU synchronization"></p>
<p>Regarding the <strong>second</strong> question. <strong>Yes</strong>, it does declare the amount of shared memory specified per block. Take into account that the quantity of available shared memory is measured per <strong><em>SM</em></strong>. So one should be very <strong>careful</strong> how the <strong>shared memory</strong> is used along with the <strong>launch configuration</strong>.</p> |
15,178,358 | How to use sidebar with the keyboard in Sublime Text 2 and 3? | <p>When using <em>Sublime Text 2</em> we tend to open the <em>side bar</em> to navigate thru files/folders in our projects. For that we can use the hotkey <em>ctrl+k ctrl+b</em> (in windows).</p>
<p>However, once we're in the <em>side bar</em>, we <strong>can't use it with keyboard</strong> (arrows for instance). We have to stick using it with our own mouse...</p>
<p><strong>Just a note</strong>: I installed SideBarEnhancements plugin, but I didn't find anything that could solve my problem.</p>
<p>Any solution you might know?</p> | 15,179,191 | 13 | 2 | null | 2013-03-02 19:18:12.177 UTC | 55 | 2020-05-11 19:55:05.483 UTC | 2015-12-01 09:51:19.86 UTC | null | 3,540,289 | null | 854,676 | null | 1 | 160 | sublimetext2|keyboard-shortcuts|sublimetext3|sublimetext|text-editor | 52,302 | <p>You can type <kbd>Ctrl</kbd>+<kbd>0</kbd> (<kbd>Ctrl</kbd>+<kbd>Zero</kbd>) to focus on the side bar.</p>
<p>Then you'll be able to move selection among files with arrow keys and to open the selected file hitting <kbd>Enter</kbd>, without touching the mouse.</p> |
14,976,495 | Get selected option text with JavaScript | <p>I have a dropdown list like this:</p>
<pre><code><select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
</code></pre>
<p>How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:</p>
<pre><code><select id="box1" onChange="myNewFunction(this.selectedIndex);" >
</code></pre>
<p>But rather than <code>7122</code> I want <code>cat</code>.</p> | 14,976,638 | 15 | 3 | null | 2013-02-20 09:35:41.157 UTC | 33 | 2022-05-16 13:34:20.613 UTC | 2015-06-10 11:00:53.783 UTC | null | 1,151,831 | null | 603,902 | null | 1 | 230 | javascript|html|dom|drop-down-menu | 529,462 | <p>Try options</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>function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select></code></pre>
</div>
</div>
</p> |
43,855,166 | How to tell if two dates are in the same day or in the same hour? | <p>The JavaScript Date object compare dates with time including, so, if you compare:
<code>time1.getTime() === time2.getTime()</code>, they'll be <strong>"false"</strong> if at least one millisecond is different.</p>
<p>What we need is to have a nice way to compare by Hour, Day, Week, Month, Year?
Some of them are easy, like year: <code>time1.getYear() === time2.getYear()</code>
but with day, month, hour it is more complex, as it requires multiple validations or divisions.</p>
<p>Is there any nice module or optimized code for doing those comparisons?</p> | 43,855,221 | 2 | 4 | null | 2017-05-08 18:50:03.767 UTC | 5 | 2021-09-07 09:21:37.017 UTC | 2021-09-07 09:21:37.017 UTC | null | 2,215,679 | null | 496,136 | null | 1 | 67 | javascript|typescript | 53,329 | <p>The Date prototype has APIs that allow you to check the year, month, and day-of-month, which seems simple and effective.</p>
<p>You'll want to decide whether your application needs the dates to be the same from the point of view of the locale where your code runs, or if the comparison should be based on UTC values.</p>
<pre><code>function sameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate();
}
</code></pre>
<p>There are corresponding UTC getters <code>getUTCFullYear()</code>, <code>getUTCMonth()</code>, and <code>getUTCDate()</code>.</p> |
28,370,295 | SQL Server : How to test if a string has only digit characters | <p>I am working in SQL Server 2008. I am trying to test whether a string (varchar) has only digit characters (0-9). I know that the IS_NUMERIC function can give spurious results. (My data can possibly have $ signs, which should not pass the test.) So, I'm avoiding that function.</p>
<p>I already have a test to see if a string has any non-digit characters, i.e.,</p>
<pre><code>some_column LIKE '%[^0123456789]%'
</code></pre>
<p>I would think that the only-digits test would be something similar, but I'm drawing a blank. Any ideas?</p> | 28,370,642 | 7 | 3 | null | 2015-02-06 16:26:24.213 UTC | 5 | 2021-01-21 08:55:20.873 UTC | 2016-09-17 14:01:52.767 UTC | null | 3,349,551 | null | 3,100,444 | null | 1 | 50 | sql|sql-server|sql-server-2008 | 141,082 | <p>Use <code>Not Like</code> </p>
<pre><code>where some_column NOT LIKE '%[^0-9]%'
</code></pre>
<h2>Demo</h2>
<pre><code>declare @str varchar(50)='50'--'asdarew345'
select 1 where @str NOT LIKE '%[^0-9]%'
</code></pre> |
28,013,717 | eclemma branch coverage for switch: 7 of 19 missed | <p>I have this switch system and I'm using eclemma to test the branch coverage. We are required to have at least 80% in branch coverage for everything so I'm trying to test as much as possible.
However, eclemma tells me this switch system is not fully tested in terms of branch coverage.</p>
<pre><code>pos = p.getCurrentPosition().substring(0, 1);
switch (pos) {
case "G":
goalkeepers++;
break;
case "D":
defense++;
break;
case "M":
midfield++;
break;
case "F":
offense++;
break;
case "S":
substitutes++;
break;
case "R":
reserves++;
break;
}
</code></pre>
<p>I used straightforward JUnit tests to go trough each of these cases.
Still eclemma marks this as yellow and says "7 of 19 branches missed".
I would say there are only 7 ways to go through this switch system (the 6 individual cases+all undefined). </p>
<p>I tried searching for similar questions on stack overflow. Some of them had as solutions to use if/else for full coverage. I'm not sure if this is the only way possible to get this coverage.</p>
<p>Can anybody explain where all these 19 branches come from and how I could test these remaining 7 to get a 100% branch coverage on this switch case?</p> | 28,015,212 | 2 | 3 | null | 2015-01-18 19:14:24.993 UTC | 3 | 2015-01-20 17:05:55.03 UTC | 2015-01-18 19:25:04.987 UTC | null | 4,159,284 | null | 4,159,284 | null | 1 | 29 | java|testing|switch-statement|code-coverage|eclemma | 14,367 | <p>The Java compiler translates the switch-case code either to a <code>tableswitch</code> or to a <code>lookupswitch</code>.
The <code>tableswitch</code> is used when there are only a few gaps are between the different cases. Otherwise, the <code>lookupswitch</code> is used.</p>
<p><strong>In your case a <code>tableswitch</code> is used</strong> because the hash codes of your cases are closely spaced (unlike in the code referenced by owaism):</p>
<pre><code> 16: tableswitch { // 68 to 83
68: 111 // 'D'
69: 183
70: 141 // 'F'
71: 96 // 'G'
72: 183
73: 183
74: 183
75: 183
76: 183
77: 126 // 'M'
78: 183
79: 183
80: 183
81: 183
82: 171 // 'R'
83: 156 // 'S'
default: 183
}
</code></pre>
<p>The numbers to the left of the colon are the ordered hash codes and the filled gaps between them, the numbers to the right are the jump destinations. (In Java, the hash code of a character is its ASCII value.)</p>
<p><code>68</code> is the hash code of "D" (the lowest one), and <code>83</code> is the hash code of "S" (the highest one).
<code>69</code> is the value of one of the gaps between the real cases and will jump to the default case.</p>
<p>However, I assume that EclEmma excludes these branches from the coverage computation of a <code>tableswitch</code> (it would lower the coverage even more because of the gaps).
So we have <strong>0 (counted) branches yet.</strong></p>
<p>Next, an equals comparison of the string value is performed at each jump destination (except at the one of the default case). As your switch-case consists of 6 cases, we have 6 six jump destinations with an equals comparison.</p>
<p>The byte code of the comparison for case "G" is below:</p>
<pre><code> 96: aload_3
97: ldc #10
99: invokevirtual #11 java/lang/Object;)Z
102: ifeq 183
105: iconst_0
106: istore 4
108: goto 183
111: aload_3
</code></pre>
<p>EclEmma counts two branches: either the input string and the case string are equals or they are not. Thus, we have <strong>6 * 2 branches for the comparisons.</strong> (The default case does not branch.)</p>
<p>Next, if the two strings are equal the index of the case will be stored (byte code lines <code>105-106</code> for the case "G"). Then a jump to the second <code>tableswitch</code> will be executed. Otherwise, the jump will be executed directly.</p>
<pre><code> 185: tableswitch { // 0 to 5
0: 224
1: 237
2: 250
3: 263
4: 276
5: 289
default: 299
}
</code></pre>
<p>This switch operates on the previously stored case index and jumps to the code in the case (case "G" has index <code>0</code>, the default case has <code>-1</code>). EclEmma counts <strong>7 branches (6 cases plus the default case).</strong></p>
<p>Consequently, we have 0 counted branches in the first <code>tableswitch</code>, 12 branches in the <code>equals</code> comparisons and further 7 branches in the second <code>tableswitch</code>. All in all, this <strong>results in 19 branches.</strong></p>
<hr>
<p>Your <strong>tests do not cover any of the 6 not-equals branches.</strong>
In order to cover these, you would need to find a string for each case which is not equal to the case condition but has the same hash code.
It is possible, but definitively not sensible...</p>
<p>Probably, the branch counting of EclEmma will be adjusted in the future.</p>
<p>Moreover, I guess you don't have a test case which does not match with any of the cases (thus the <strong>(implicit) default case is not covered.)</strong></p> |
7,761,287 | Backbone.js: how to redirect from one view to another view? | <p>In Backbone.js, what is the equivalent of HttpResponseRedirect in Django? </p>
<p>In one Backbone.View, I need to submit data to the server, and then redirect the user to another view. How does this work? Should I use event or router? </p>
<p>Thanks!</p> | 7,762,553 | 2 | 1 | null | 2011-10-13 22:43:21.403 UTC | 11 | 2014-06-09 04:40:32.29 UTC | null | null | null | null | 929,318 | null | 1 | 23 | backbone.js | 34,308 | <p>It's important to understand that <a href="http://lostechies.com/derickbailey/2011/08/03/stop-using-backbone-as-if-it-were-a-stateless-web-server/" rel="noreferrer">Backbone is not a stateless web server</a>, so a "redirect" might sound like what you want, but it most likely isn't. If you have any experience in building stateful desktop applications, draw from that experience and how you would move from one screen to another. If you don't have any desktop client experience, I highly recommend you get some of that under your belt because a Backbone app is a stateful app, it just happens to run in a browser.</p>
<p>Assuming you've got some stateful app knowledge, you have a couple of options for making this work.</p>
<h3>Router.navigate: the "redirect" equivalent (not a fan of this)</h3>
<p>After your call to the server has come back, you can call your router's <code>navigate</code> method: <code>myRouter.navigate("/myRoute", true)</code>. Be sure to pass the <code>true</code> argument as the second parameter. Or, like JasonOffutt suggest, just manually update the url's hash fragment and it's effectively the same thing.</p>
<p><a href="http://lostechies.com/derickbailey/2011/08/28/dont-execute-a-backbone-js-route-handler-from-your-code/" rel="noreferrer">I'm not fond of this</a>, but some people are.</p>
<h3>Procedural workflow</h3>
<p>You can create a very simple object that knows how to put the right view on the screen, when you call a method. For example, if you need to show a view called "WidgetView", create an object with a method called <code>showWidgetView</code>. Make the object with this method available anywhere in your code by attaching it to a namespace, passing it to your running code, or some other technique. When your call to the server returns, call the object's <code>showWidgetView</code> method and let it show the next view for you.</p>
<p>This is functional, but it gets messy quickly in anything other than really small apps. I do this in small apps, though. When you get to larget apps, you need to think about evented workflow and event-driven architectures.</p>
<h3>Events and workflow</h3>
<p>After your server call returns, fire off an event using something like <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/" rel="noreferrer">an event aggregator</a>, letting other parts of your system know that something important just happened. These other parts of the system can then figure out what to do in response, including call code that replaces the current view with a new one, updates the url route, etc.</p>
<p>When you go down the path of using events, eventually you'll run into a cluster of code that doesn't seem to fit anywhere, nicely. This is usually your event handlers, and is usually a sign of an object / concern that wants to be encapsulated. Creating higher level workflow objects in Backbone is a good idea if you're using an event driven architecture.</p>
<p>These workflow objects are generally responsible for kicking off a workflow by getting all of the right views and models in place, and then contain event handlers for your views and / or event aggregator. The event handler methods will check the state of the app either through the args passed through the method, or by looking at some other state, and figure out what needs to happen next. Then it will cause the app to change to whatever it needs to look like, based on the new state.</p>
<p>Also, a workflow object is <a href="http://lostechies.com/derickbailey/2011/08/30/dont-limit-your-backbone-apps-to-backbone-constructs/" rel="noreferrer">not a backbone construct</a>. It's something that you'll build yourself, just using plain old JavaScript.</p>
<p>...</p>
<p>Hope that helps.</p> |
9,644,870 | PHP object literal | <p>In PHP, I can specify array literals quite easily:</p>
<pre><code>array(
array("name" => "John", "hobby" => "hiking"),
array("name" => "Jane", "hobby" => "dancing"),
...
)
</code></pre>
<p>But what if I want array of objects? How can I specify object literal in PHP?
I.e. in javascript it would be:</p>
<pre><code>[
{name: "John", hobby: "hiking"},
{name: "Jane", hobby: "dancing"}
]
</code></pre> | 9,644,977 | 10 | 6 | null | 2012-03-10 07:54:54.363 UTC | 11 | 2021-06-09 17:23:23.117 UTC | null | null | null | null | 684,229 | null | 1 | 68 | php|object|literals|object-literal | 35,024 | <p>As BoltClock mentioned there is no object literal in PHP however you can do this by simply type casting the arrays to objects:</p>
<pre><code>$testArray = array(
(object)array("name" => "John", "hobby" => "hiking"),
(object)array("name" => "Jane", "hobby" => "dancing")
);
echo "Person 1 Name: ".$testArray[0]->name;
echo "Person 2 Hobby: ".$testArray[1]->hobby;
</code></pre> |
19,416,644 | How can a Java variable be different from itself? | <p>I am wondering if this question can be solved in Java (I'm new to the language). This is the code:</p>
<pre><code>class Condition {
// you can change in the main
public static void main(String[] args) {
int x = 0;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
</code></pre>
<p>I received the following question in my lab: How can you skip the first case (i.e. make the <code>x == x</code> condition false) without modifying the condition itself?</p> | 19,416,665 | 10 | 23 | null | 2013-10-17 01:15:23.187 UTC | 40 | 2021-01-28 16:54:05.82 UTC | 2013-12-10 18:50:20.67 UTC | null | 105,971 | null | 1,187,855 | null | 1 | 109 | java|if-statement | 10,146 | <p>One simple way is to use <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#NaN" rel="noreferrer"><code>Float.NaN</code></a>:</p>
<pre><code>float x = Float.NaN; // <--
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
</code></pre>
<pre>
Not ok
</pre>
<p>You can do the same with <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#NaN" rel="noreferrer"><code>Double.NaN</code></a>.</p>
<hr />
<p>From <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21.1" rel="noreferrer"><strong>JLS §15.21.1.</strong> Numerical Equality Operators <code>==</code> and <code>!=</code></a>:</p>
<blockquote>
<p>Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:</p>
<ul>
<li><p>If either operand is NaN, then the result of <code>==</code> is <code>false</code> but the result of <code>!=</code> is <code>true</code>.</p>
<p>Indeed, the test <code>x!=x</code> is <code>true</code> if and only if the value of <code>x</code> is NaN.</p>
</li>
</ul>
<p>...</p>
</blockquote> |
66,813,185 | Regex to validate subtract equations like "abc-b=ac" | <p>I've stumbled upon a regex question.</p>
<p>How to validate a <em>subtract equation</em> like this?</p>
<p>A string subtract another string equals to whatever remains(all the terms are just plain strings, not sets. So <code>ab</code> and <code>ba</code> are different strings).</p>
<h3>Pass</h3>
<ul>
<li><code>abc-b=ac</code></li>
<li><code>abcde-cd=abe</code></li>
<li><code>ab-a=b</code></li>
<li><code>abcde-a=bcde</code></li>
<li><code>abcde-cde=ab</code></li>
</ul>
<h3>Fail</h3>
<ul>
<li><code>abc-a=c</code></li>
<li><code>abcde-bd=ace</code></li>
<li><code>abc-cd=ab</code></li>
<li><code>abcde-a=cde</code></li>
<li><code>abc-abc=</code></li>
<li><code>abc-=abc</code></li>
</ul>
<p>Here's what I tried and you may play around with it</p>
<p><a href="https://regex101.com/r/lTWUCY/1/" rel="noreferrer">https://regex101.com/r/lTWUCY/1/</a></p> | 66,813,364 | 2 | 7 | null | 2021-03-26 08:14:01.027 UTC | 9 | 2021-03-28 14:11:05.717 UTC | 2021-03-27 02:24:32.71 UTC | null | 10,289,265 | null | 10,289,265 | null | 1 | 16 | regex|pcre | 1,223 | <p><strong>Disclaimer:</strong> I see that some of the comments were deleted. So let me start by saying that, though short (in terms of code-golf), the following answer is <em>not</em> the most efficient in terms of steps involved. Though, looking at the nature of the question and its "puzzle" aspect, it will probably do fine. For a more efficient answer, I'd like to redirect you to <a href="https://stackoverflow.com/a/66813440/9758194">this</a> answer.</p>
<hr />
<p>Here is my attempt:</p>
<pre><code>^(.*)(.+)(.*)-\2=(?=.)\1\3$
</code></pre>
<p>See the online <a href="https://regex101.com/r/4Fwv8V/1" rel="noreferrer">demo</a></p>
<ul>
<li><code>^</code> - Start line anchor.</li>
<li><code>(.*)</code> - A 1st capture group with 0+ non-newline characters right upto;</li>
<li><code>(.+)</code> - A 2nd capture group with 1+ non-newline characters right upto;</li>
<li><code>(.*)</code> - A 3rd capture group with 0+ non-newline characters right upto;</li>
<li><code>-\2=</code> - An hyphen followed by a backreference to our 2nd capture group and a literal "=".</li>
<li><code>(?=.)</code> - A positive lookahead to assert position is followed by at least a single character other than newline.</li>
<li><code>\1\3</code> - A backreference to what was captured in both the 1st and 3rd capture group.</li>
<li><code>$</code> - End line anchor.</li>
</ul>
<hr />
<p><strong>EDIT:</strong></p>
<p>I guess a bit more restrictive could be:</p>
<pre><code>^([a-z]*)([a-z]+)((?1))-\2=(?=.)\1\3$
</code></pre> |
8,554,678 | .Trim() when string is empty or null | <p>I'm receiving some data from the client in the form of json.
I'm writing this:</p>
<pre><code>string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
</code></pre>
<p>If the variable that's being parsed from json comes back empty, does this code crash when I call the .Trim() method?</p>
<p>Thanks.</p> | 8,554,693 | 10 | 3 | null | 2011-12-18 20:46:00.18 UTC | 6 | 2022-09-19 17:37:36.137 UTC | null | null | null | null | 565,968 | null | 1 | 31 | c# | 92,234 | <p>If the serializer returns an empty string, <code>Trim</code> will do nothing.</p>
<p>If the serializer returns <code>null</code>, you will get a <code>NullReferenceException</code> on the call to <code>Trim</code>.</p>
<p>Your code would be better written (as far as initialization is concerned) like this:</p>
<pre><code>string theText =
((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
</code></pre>
<p>There is no point in declaring and initializing the variable and the immediately assigning to it. </p>
<p>The following would be safest, if you don't know what the serializer might return:</p>
<pre><code>string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));
if(!string.IsNullOrEmpty(theText))
{
theText = theText.Trim();
}
</code></pre> |
5,427,839 | Is it possible to make an interactive Rake task? | <p>I want to run a Rake task that asks the user for input. </p>
<p>I know that I can supply input on the command line, but I want to ask the user if they are <em>sure</em> they want to proceed with a particular action in case they mistyped one of the values supplied to the Rake task.</p> | 5,458,190 | 4 | 3 | null | 2011-03-25 02:14:26.81 UTC | 10 | 2019-09-12 20:21:05.537 UTC | 2014-09-29 17:02:17.643 UTC | null | 128,421 | null | 465,986 | null | 1 | 50 | rake | 16,627 | <p>Something like this might work</p>
<pre><code>task :action do
STDOUT.puts "I'm acting!"
end
task :check do
STDOUT.puts "Are you sure? (y/n)"
input = STDIN.gets.strip
if input == 'y'
Rake::Task["action"].reenable
Rake::Task["action"].invoke
else
STDOUT.puts "So sorry for the confusion"
end
end
</code></pre>
<p>Task reenabling and invoking from <a href="https://stackoverflow.com/questions/577944/how-to-run-rake-tasks-from-within-rake-tasks/1290119#1290119">How to run Rake tasks from within Rake tasks?</a></p> |
5,322,669 | sqlite and 'constraint failed' error while select and insert at the same time | <p>I'm working on migration function. It reads data from old table and inserts it into the new one. All that stuff working in background thread with low priority.</p>
<p>My steps in pseudo code.</p>
<pre><code>sqlite3_prepare_stmt (select statement)
sqlite3_prepare_stmt (insert statement)
while (sqlite3_step (select statement) == SQLITE_ROW)
{
get data from select row results
sqlite3_bind select results to insert statement
sqlite3_step (insert statement)
sqlite3_reset (insert statement)
}
sqlite3_reset (select statement)
</code></pre>
<p>I'm always getting 'constraint failed' error on <code>sqlite3_step (insert statement)</code>. Why it's happend and how i could fix that?</p>
<p><strong>UPD:</strong> As i'm understand that's happend because background thread use db handle opened in main thread. Checking that guess now.</p>
<p><strong>UPD2:</strong> </p>
<pre><code>sqlite> select sql from sqlite_master where tbl_name = 'tiles';
CREATE TABLE tiles('pk' INTEGER PRIMARY KEY, 'data' BLOB, 'x' INTEGER, 'y' INTEGER, 'z' INTEGER, 'importKey' INTEGER)
sqlite> select sql from sqlite_master where tbl_name = 'tiles_v2';
CREATE TABLE tiles_v2 (pk int primary key, x int, y int, z int, layer int, data blob, timestamp real)
</code></pre> | 5,324,467 | 6 | 0 | null | 2011-03-16 08:27:58.473 UTC | 1 | 2021-05-27 20:01:41.527 UTC | 2011-03-16 13:49:02.373 UTC | null | 241,482 | null | 241,482 | null | 1 | 7 | sql|sqlite | 67,556 | <p>It probably means your insert statement is violating a constraint in the new table. Could be a primary key constraint, a unique constraint, a foreign key constraint (if you're using <code>PRAGMA foreign_keys = ON;</code>), and so on.</p>
<p>You fix that either by dropping the constraint, correcting the data, or dropping the data. Dropping the constraint is usually a Bad Thing, but that depends on the application.</p>
<p>Is there a compelling reason to copy data one row at a time instead of as a set?</p>
<pre><code>INSERT INTO new_table
SELECT column_list FROM old_table;
</code></pre>
<p>If you need help identifying the constraint, edit your original question, and post the output of these two SQLite queries.</p>
<pre><code>select sql from sqlite_master where tbl_name = 'old_table_name';
select sql from sqlite_master where tbl_name = 'new_table_name';
</code></pre>
<hr>
<p><strong>Update:</strong> Based on the output of those two queries, I see only one constraint--the primary key constraint in each table. If you haven't built any triggers on these tables, the only constraint that can fail is the primary key constraint. And the only way that constraint can fail is if you try to insert two rows that have the same value for 'pk'.</p>
<p>I suppose that could happen in a few different ways.</p>
<ul>
<li>The old table has duplicate values in
the 'pk' column.</li>
<li>The code that does your migration
alters or injects a duplicate value
before inserting data into your new
table.</li>
<li>Another process, possibly running on
a different computer, is inserting or
updating data without your knowledge.</li>
<li>Other reasons I haven't thought of yet. :-)</li>
</ul>
<p>You can determine whether there are duplicate values of 'pk' in the old table by running this query.</p>
<pre><code>select pk
from old_table_name
group by pk
having count() > 1;
</code></pre>
<p>You might consider trying to manually migrate the data using <code>INSERT INTO . . . SELECT . . .</code> If that fails, add a WHERE clause to reduce the size of the set until you isolate the bad data.</p> |
5,398,930 | General rules of passing/returning reference of array (not pointer) to/from a function? | <p>We can pass reference of an array to a function like:</p>
<pre><code>void f(int (&a)[5]);
int x[5];
f(x); //okay
int y[6];
f(y); //error - type of y is not `int (&)[5]`.
</code></pre>
<p>Or even better, we can write a function template:</p>
<pre><code>template<size_t N>
void f(int (&a)[N]); //N is size of the array!
int x[5];
f(x); //okay - N becomes 5
int y[6];
f(y); //okay - N becomes 6
</code></pre>
<hr>
<p>Now my question is, how to return reference of an array from a function?</p>
<p>I want to return array of folllowing types from a function:</p>
<pre><code>int a[N];
int a[M][N];
int (*a)[N];
int (*a)[M][N];
</code></pre>
<p>where <code>M</code> and <code>N</code> is known at compile time!</p>
<p>What are general rules for passing and returning compile-time reference of an array to and from a function? How can we pass reference of an array of type <code>int (*a)[M][N]</code> to a function?</p>
<p>EDIT:</p>
<p><strong>Adam</strong> commented : <code>int (*a)[N]</code> is not an array, it's a pointer to an array.</p>
<p>Yes. But one dimension is known at compile time! How can we pass this information which is known at compile time, to a function?</p> | 5,399,014 | 6 | 6 | null | 2011-03-22 23:03:05.373 UTC | 27 | 2016-10-01 23:54:33.323 UTC | 2011-03-22 23:09:53.577 UTC | null | 415,784 | null | 415,784 | null | 1 | 35 | c++|arrays|compile-time | 32,875 | <p>If you want to return a reference to an array from a function, the declaration would look like this:</p>
<pre><code>// an array
int global[10];
// function returning a reference to an array
int (&f())[10] {
return global;
}
</code></pre>
<p>The declaration of a function returning a reference to an array looks the same as the declaration of a variable that is a reference to an array - only that the function name is followed by <code>()</code>, which may contain parameter declarations:</p>
<pre><code>int (&variable)[1][2];
int (&functionA())[1][2];
int (&functionB(int param))[1][2];
</code></pre>
<p>Such declarations can be made much clearer by using a typedef:</p>
<pre><code>typedef int array_t[10];
array_t& f() {
return global;
}
</code></pre>
<p>If you want it to get really confusing, you can declare a function that takes a reference to an array and also returns such a reference:</p>
<pre><code>template<int N, int M>
int (&f(int (&param)[M][N]))[M][N] {
return param;
}
</code></pre>
<p><em>Pointers</em> to arrays work the same, only that they use <code>*</code> instead of <code>&</code>.</p> |
5,091,023 | Choosing between WPF/C# and Qt/C++ | <p>Me and my team are developing an application, which involves a back-end written in C++ and involves use of libraries such as OpenCV, MIL, etc.</p>
<p>Now, we need to develop a GUI to interface with this program, such that the GUI displays the images, and the user can interact with the images and annotate / mark the images, and then run the image processing algorithms written in C++ to display results.</p>
<p>For the GUI, i am stuck choosing between WPF and Qt
I personally find WPF to be easier, and more powerful than Qt
I understand that WPF is not portable to Linux, but i am not worried about this too much...
Also, WPF uses the DirectX technology, which i may have to use to generate some 3-D visualization at a later stage.</p>
<p>Please help me with these points :</p>
<ol>
<li>Can I interface WPF directly with C++ (and not with Visual C# ??)</li>
<li>If (Point 1) is not possible, then consider this :
The code in C++ is going to be big, and involving some libraries too, so can i use C# to call C++ functions
Would the time invested in learning Qt be lesser than making my unmanaged non-OO C++ code work with WPF ?</li>
</ol>
<p>(i have a sinking feeling that I'd have to write too much code for interfacing C++ with WPF, which may equal rewriting half of the actual program itself... :-( )</p> | 5,094,614 | 7 | 6 | null | 2011-02-23 12:39:38.07 UTC | 18 | 2015-09-02 06:45:12.51 UTC | 2015-09-02 06:45:12.51 UTC | null | 630,170 | null | 630,170 | null | 1 | 50 | c#|c++|wpf|qt|user-interface | 54,352 | <p>I've used both Qt with C++ and WPF. I much prefer WPF as a User Interface framework. Qt isn't bad, especially post 4.0. I wouldn't even touch earlier versions of Qt.</p>
<p>As others have said in comments, WPF is better documented, and the online community is larger. If you are looking at styled applications WPF is certainly the way to go. Qt's Declarative language which is new is a good step along that road, but because it's so new it tends to be a bit buggy. WPF has been around longer, and is more mature and richer in features.</p>
<p>However, I think the real issue in your case is the c++ code base that you have.</p>
<p>WPF will require a C++/CLI layer (managed C++) in order to interface properly with your c++ code base. This sounds complicated, and does require a little bit of work, but it is not as crazy as it might sound. And there is tons of documentation about this as well. Personally I would stay away from PInvoke.</p>
<p>Qt is a little easier because it is c++ based, but you will have some translation to do between c++ native types, and Qt types (like QString, QList etc...) that are used internally.</p>
<p>Another thing to consider is what look-and feel you would like for your UI. For example if you were thinking about a nice Ribbon (office 2008, 2010) look, then you will not get this with Qt. Also, there are a ton of third-party WPF controls, but I haven't found very many for Qt. In some cases it is very handy to buy a nice set of controls to supplement the ones Microsoft gives by default.</p>
<p>Over the past couple of years where we don't have a requirement to have a linux UI we have been using WPF, regardless of the code base. We haven't regretted it yet.</p>
<p>However, I will also suggest a third option. Code-jock is a UI framework that is based on MFC I believe. It is c++ and ActiveX based. It has become quite sophisticated. Check it out <a href="http://www.codejock.com/" rel="noreferrer">here</a>.</p>
<p>EDIT:
QML has come a long way since I first looked at it. I haven't had the time to look at it in depth, but from what I hear it offers some very interesting features. It is worth an extra look.</p>
<p>Also, as a few comments have indicated, there are more Office-like controls such as a ribbon, and also some diagram and graphing controls that have added to the Qt toolset. These do make Qt an interesting prospect.</p>
<p>I will stand by something I said earlier though, that as a programmer I find making UIs with WPF a whole lot easier, and I am more pleased with my results than anything that I have ever coded with Qt.</p> |
5,308,200 | Clear text in EditText when entered | <p>I'm trying to set and onclicklistener so that when I click within the edittext element it will clear its current contents. Is there something wrong here? When I compile this code I get a force quit and ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined error.</p>
<pre><code>public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText = (EditText)findViewById(R.id.editText1);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText.setOnClickListener(this);
setContentView(R.layout.main);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText("");
}
}
</code></pre> | 5,308,229 | 18 | 8 | null | 2011-03-15 06:23:00.87 UTC | 17 | 2021-05-23 13:38:59.787 UTC | null | null | null | null | 382,906 | null | 1 | 108 | android|android-edittext | 319,835 | <p>First you need to call <code>setContentView(R.layout.main)</code> then all other initialization.</p>
<p>Please try below Code.</p>
<pre><code>public class Trackfolio extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
editText.getText().clear(); //or you can use editText.setText("");
}
}
</code></pre> |
5,408,406 | Web workers without a separate Javascript file? | <p>As far as I can tell, web workers need to be written in a separate JavaScript file, and called like this: </p>
<pre><code>new Worker('longrunning.js')
</code></pre>
<p>I'm using the closure compiler to combine and minify all my JavaScript source code, and I'd rather not have to have my workers in separate files for distribution. Is there some way to do this?</p>
<pre><code>new Worker(function() {
//Long-running work here
});
</code></pre>
<p>Given that first-class functions are so crucial to JavaScript, why does the standard way to do background work have to load a whole other JavaScript file from the web server?</p> | 6,454,685 | 31 | 5 | null | 2011-03-23 16:20:38.67 UTC | 127 | 2022-09-06 11:33:49.743 UTC | 2019-09-19 05:02:39.407 UTC | null | 7,594,095 | null | 561,519 | null | 1 | 344 | javascript|web-worker | 108,211 | <p><a href="http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers" rel="noreferrer">http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers</a></p>
<blockquote>
<p>What if you want to create your worker script on the fly, or create a self-contained page without having to create separate worker files? With Blob(), you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string</p>
</blockquote>
<br/>
<h2>Full example of BLOB inline worker:</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<script id="worker1" type="javascript/worker">
// This script won't be parsed by JS engines because its type is javascript/worker.
self.onmessage = function(e) {
self.postMessage('msg from worker');
};
// Rest of your worker code goes here.
</script>
<script>
var blob = new Blob([
document.querySelector('#worker1').textContent
], { type: "text/javascript" })
// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
console.log("Received: " + e.data);
}
worker.postMessage("hello"); // Start the worker.
</script></code></pre>
</div>
</div>
</p> |
17,097,141 | How to add/subtract date/time components using a calculated interval? | <p>I'd like to get this to work in Teradata:</p>
<p><strong>Updated SQL for better example</strong></p>
<pre><code>select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + interval Offset hour) GMT
</code></pre>
<p>However, I get an error of <code>Expected something like a string or a Unicode character blah blah</code>. It seems that you have to hardcode the interval like this:</p>
<pre><code>select current_timestamp + interval '4' day
</code></pre>
<p>Yes, I know I hardcoded it in my first example, but that was only to demonstrate a calculated result.</p>
<p>If you must know, I am having to convert all dates and times in a few tables to GMT, but I have to account for daylight savings time. I am in Eastern, so I need to add 4 hours if the date is within the DST timeframe and add 5 hours otherwise.</p>
<p>I know I can just create separate update statements for each period and just change the value from a 4 to a 5 accordingly, but I want my query to be dynamic and smart.</p> | 17,108,026 | 3 | 0 | null | 2013-06-13 21:09:40.063 UTC | null | 2013-06-27 12:23:56.143 UTC | 2013-06-14 11:51:53.763 UTC | null | 701,346 | null | 701,346 | null | 1 | 6 | teradata | 40,989 | <p>Here's the solution:</p>
<pre><code>select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + cast(Offset as interval hour)) GMT
</code></pre>
<p>You have to actually cast the case statement's return value as an interval. I didn't even know interval types existed in Teradata. Thanks to this page for helping me along:</p>
<p><a href="http://www.teradataforum.com/l081007a.htm" rel="noreferrer">http://www.teradataforum.com/l081007a.htm</a></p> |
16,675,657 | Exporting PDF files in Java | <p>I have a table that gets it's data from a SQL DB.
I'm trying to find the easiest way to export that table, as it is, into a PDF file.
Nothing fancy, just a title and the table with it's content.
I've searched around here and also checked into external packages (docmosis and such), but did not make up my mind.
I am fairly new in Java and I'm looking for the easiest way to export a table to a pdf.</p>
<p>Trying to answer possible questions, here's how I populate the table:</p>
<pre><code>try {
result = DBConnection.getTableContent("customers", attributes, where, null, null);
DefaultTableModel model = (DefaultTableModel) searchTable.getModel();
model.setRowCount(0);
for (int i = 0; i < result.size(); i++) {
model.addRow(result.get(i).toArray());
}
}
</code></pre>
<p>Thanks</p> | 16,675,752 | 3 | 3 | null | 2013-05-21 17:07:32.737 UTC | 5 | 2014-02-28 13:31:50.46 UTC | 2013-05-21 17:15:06.94 UTC | null | 1,003,142 | null | 2,399,013 | null | 1 | 7 | java|export-to-pdf | 39,495 | <p>You can use iText PDF Api. It is pretty easy to use. You just have to download the jar, import the class and you are good to go. Check out this <a href="http://www.vogella.com/articles/JavaPDF/article.html#createpdf" rel="noreferrer">tutorial</a> on how to use the classes</p> |
12,375,919 | Powershell non-positional, optional params | <p>I'm trying to create a powershell (2.0) script that will accept arguments that follow this basic pattern:</p>
<pre><code>.\{script name} [options] PATH
</code></pre>
<p>Where options are any number of optional parameters - think along the lines of '-v' for verbose. The PATH argument will simply be whatever argument is passed in last, and is mandatory. One could call the script with no options and only one argument, and that argument would be assumed to be the Path. I'm having trouble setting up a parameters list that contains only optional parameters but is also non-positional.</p>
<p>This quick script demonstrates the problem I am having:</p>
<pre><code>#param test script
Param(
$firstArg,
$secondArg,
[switch]$thirdArg,
[Parameter(ValueFromRemainingArguments = $true)]
$remainingArgs)
write-host "first arg is $firstArg"
write-host "second arg is $secondArg"
write-host "third arg is $thirdArg"
write-host "remaining: $remainingArgs"
</code></pre>
<p>When called like so:</p>
<pre><code>.\param-test.ps1 firstValue secondValue
</code></pre>
<p>The script outputs:</p>
<pre><code>first arg is firstValue
second arg is secondValue
third arg is False
remaining:
</code></pre>
<p>The behavior I am <em>trying</em> to create would have both arguments fall through the optional params and end up in the remainingArgs variable.</p>
<p><a href="https://stackoverflow.com/questions/2795582/how-to-specify-a-non-positional-parameter-in-a-powershell-script/2795683">This question/answer</a> helpfully provided a way to achieve the desired behavior, but it only seems to work if there is at least one mandatory parameter, and only if it comes <em>before</em> all of the other arguments. </p>
<p>I can demonstrate this behavior by making firstArg mandatory and specifying a position of 0:</p>
<pre><code>#param test script
Param(
[Parameter(Mandatory=$true, Position = 0)]
$firstArg,
$secondArg,
[switch]$thirdArg,
[Parameter(ValueFromRemainingArguments = $true)]
$remainingArgs)
write-host "first arg is $firstArg"
write-host "second arg is $secondArg"
write-host "third arg is $thirdArg"
write-host "remaining: $remainingArgs"
</code></pre>
<p>Run with the same input as before:</p>
<pre><code>.\param-test.ps1 firstValue secondValue
</code></pre>
<p>The output is as follows:</p>
<pre><code>first arg is firstValue
second arg is
third arg is False
remaining: secondValue
</code></pre>
<p>The first, mandatory argument is assigned, and everything left falls all the way through.</p>
<p>The question is this: How can I set up a params list such that <em>all</em> of the params are optional, and <em>none</em> of them is positional?</p> | 12,377,616 | 1 | 0 | null | 2012-09-11 18:40:14.697 UTC | 10 | 2014-07-21 16:14:26.28 UTC | 2017-05-23 11:54:36.933 UTC | null | -1 | null | 341,747 | null | 1 | 23 | powershell|scripting|arguments | 37,464 | <p>How about this?</p>
<pre><code>function test
{
param(
[string] $One,
[string] $Two,
[Parameter(Mandatory = $true, Position = 0)]
[string] $Three
)
"One = [$one] Two = [$two] Three = [$three]"
}
</code></pre>
<p><code>One</code> and <code>Two</code> are optional, and may only be specified by name. <code>Three</code> is mandatory, and may be provided without a name.</p>
<p>These work:</p>
<pre><code>test 'foo'
One = [] Two = [] Three = [foo]
test -One 'foo' 'bar'
One = [foo] Two = [] Three = [bar]
test 'foo' -Two 'bar'
One = [] Two = [bar] Three = [foo]
</code></pre>
<p>This will fail:</p>
<pre><code>test 'foo' 'bar'
test : A positional parameter cannot be found that accepts argument 'bar'.
At line:1 char:1
+ test 'foo' 'bar'
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [test], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,test
</code></pre>
<p>This doesn't <em>enforce</em> that your mandatory arg is placed last, or that it's not named. But it <em>allows</em> for the basic usage pattern you want.</p>
<p>It also does not allow for more than one value in <code>$Three</code>. This might be what you want. But, if you want to treat multiple non-named params as being part of <code>$Three</code>, then add the <code>ValueFromRemainingArguments</code> attribute.</p>
<pre><code>function test
{
param(
[string] $One,
[string] $Two,
[Parameter(Mandatory = $true, Position = 0, ValueFromRemainingArguments = $true)]
[string] $Three
)
"One = [$one] Two = [$two] Three = [$three]"
}
</code></pre>
<p>Now things like this work:</p>
<pre><code>test -one 'foo' 'bar' 'baz'
One = [foo] Two = [] Three = [bar baz]
</code></pre>
<p>Or even</p>
<pre><code>test 'foo' -one 'bar' 'baz'
One = [bar] Two = [] Three = [foo baz]
</code></pre> |
12,488,845 | The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file | <pre><code> The Report Viewer Web Control HTTP Handler has not been registered in the application's
web.config file. Add <add verb="*" path="Reserved.ReportViewerWebControl.axd" type =
"Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> to the system.web/httpHandlers section of the web.config file
</code></pre>
<p>This error is coming . I have already mentioned this line in http handler but still getting this error </p>
<pre><code><add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=0000000000000000" validate="false" />
</code></pre>
<p>my html page markup is as follow </p>
<pre><code><%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="btnsubmit" runat="server" OnClick="GenerateReportButton_Click" />
<rsweb:ReportViewer ID="ReportViewer1" runat="server">
</rsweb:ReportViewer>
</asp:Content>
</code></pre>
<p>Web config assemblies section is as follows :</p>
<pre><code><assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</code></pre> | 12,782,652 | 14 | 1 | null | 2012-09-19 05:01:00.45 UTC | 5 | 2022-08-08 20:37:24.183 UTC | 2012-09-19 06:00:11.653 UTC | null | 1,358,004 | null | 779,158 | null | 1 | 23 | asp.net|visual-studio-2008|httphandler|rdlc | 86,494 | <p>I was having the very same problem. What happened was I put the Report loading routine on Page_Load, and didn't wrap it in <code>if (!IsPostBack)</code>. The ReportViewer makes a POST to the page, and that was triggering Page_Load and reloading the report, somehow messing it up. After putting everything inside <code>if (!IsPostBack)</code>, it worked like a charm.</p> |
12,252,378 | Capturing a form submit with jquery and .submit | <p>I'm attempting to use jQuery to capture a submit event and then send the form elements formatted as JSON to a PHP page.
I'm having issues capturing the submit though, I started with a <code>.click()</code> event but moved to the <code>.submit()</code> one instead.</p>
<p>I now have the following trimmed down code.</p>
<p>HTML</p>
<pre><code><form method="POST" id="login_form">
<label>Username:</label>
<input type="text" name="username" id="username"/>
<label>Password:</label>
<input type="password" name="password" id="password"/>
<input type="submit" value="Submit" name="submit" class="submit" id="submit" />
</form>
</code></pre>
<p>Javascript</p>
<pre><code>$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
});
</code></pre> | 12,252,576 | 5 | 8 | null | 2012-09-03 18:08:08.62 UTC | 14 | 2019-02-23 15:43:21.753 UTC | 2016-04-13 02:12:56.967 UTC | null | 2,311,366 | null | 618,579 | null | 1 | 63 | javascript|html|jquery | 173,441 | <p>Wrap the code in document ready and prevent the default submit action:</p>
<pre><code>$(function() { //shorthand document.ready function
$('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var data = $("#login_form :input").serializeArray();
console.log(data); //use the console for debugging, F12 in Chrome, not alerts
});
});
</code></pre> |
19,184,052 | Center align with table-cell | <p>I'm trying to use the table-cell way to center a div vertically and horizontally.</p>
<p>It works when I use the following code:</p>
<pre class="lang-css prettyprint-override"><code>div {
display: table;
}
.logo {
display: table-cell;
position: absolute;
vertical-align: middle;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
</code></pre>
<p>But I'd rather wrap <code>.logo</code> in another div called <code>.center</code> like here <a href="http://jsfiddle.net/cxvDL/" rel="noreferrer">JSFiddle</a>, but for some reason, although it works in JSFiddle, it isn't working for me on my site.</p> | 19,184,468 | 2 | 6 | null | 2013-10-04 14:39:29.957 UTC | 13 | 2021-03-06 22:34:14.817 UTC | 2021-03-06 22:34:14.817 UTC | null | 8,816,585 | null | 1,694,704 | null | 1 | 51 | html|css | 174,177 | <p>Here is a good starting point.</p>
<p>HTML:</p>
<pre><code><div class="containing-table">
<div class="centre-align">
<div class="content"></div>
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre class="lang-css prettyprint-override"><code>.containing-table {
display: table;
width: 100%;
height: 400px; /* for demo only */
border: 1px dotted blue;
}
.centre-align {
padding: 10px;
border: 1px dashed gray;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
vertical-align: top; /* Removes the extra white space below the baseline */
}
</code></pre>
<p>See demo at: <a href="http://jsfiddle.net/audetwebdesign/jSVyY/" rel="noreferrer">http://jsfiddle.net/audetwebdesign/jSVyY/</a></p>
<p><code>.containing-table</code> establishes the width and height context for <code>.centre-align</code> (the table-cell).</p>
<p>You can apply <code>text-align</code> and <code>vertical-align</code> to alter <code>.centre-align</code> as needed.</p>
<p>Note that <code>.content</code> needs to use <code>display: inline-block</code> if it is to be centered horizontally using the text-align property.</p> |
3,440,266 | How to add audio to video file on iphone SDK | <p>I have a video file and an audio file. Is it possible to merge it to one video with with sound file. I think AVMutableComposition should help me, but I still dont understand how. any advices?</p> | 3,456,565 | 3 | 0 | null | 2010-08-09 13:05:21.087 UTC | 25 | 2020-11-11 12:31:24.913 UTC | null | null | null | null | 390,174 | null | 1 | 12 | iphone|audio|video-encoding | 12,680 | <p>Thanks Daniel. I figured it out, its easy.</p>
<pre><code>AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioUrl options:nil];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoUrl options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration)
ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition
presetName:AVAssetExportPresetPassthrough];
NSString* videoName = @"export.mov";
NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
NSURL *exportUrl = [NSURL fileURLWithPath:exportPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
{
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
_assetExport.outputFileType = @"com.apple.quicktime-movie";
DLog(@"file type %@",_assetExport.outputFileType);
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void ) {
// your completion code here
}
}
];
</code></pre> |
3,480,473 | how to add object to NSMutableArray | <p>I am trying to read an input file (if it exists) and then want to add a string to that input. My code looks as follows.</p>
<pre><code>NSMutableArray *listData = [[NSMutableArray alloc] initWithContentsOfFile:*filepath*];
// listData = null if the input file does not exist.
NSString *jobName = [NSString stringWithFormat:@"My New Job"];
[listData addObject:jobName];
</code></pre>
<p>if the input exists then after <strong>addObject:jobName</strong>, the <strong>listData</strong> is updated but if the input file does not exist the <strong>listData</strong> still gives null after <strong>addObject:jobName</strong>. My input file (if exists) looks something like.</p>
<pre><code><array>
<string>My Job 1</string>
<string>My Job 2</string>
<string>My Job 3</string>
</array>
</code></pre>
<p>I want to add the string in the existing array of strings or want to create a new array of string jobName if it is not already there. Can somebody help me out. Which method I should use to create a new array of string when the input file does not exist.</p> | 3,480,488 | 3 | 0 | null | 2010-08-13 20:30:50.84 UTC | 3 | 2016-03-01 19:57:37.16 UTC | 2010-08-13 20:33:19.877 UTC | null | 168,225 | null | 419,968 | null | 1 | 16 | objective-c|iphone | 50,476 | <p>One of some possibilities:</p>
<pre><code>if (!listData) listData = [[NSMutableArray alloc] init];
[listData addObject:jobName];
</code></pre> |
3,619,824 | what's the relationship between Selenium RC and WebDriver? | <p>I can see that since selenium 2.0, WebDriver and Selenium RC are packaged together for download. Now I primarily use WebDriver, but can I bring in Selenium RC in my testing scripts from now and then? Is there anything that Selenium RC is capable of but WebDriver is not, or vice versa? </p> | 3,620,068 | 3 | 1 | null | 2010-09-01 15:44:41.18 UTC | 12 | 2015-08-06 04:31:20.807 UTC | 2015-08-06 04:31:20.807 UTC | null | 617,450 | null | 179,385 | null | 1 | 33 | selenium|selenium-rc|webdriver | 26,170 | <p>You should probably start your research here (though you may have already gone over this): <a href="http://seleniumhq.org/docs/03_webdriver.html" rel="noreferrer">http://seleniumhq.org/docs/03_webdriver.html</a></p>
<p>I'll assume you're contrasting Selenium-RC to WebDriver, Selenium-IDE really isn't in the same ballpark.</p>
<p>Selenium uses JavaScript to automate web pages. This lets it interact very tightly with web content, and was one of the first automation tools to support Ajax and other heavily dynamic pages. However, this also means Selenium runs inside the JavaScript sandbox. This means you need to run the Selenium-RC server to get around the same-origin policy, which can sometimes cause issues with browser setup.</p>
<p>WebDriver on the other hand uses native automation from each language. While this means it takes longer to support new browsers/languages, it does offer a much closer 'feel' to the browser. If you're happy with WebDriver, stick with it, it's the future. There are limitations and bugs right now, but if they're not stopping you, go for it.</p>
<p><strong>Selenium Benefits over WebDriver</strong></p>
<ul>
<li>Supports many browsers and many languages, WebDriver needs native implementations for each new language/browser combo.</li>
<li>Very mature and complete API</li>
<li>Currently (Sept 2010) supports JavaScript alerts and confirms better</li>
</ul>
<p><strong>Benefits of WebDriver Compared to Selenium</strong></p>
<ul>
<li>Native automation faster and a little less prone to error and browser configuration</li>
<li>Does not require Selenium-RC Server to be running</li>
<li>Access to headless HTMLUnit can allow tests to run very fast</li>
<li>Great API</li>
</ul> |
3,479,330 | How is malloc() implemented internally? | <p>Can anyone explain how <code>malloc()</code> works internally?</p>
<p>I have sometimes done <code>strace program</code> and I see a lot of <code>sbrk</code> system calls, doing <code>man sbrk</code> talks about it being used in <code>malloc()</code> but not much more.</p> | 3,479,496 | 3 | 2 | null | 2010-08-13 17:35:29.86 UTC | 96 | 2020-09-21 08:45:44.483 UTC | 2013-08-19 01:36:29.793 UTC | null | 565,635 | null | 257,942 | null | 1 | 126 | c|memory|malloc|system-calls|sbrk | 154,150 | <p>The <code>sbrk</code>system call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no <code>malloc</code> really gives memory segments back to the kernel with that method). Aside from that, there's also <code>mmap</code> which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, <code>mmap</code> is how you do it).</p>
<p>So you have two methods of getting more memory from the kernel: <code>sbrk</code> and <code>mmap</code>. There are various strategies on how to organize the memory that you've got from the kernel.</p>
<p>One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a <code>malloc</code> implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask <code>malloc</code> to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area <code>malloc</code> could use <code>mmap</code> to allocate directly with the kernel. If the bucket of a certain size is empty <code>malloc</code> could use <code>sbrk</code> to get more space for a new bucket.</p>
<p>There are various <code>malloc</code> designs and there is propably no one true way of implementing <code>malloc</code> as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via <code>sbrk</code>/<code>mmap</code> that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to <code>malloc</code> again somehow. You don't just hand out memory without reusing it.</p>
<p>If you're interested, the OpenSER/Kamailio SIP proxy has two <code>malloc</code> implementations (they need their own because they make heavy use of shared memory and the system <code>malloc</code> doesn't support shared memory). See: <a href="https://github.com/OpenSIPS/opensips/tree/master/mem" rel="noreferrer">https://github.com/OpenSIPS/opensips/tree/master/mem</a></p>
<p>Then you could also have a look at the <a href="http://sourceware.org/git/?p=glibc.git;a=tree;f=malloc" rel="noreferrer">GNU libc <code>malloc</code> implementation</a>, but that one is very complicated, IIRC.</p> |
22,593,286 | Detect/measure scroll speed | <p>I'm trying to think of a way to <strong><em>measure the velocity</em></strong> of a scroll event, that would produce some sort of a number which will represent the speed (distance from scroll point A to point B relative to the time it took). </p>
<p><hr>
I would welcome any suggestions in the form of pseudo code...
I was trying to find information on this problem, online but could not find anything. very weird since it's 2014, how could it be that there is nothing on google for this...weird!</p> | 22,599,173 | 3 | 22 | null | 2014-03-23 16:00:39.96 UTC | 14 | 2022-06-08 09:09:07.22 UTC | null | null | null | null | 104,380 | null | 1 | 27 | javascript|events|scroll | 34,066 | <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>var checkScrollSpeed = (function(settings){
settings = settings || {};
var lastPos, newPos, timer, delta,
delay = settings.delay || 50; // in "ms" (higher means lower fidelity )
function clear() {
lastPos = null;
delta = 0;
}
clear();
return function(){
newPos = window.scrollY;
if ( lastPos != null ){ // && newPos < maxScroll
delta = newPos - lastPos;
}
lastPos = newPos;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
// listen to "scroll" event
window.onscroll = function(){
console.clear()
console.log( checkScrollSpeed() );
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{ height:300vh }</code></pre>
</div>
</div>
</p>
<p>Demo page:
<a href="http://codepen.io/vsync/pen/taAGd/" rel="nofollow noreferrer">http://codepen.io/vsync/pen/taAGd/</a></p>
<p>Simplified demo:
<a href="http://jsbin.com/mapafadako/edit?js,console,output" rel="nofollow noreferrer">http://jsbin.com/mapafadako/edit?js,console,output</a></p>
<hr>
For real fun, give a real website these rules, then copy the JS and run it |
11,161,248 | Setting JAVA_HOME | <p>I'm having a problem when running programs that use Java from the command line. I get back a message saying Java.exe could not be found.</p>
<p><img src="https://i.stack.imgur.com/7R0XN.jpg" alt="enter image description here"></p>
<p>I've followed the <a href="https://confluence.atlassian.com/display/CONF26/Set+JAVA_HOME+variable+in+Windows" rel="nofollow noreferrer">instructions found in several places for setting JAVA_HOME in Windows 7</a>. </p>
<p><img src="https://i.stack.imgur.com/FVAGr.jpg" alt="enter image description here"></p>
<p>As can be seen in the image I'm pointing to the JDK folder as instructed, I've also tried several variations including linking to the bin folder(where java.exe is located).</p>
<p>What am I doing wrong, and how can I debug this.</p>
<p><em>EDIT:</em></p>
<p>Typing Set in Command Prompt outputs</p>
<p><img src="https://i.stack.imgur.com/jRiRU.jpg" alt="enter image description here"></p> | 11,193,584 | 6 | 1 | null | 2012-06-22 17:28:09.973 UTC | 4 | 2021-08-18 09:30:12.92 UTC | 2021-08-18 09:30:12.92 UTC | null | 1,862,590 | null | 773,263 | null | 1 | 5 | java|windows|command-line|environment-variables | 88,173 | <p>As many have mentioned I had to add...</p>
<pre><code>C:\Program Files\Java\jdk_version\bin
</code></pre>
<p>...to the path variable.</p>
<p>However what was not mentioned and was stopping this from working was that I had to make sure
java\bin directory is in the path statement before the windows\system32 directory, otherwise this will not work.</p>
<p>I was able to find the information <a href="https://stackoverflow.com/a/5734845/773263">here</a>.</p> |
10,921,791 | melt / reshape in excel using VBA? | <p>I'm currently adjusting to a new job where most of the work I share with colleagues is via MS Excel. I am using pivot tables frequently, and therefore need "stacked" data, precisely the output of the <code>melt()</code> function in the <code>reshape</code> (reshape2) package in R that I've come to rely on for this.</p>
<p><strong>Could anyone get me started on a VBA macro to accomplish this, or does one exist already?</strong></p>
<p>The outline of the macro would be:</p>
<ol>
<li>Select a range of cells in an Excel workbook. </li>
<li>Start "melt" macro.</li>
<li>Macro would create a prompt, "Enter number of id columns", where you would enter the number preceding columns of identifying information. (for the example R code below it's 4).</li>
<li>Create a new worksheet in the excel file titled "melt"
that would stack the data, and create a new column titled "variable"
equal to the data column headers from the original selection.</li>
</ol>
<p>In other words, the output would look exactly the same as the output of simply executing these two lines in R:</p>
<pre><code>require(reshape)
melt(your.unstacked.dataframe, id.vars = 1:4)
</code></pre>
<p>Here's an example:</p>
<pre><code># unstacked data
> df1
Year Month Country Sport No_wins No_losses High_score Total_games
2 2010 5 USA Soccer 4 3 5 9
3 2010 6 USA Soccer 5 3 4 8
4 2010 5 CAN Soccer 2 9 7 11
5 2010 6 CAN Soccer 4 8 4 13
6 2009 5 USA Soccer 8 1 4 9
7 2009 6 USA Soccer 0 0 3 2
8 2009 5 CAN Soccer 2 0 6 3
9 2009 6 CAN Soccer 3 0 8 3
# stacking the data
> require(reshape)
> melt(df1, id.vars=1:4)
Year Month Country Sport variable value
1 2010 5 USA Soccer No_wins 4
2 2010 6 USA Soccer No_wins 5
3 2010 5 CAN Soccer No_wins 2
4 2010 6 CAN Soccer No_wins 4
5 2009 5 USA Soccer No_wins 8
6 2009 6 USA Soccer No_wins 0
7 2009 5 CAN Soccer No_wins 2
8 2009 6 CAN Soccer No_wins 3
9 2010 5 USA Soccer No_losses 3
10 2010 6 USA Soccer No_losses 3
11 2010 5 CAN Soccer No_losses 9
12 2010 6 CAN Soccer No_losses 8
13 2009 5 USA Soccer No_losses 1
14 2009 6 USA Soccer No_losses 0
15 2009 5 CAN Soccer No_losses 0
16 2009 6 CAN Soccer No_losses 0
17 2010 5 USA Soccer High_score 5
18 2010 6 USA Soccer High_score 4
19 2010 5 CAN Soccer High_score 7
20 2010 6 CAN Soccer High_score 4
21 2009 5 USA Soccer High_score 4
22 2009 6 USA Soccer High_score 3
23 2009 5 CAN Soccer High_score 6
24 2009 6 CAN Soccer High_score 8
25 2010 5 USA Soccer Total_games 9
26 2010 6 USA Soccer Total_games 8
27 2010 5 CAN Soccer Total_games 11
28 2010 6 CAN Soccer Total_games 13
29 2009 5 USA Soccer Total_games 9
30 2009 6 USA Soccer Total_games 2
31 2009 5 CAN Soccer Total_games 3
32 2009 6 CAN Soccer Total_games 3
</code></pre> | 10,922,351 | 4 | 3 | null | 2012-06-06 20:32:26.453 UTC | 15 | 2019-05-31 04:41:49.46 UTC | 2014-07-31 18:21:56.933 UTC | null | 415,864 | null | 594,795 | null | 1 | 18 | r|vba|excel|pivot-table|reshape2 | 14,071 | <p>I've got two posts, with usable code and downloadable workbook, on doing this in Excel/VBA on my blog:</p>
<p><a href="http://yoursumbuddy.com/data-normalizer" rel="nofollow noreferrer">http://yoursumbuddy.com/data-normalizer</a></p>
<p><a href="http://yoursumbuddy.com/data-normalizer-the-sql/" rel="nofollow noreferrer">http://yoursumbuddy.com/data-normalizer-the-sql/</a></p>
<p>Here's the code:</p>
<pre class="lang-vb prettyprint-override"><code>'Arguments
'List: The range to be normalized.
'RepeatingColsCount: The number of columns, starting with the leftmost,
' whose headings remain the same.
'NormalizedColHeader: The column header for the rolled-up category.
'DataColHeader: The column header for the normalized data.
'NewWorkbook: Put the sheet with the data in a new workbook?
'
'NOTE: The data must be in a contiguous range and the
'columns that will be repeated must be to the left,
'with the columns to be normalized to the right.
Sub NormalizeList(List As Excel.Range, RepeatingColsCount As Long, _
NormalizedColHeader As String, DataColHeader As String, _
Optional NewWorkbook As Boolean = False)
Dim FirstNormalizingCol As Long, NormalizingColsCount As Long
Dim ColsToRepeat As Excel.Range, ColsToNormalize As Excel.Range
Dim NormalizedRowsCount As Long
Dim RepeatingList() As String
Dim NormalizedList() As Variant
Dim ListIndex As Long, i As Long, j As Long
Dim wbSource As Excel.Workbook, wbTarget As Excel.Workbook
Dim wsTarget As Excel.Worksheet
With List
'If the normalized list won't fit, you must quit.
If .Rows.Count * (.Columns.Count - RepeatingColsCount) > .Parent.Rows.Count Then
MsgBox "The normalized list will be too many rows.", _
vbExclamation + vbOKOnly, "Sorry"
Exit Sub
End If
'You have the range to be normalized and the count of leftmost rows to be repeated.
'This section uses those arguments to set the two ranges to parse
'and the two corresponding arrays to fill
FirstNormalizingCol = RepeatingColsCount + 1
NormalizingColsCount = .Columns.Count - RepeatingColsCount
Set ColsToRepeat = .Cells(1).Resize(.Rows.Count, RepeatingColsCount)
Set ColsToNormalize = .Cells(1, FirstNormalizingCol).Resize(.Rows.Count, NormalizingColsCount)
NormalizedRowsCount = ColsToNormalize.Columns.Count * .Rows.Count
ReDim RepeatingList(1 To NormalizedRowsCount, 1 To RepeatingColsCount)
ReDim NormalizedList(1 To NormalizedRowsCount, 1 To 2)
End With
'Fill in every i elements of the repeating array with the repeating row labels.
For i = 1 To NormalizedRowsCount Step NormalizingColsCount
ListIndex = ListIndex + 1
For j = 1 To RepeatingColsCount
RepeatingList(i, j) = List.Cells(ListIndex, j).Value2
Next j
Next i
'We stepped over most rows above, so fill in other repeating array elements.
For i = 1 To NormalizedRowsCount
For j = 1 To RepeatingColsCount
If RepeatingList(i, j) = "" Then
RepeatingList(i, j) = RepeatingList(i - 1, j)
End If
Next j
Next i
'Fill in each element of the first dimension of the normalizing array
'with the former column header (which is now another row label) and the data.
With ColsToNormalize
For i = 1 To .Rows.Count
For j = 1 To .Columns.Count
NormalizedList(((i - 1) * NormalizingColsCount) + j, 1) = .Cells(1, j)
NormalizedList(((i - 1) * NormalizingColsCount) + j, 2) = .Cells(i, j)
Next j
Next i
End With
'Put the normal data in the same workbook, or a new one.
If NewWorkbook Then
Set wbTarget = Workbooks.Add
Set wsTarget = wbTarget.Worksheets(1)
Else
Set wbSource = List.Parent.Parent
With wbSource.Worksheets
Set wsTarget = .Add(after:=.Item(.Count))
End With
End If
With wsTarget
'Put the data from the two arrays in the new worksheet.
.Range("A1").Resize(NormalizedRowsCount, RepeatingColsCount) = RepeatingList
.Cells(1, FirstNormalizingCol).Resize(NormalizedRowsCount, 2) = NormalizedList
'At this point there will be repeated header rows, so delete all but one.
.Range("1:" & NormalizingColsCount - 1).EntireRow.Delete
'Add the headers for the new label column and the data column.
.Cells(1, FirstNormalizingCol).Value = NormalizedColHeader
.Cells(1, FirstNormalizingCol + 1).Value = DataColHeader
End With
End Sub
</code></pre>
<p>You’d call it like this:</p>
<pre class="lang-vb prettyprint-override"><code>Sub TestIt()
NormalizeList ActiveSheet.UsedRange, 4, "Variable", "Value", False
End Sub
</code></pre> |
11,141,831 | How do I output a drupal image field? | <p>It is quite possible that I'm just looking for help finding the name of a function that already exists within drupal (7) but sometimes the documentation is a bit difficult to navigate. Hopefully someone can help me.</p>
<p>I have a node that has a custom field.</p>
<p>I am working within a template <code>field--mycustomcontenttype.tpl.php</code> and so am trying to find the name of the PHP function that outputs and image field with image styles.</p>
<p><code>mycustomcontenttype</code> is a NODE with the following additional field:</p>
<pre><code>[field_image] => Array
(
[und] => Array
(
[0] => Array
(
[fid] => 51
[alt] => ImageAltText
[title] =>
[width] => 150
[height] => 150
[uid] => 29
[filename] => myimagename.jpg
[uri] => public://myimagename.jpg
[filemime] => image/jpeg
[filesize] => 8812
[status] => 1
[timestamp] => 1339445372
[uuid] => a088ea8f-ddf9-47d1-b013-19c8f8cada07
[metatags] => Array
(
)
)
</code></pre>
<p>So I <em>could</em> display the image using an (ugly) hand rolled functions that takes the value found in <code>$item['#options']['entity']->field_image</code> and does the substitution of <code>public://</code> for the actual server path, and then it's also possible that I'm going to want to load the image with the correct drupal image style (thumbnail, custom-style, etc...)</p>
<p>Sadly, I just have no idea what the name of the function that works something like: <code>unknown_function_name_drupal_image_print($item['#options']['entity']->field_image, 'thumnail');</code> is.</p>
<p>Is there anyone who can help me find this?</p> | 11,141,911 | 10 | 0 | null | 2012-06-21 15:44:53.093 UTC | 11 | 2017-04-19 07:06:08.013 UTC | 2013-12-07 01:44:25.483 UTC | null | 759,866 | null | 398,055 | null | 1 | 21 | drupal|drupal-7|drupal-theming|drupal-themes | 49,856 | <p>You are looking for <a href="https://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_url/7"><code>image_style_url(style_name, image_url);</code></a></p>
<p>For example:</p>
<pre><code><?='<img src="'.image_style_url('fullwidth', $node->field_page_image['und'][0]['filename']).'" />'?>
</code></pre>
<p><strong>EDIT</strong></p>
<p>As pointed out you can also set the image style in the Manage Display page for the content type and then output using render.</p>
<pre><code><?php print render($content['field_image']); ?>
</code></pre> |
11,239,495 | Checking if file is completely written | <p>Currently I'm working on the project that does processing files from source directory in one of it's routines. There's a Java process that's looking for specified directory and tries to read and process files if they exist. Files are quit large and updates by other thirdparty process. The question is how can I check if the file is completely written? I'm trying to use <code>file.length()</code> but looks like even if writing process hasn't been completed it returns actual size. I have a feeling that solution should be platform dependent. Any help would be appreciated.</p>
<p>UPDATE:
This question is not really different from the duplicate but it has an answer with working code snippet that is highly rated.</p> | 11,239,561 | 6 | 4 | null | 2012-06-28 06:57:54.79 UTC | 10 | 2020-05-03 14:28:32.867 UTC | 2015-03-13 11:41:50.663 UTC | null | 538,514 | null | 538,514 | null | 1 | 26 | java|file|io|filesystems | 50,660 | <p>Does the producer process close the file when its finished writing? If so, trying to open the file in the consumer process with an exclusive lock will fail if the producer process is still producing.</p> |
11,264,188 | How can I detect onKeyUp in AngularJS? | <p>How can I detect onKeyUp in AngularJS?</p>
<p>I'm looking for an 'ngOnkeyup' directive, similar to ngChange, but I can't find anything suitable.</p>
<p>If there isn't such a directive, is there a clean way to call into the controller from a browser-native onkeyup event? </p> | 11,267,263 | 8 | 0 | null | 2012-06-29 15:02:22.683 UTC | 14 | 2018-08-10 23:14:22.8 UTC | null | null | null | null | 129,805 | null | 1 | 48 | angularjs | 73,406 | <p><strong>EDIT: see second answer below from maklemenz which refers to the new built-in ng-keyup directive</strong> </p>
<p>You could use the <a href="http://angular-ui.github.com/">angular-ui library</a>: </p>
<p>With angular-ui, you can just do</p>
<pre><code><input ui-event="{keyup: 'myFn($event)'}"
</code></pre>
<p>If you don't want to use another library, the most efficient and simple way to do this is:</p>
<p>JS</p>
<pre><code>myApp.directive('onKeyup', function() {
return function(scope, elm, attrs) {
elm.bind("keyup", function() {
scope.$apply(attrs.onKeyup);
});
};
});
</code></pre>
<p>HTML:</p>
<pre><code><input on-keyup="count = count + 1">
</code></pre>
<hr>
<p><strong>Edit</strong>: If you wanted to detect which key was pressed, you have two basic options really. You could add an attribute to the directive to handle the allowed keys within the directive, or you could pass the key pressed to your controller. I would generally recommend the directive handles the key method.</p>
<p>Here's an example of both ways: <a href="http://jsfiddle.net/bYUa3/2">http://jsfiddle.net/bYUa3/2</a></p> |
10,978,869 | Safely create a file if and only if it does not exist with Python | <p>I wish to write to a file based on whether that file already exists or not, only writing if it doesn't already exist (in practice, I wish to keep trying files until I find one that doesn't exist).</p>
<p>The following code shows a way in which a potentially attacker could insert a symlink, as suggested in <a href="https://stackoverflow.com/a/85237/709852">this post</a> in between a test for the file and the file being written. If the code is run with high enough permissions, this could overwrite an arbitrary file.</p>
<p>Is there a way to solve this problem?</p>
<pre><code>import os
import errno
file_to_be_attacked = 'important_file'
with open(file_to_be_attacked, 'w') as f:
f.write('Some important content!\n')
test_file = 'testfile'
try:
with open(test_file) as f: pass
except IOError, e:
# Symlink created here
os.symlink(file_to_be_attacked, test_file)
if e.errno != errno.ENOENT:
raise
else:
with open(test_file, 'w') as f:
f.write('Hello, kthxbye!\n')
</code></pre> | 10,979,569 | 3 | 4 | null | 2012-06-11 11:03:11.377 UTC | 20 | 2021-03-25 23:02:11.493 UTC | 2021-03-25 22:59:34.373 UTC | null | 63,550 | null | 709,852 | null | 1 | 102 | python | 68,203 | <p><strong>Edit</strong>: See also <a href="https://stackoverflow.com/a/18474773/220155">Dave Jones' answer</a>: from Python 3.3, you can use the <code>x</code> flag to <code>open()</code> to provide this function.</p>
<p><strong>Original answer below</strong></p>
<p>Yes, but not using Python's standard <code>open()</code> call. You'll need to use <a href="http://docs.python.org/library/os.html#os.open" rel="noreferrer"><code>os.open()</code></a> instead, which allows you to specify flags to the underlying C code.</p>
<p>In particular, you want to use <code>O_CREAT | O_EXCL</code>. From the man page for <code>open(2)</code> under <code>O_EXCL</code> on my Unix system:</p>
<blockquote>
<p>Ensure that this call creates the file: if this flag is specified in conjunction with <code>O_CREAT</code>, and pathname already exists, then <code>open()</code> will fail. The behavior of <code>O_EXCL</code> is undefined if <code>O_CREAT</code> is not specified.</p>
<p>When these two flags are specified, symbolic links are not followed: if pathname is a symbolic link, then <code>open()</code> fails regardless of where the symbolic link points to.</p>
<p><code>O_EXCL</code> is only supported on NFS when using NFSv3 or later on kernel 2.6 or later. In environments where NFS <code>O_EXCL</code> support is not provided, programs that rely on it for performing locking tasks will contain a race condition.</p>
</blockquote>
<p>So it's not perfect, but AFAIK it's the closest you can get to avoiding this race condition.</p>
<p>Edit: the other rules of using <code>os.open()</code> instead of <code>open()</code> still apply. In particular, if you want use the returned file descriptor for reading or writing, you'll need one of the <code>O_RDONLY</code>, <code>O_WRONLY</code> or <code>O_RDWR</code> flags as well.</p>
<p>All the <code>O_*</code> flags are in Python's <code>os</code> module, so you'll need to <code>import os</code> and use <code>os.O_CREAT</code> etc.</p>
<h3>Example:</h3>
<pre><code>import os
import errno
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
try:
file_handle = os.open('filename', flags)
except OSError as e:
if e.errno == errno.EEXIST: # Failed as the file already exists.
pass
else: # Something unexpected went wrong so reraise the exception.
raise
else: # No exception, so the file must have been created successfully.
with os.fdopen(file_handle, 'w') as file_obj:
# Using `os.fdopen` converts the handle to an object that acts like a
# regular Python file object, and the `with` context manager means the
# file will be automatically closed when we're done with it.
file_obj.write("Look, ma, I'm writing to a new file!")
</code></pre> |
12,715,195 | How to forward a subdomain to a new port on the same IP address using Apache? | <p>I have a NAS/Server running at home 24/7 and run many different services on it. I have got a domain name pointing to it now, and was wondering if it would be possible to create sub-domains that point to different ports for different services. For example:</p>
<ul>
<li><a href="http://subsonic.mydomain.com">http://subsonic.mydomain.com</a> --> XXX.XXX.XXX.XXX:4040</li>
<li><a href="http://minecraft.mydomain.com">http://minecraft.mydomain.com</a> --> XXX.XXX.XXX.XXX:25565</li>
<li><a href="http://files.mydomain.com">http://files.mydomain.com</a> --> XXX.XXX.XXX.XXX:4082</li>
</ul>
<p>I have a single D-LINK router that currently port forwards all these ports to my NAS/Server whose IP is 192.168.0.104.</p>
<p>EDIT: The server is running Ubuntu 12.04.</p>
<p>What service or proxy do I need to run that can recognize the sub domain and route the traffic accordingly? Or could I use apache virtual hosts to handle this, because these subdomains will come in on port 80, which apache is listening to? Or does virtual hosts not work like this?</p>
<p>Any information, ideas, or tips would be helpful/useful.</p> | 12,732,965 | 1 | 1 | null | 2012-10-03 19:09:48.817 UTC | 12 | 2018-02-12 00:59:11.297 UTC | 2018-02-12 00:59:11.297 UTC | null | 188,963 | null | 1,094,175 | null | 1 | 16 | apache|dns|web|subdomain|portforwarding | 23,363 | <p>There are two ways to do this. You could use the VirtualHost section of your <code>httpd.conf</code> or you could do it in your <code>.htaccess</code>. (assuming that the subdomains resolve to the same IP as your webserver)</p>
<p>In <code>httpd.conf</code>:</p>
<pre><code><VirtualHost *:80>
ServerName subsonic.mydomain.com
redirect / http://mydomain.com:4040/
</VirtualHost>
</code></pre>
<p>In <code>.htaccess</code>:</p>
<pre><code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^subsonic\.mydomain\.com$ [NC]
RewriteRule ^(.*)$ http://mydomain.com:4040/$1 [R=301]
</code></pre>
<p>Documentation:<br />
- <a href="http://httpd.apache.org/docs/current/vhosts/name-based.html">Guide to creating name-based virtual hosts</a><br />
- <a href="http://httpd.apache.org/docs/current/mod/core.html">Core</a>, including <a href="http://httpd.apache.org/docs/current/mod/core.html#virtualhost">VirtualHost</a> and <a href="http://httpd.apache.org/docs/current/mod/core.html#namevirtualhost">NameVirtualHost</a><br />
- <a href="http://httpd.apache.org/docs/current/mod/mod_alias.html#redirect">Redirect</a><br />
- <a href="http://www.workingwith.me.uk/articles/scripting/mod_rewrite">mod_rewrite guide</a></p> |
13,129,287 | Is Regex instance thread safe for matches in C# | <p>I have this regex which I am using in a <code>Parallel.ForEach<string></code>. Is it safe?</p>
<pre><code>Regex reg = new Regex(SomeRegexStringWith2Groups);
Parallel.ForEach<string>(MyStrings.ToArray(), (str) =>
{
foreach (Match match in reg.Matches(str)) //is this safe?
lock (dict) if (!dict.ContainsKey(match.Groups[1].Value))
dict.Add(match.Groups[1].Value, match.Groups[2].Value);
});
</code></pre> | 13,129,370 | 1 | 4 | null | 2012-10-29 20:39:14.04 UTC | 2 | 2012-10-29 22:45:58.443 UTC | 2012-10-29 22:45:58.443 UTC | null | 258,482 | null | 258,482 | null | 1 | 39 | c#|regex|.net-4.0 | 8,047 | <p><code>Regex</code> objects are read-only, and therefore are thread safe. It's their returns, the <code>Match</code> objects that could potentially cause problems. <a href="http://msdn.microsoft.com/en-us/library/6h453d2h.aspx" rel="noreferrer">MSDN confirms this</a>:</p>
<blockquote>
<p>The Regex class itself is thread safe and immutable (read-only). That is, Regex objects can be created on any thread and shared between threads; <em>matching methods can be called from any thread and never alter any global state.</em></p>
<p>However, <em>result objects (Match and MatchCollection) returned by Regex should be used on a single thread ..</em></p>
</blockquote>
<p>I'd be concerned about how your Match collection is being generated in a way that might be concurrent, which could cause the collection to act kinda weird. Some Match implementations use delayed evaluation, which could cause some crazy behavior in that <code>foreach</code> loop. I would probably collect all the Matches and then evaluate them later, both to be safe and to get consistent performance.</p> |
13,100,611 | Replace url from youtube to embed code - Error: Permission denied to access property 'toString' | <p>I have this code and this error in FireBug:</p>
<blockquote>
<p>Error: Permission denied to access property 'toString'</p>
</blockquote>
<p>How can i fix this error?</p>
<p>HTML:</p>
<pre><code><div class="yturl">http://www.youtube.com/watch?v=UNMLEZrukRU</div>
</code></pre>
<p>JS:</p>
<pre><code>$("div.yturl").each(function(){
var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var youtubeurl = $(this).text();
var regexyoutubeurl = youtubeurl.match(regex);
if (regexyoutubeurl)
{
$(this).html("<iframe width=\"390\" height=\"315\" src=\"http://www.youtube.com/embed/"+regexyoutubeurl[2]+"\" frameborder=\"0\" allowfullscreen></iframe>");
}
});
</code></pre>
<p><strong>DEMO:</strong> <a href="http://jsfiddle.net/9e48p/" rel="noreferrer">http://jsfiddle.net/9e48p/</a></p> | 13,101,119 | 5 | 5 | null | 2012-10-27 13:30:45.577 UTC | 15 | 2015-02-18 13:49:44.693 UTC | 2013-04-17 08:56:48.823 UTC | null | 542,251 | null | 1,180,987 | null | 1 | 43 | javascript|jquery|youtube | 63,560 | <p>The error can either be fixed by Adobe's Flash Player team, or by the Google engineers - you should just ignore it for now. It's connected to Flash Player security settings and the SWF file embedded into the Youtube page. The problem has been <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21370430" rel="noreferrer">reported in the past by IBM</a>, and there is a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=434522" rel="noreferrer">Mozilla Bugzilla entry</a> as well.</p>
<p>When I deactivate Flash Player in Firefox 16.0.2, the error message disappears. Check comment #37: <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=434522#c37" rel="noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=434522#c37</a></p>
<blockquote>
<p>For what it's worth, I'm seeing this bug happen when <em>any</em> flash file,
even ones that have NO actionscript calls (ExternalInterface, etc) in
them at all, is loaded into an iframe on a page where the page domain
and the iframe domain are different. This means that the iframe
problem is caused when there is in fact a cross-domain situation in
place. However, it's not totally clear if there's really actually
attempting to be a cross-domain call that <em>should</em> be prevented and
error'd out.</p>
<p>Because it's nothing that the flash SWF itself is trying to call to do
"Location.toString", and it's nothing about the javascript on the page
doing it, the only choice is that there's something about the flash
plugin itself (9.0.124 is what I'm testing with) that's trying to make
that call up to the parent/top window to do Location.toString().</p>
</blockquote>
<p>While the bug is marked as resolved, the test case attached <a href="https://bug434522.bugzilla.mozilla.org/attachment.cgi?id=321956" rel="noreferrer">https://bug434522.bugzilla.mozilla.org/attachment.cgi?id=321956</a> produces the same error message in the latest Firefox version (both in the Firebug console, or the Firefox Error Console window).</p>
<p><strong>Update:</strong><br>
The bug has been filed with Adobe as well in the old bug database: <a href="http://bugs.adobe.com/jira/browse/FP-561" rel="noreferrer">FP-561 "Location.toString" uncaught (security) exception caused by improper Flash plugin behavior</a> (you need an account to see the bug details). The last comment there when the bug was closed:</p>
<blockquote>
<p>Tested with the latest Flash Player 10.3.181.34 on Firefox 4 and 5, no
such exception was thrown. So the bug may have been fixed, right? If
you still meet this issue, please file a bug in our new bug system
<a href="https://bugbase.adobe.com/" rel="noreferrer">https://bugbase.adobe.com/</a> and put a link in the new bug to this
original JIRA report. We are happy to follow up your report in the new
bug system.</p>
</blockquote> |
12,671,420 | iOS 6 Facebook posting procedure ends up with "remote_app_id does not match stored id" | <p>This is my third question about posting on Facebook.</p>
<p>Although this may be a duplicate of <a href="https://stackoverflow.com/questions/12555799/mac-os-x-facebook-login-failed-no-stored-remote-app-id-for-app">Mac OS X Facebook login failed - no stored remote_app_id for app</a> but I decided to post separate question because we have iOS here but not MAC OS.</p>
<p>A few days ago I posted a question <a href="https://stackoverflow.com/questions/12644229/ios-6-facebook-posting-procedure-ends-up-with-permissions-alert-view">iOS 6 Facebook posting procedure ends up with "remote_app_id does not match stored id" error</a> The problem is still the same I can't perform a post but now I've got an error:</p>
<p><code>error is: Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: remote_app_id does not match stored id." UserInfo=0xa260270 {NSLocalizedDescription=The Facebook server could not fulfill this access request: remote_app_id does not match stored id.}
</code></p>
<p>The code you may find in my previous question.<br>
Does anyone know what's going on?<br>
What is remote and stored app ids?</p> | 12,675,645 | 5 | 2 | null | 2012-10-01 10:19:38.983 UTC | 13 | 2014-04-07 09:04:49.213 UTC | 2017-05-23 12:10:24.4 UTC | null | -1 | null | 782,334 | null | 1 | 46 | ios|iphone|objective-c|facebook | 27,318 | <p>This happens when authenticating using iOS6 Accounts API. </p>
<p>All you have to do to get it working is:</p>
<ul>
<li>log in to the developers.facebook.com</li>
<li>set your app to be an iOS Native app</li>
<li>type in your app's bundle ID.</li>
</ul>
<p><img src="https://i.stack.imgur.com/oxylC.png" alt="screenshot"></p> |
30,684,613 | Android Studio - XML Editor autocomplete not working with support libraries | <p>I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions!</p>
<p>For example,</p>
<pre><code><android.support.design.widget.CoordinatorLayout
android:id="@+id/header_root"
android:layout_width="match_parent"
android:layout_height="200dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primary_dark" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:src="@drawable/ic_action_add"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="56dp"
app:fabSize="normal"
app:layout_anchor="@id/header_root"
app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture.</p>
<p><img src="https://i.stack.imgur.com/BMZvA.png" alt="enter image description here"></p>
<p>I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!</p> | 31,207,367 | 32 | 7 | null | 2015-06-06 15:32:59.773 UTC | 28 | 2022-09-24 14:11:50.427 UTC | 2019-04-12 08:57:46.887 UTC | null | 7,258,332 | null | 3,352,901 | null | 1 | 103 | android|android-studio|autocomplete | 80,083 | <p>I have tried a lot of things (restart Android Studio, PC, Invalidate Caches, Power Saver mode,...).</p>
<p>Finally, deleting the <strong>.idea</strong> folder and all <strong>.iml</strong> files from the project, restarting Android Studio, and rebuilding Gradle did the trick. Autocomplete in XML support library is working again.</p>
<p>Checking out files from Version Control or copying all the source files in a new project would do the trick as well.</p> |
11,353,075 | How can I maintain fragment state when added to the back stack? | <p>I've written up a dummy activity that switches between two fragments. When you go from FragmentA to FragmentB, FragmentA gets added to the back stack. However, when I return to FragmentA (by pressing back), a totally new FragmentA is created and the state it was in is lost. I get the feeling I'm after the same thing as <a href="https://stackoverflow.com/questions/11111649/savedinstancestate-when-restoring-fragment-from-back-stack">this</a> question, but I've included a complete code sample to help root out the issue: </p>
<pre><code>public class FooActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentA());
transaction.commit();
}
public void nextFragment() {
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentB());
transaction.addToBackStack(null);
transaction.commit();
}
public static class FragmentA extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View main = inflater.inflate(R.layout.main, container, false);
main.findViewById(R.id.next_fragment_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((FooActivity) getActivity()).nextFragment();
}
});
return main;
}
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save some state!
}
}
public static class FragmentB extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.b, container, false);
}
}
}
</code></pre>
<p>With some log messages added:</p>
<pre><code>07-05 14:28:59.722 D/OMG ( 1260): FooActivity.onCreate
07-05 14:28:59.742 D/OMG ( 1260): FragmentA.onCreateView
07-05 14:28:59.742 D/OMG ( 1260): FooActivity.onResume
<Tap Button on FragmentA>
07-05 14:29:12.842 D/OMG ( 1260): FooActivity.nextFragment
07-05 14:29:12.852 D/OMG ( 1260): FragmentB.onCreateView
<Tap 'Back'>
07-05 14:29:16.792 D/OMG ( 1260): FragmentA.onCreateView
</code></pre>
<p>It's never calling FragmentA.onSaveInstanceState and it creates a new FragmentA when you hit back. However, if I'm on FragmentA and I lock the screen, FragmentA.onSaveInstanceState does get called. So weird...am I wrong in expecting a fragment added to the back stack to not need re-creation? Here's what the <a href="http://developer.android.com/guide/components/fragments.html#Transactions" rel="noreferrer">docs</a> say:</p>
<blockquote>
<p>Whereas, if you do call addToBackStack() when removing a fragment,
then the fragment is stopped and will be resumed if the user navigates
back.</p>
</blockquote> | 11,353,470 | 16 | 9 | null | 2012-07-05 21:50:39.927 UTC | 63 | 2022-06-11 07:17:17.083 UTC | 2017-05-23 11:55:10.63 UTC | null | -1 | null | 214,240 | null | 1 | 172 | android|android-fragments|back-stack | 163,086 | <p>If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with <code>onCreateView()</code> in the fragment lifecycle, see <a href="http://developer.android.com/guide/components/fragments.html#Creating" rel="noreferrer">Fragment lifecycle</a>. </p>
<p>So if you want to store state you should use instance variables and <strong>not</strong> rely on <code>onSaveInstanceState()</code>.</p> |
11,307,218 | GridView VS GridLayout in Android Apps | <p>I have to use a Grid to implement Photo Browser in Android.
So, I would like to know the <strong>difference between GridView and GridLayout</strong>.</p>
<p>So that I shall choose the right one. </p>
<p>Currently I'm using GridView to display the images dynamically.</p> | 11,307,615 | 1 | 0 | null | 2012-07-03 08:32:28.87 UTC | 54 | 2020-01-09 10:31:54.263 UTC | 2020-01-09 10:31:54.263 UTC | null | 1,439,092 | null | 1,439,092 | null | 1 | 244 | android|grid|android-gridview|grid-layout | 119,860 | <p>A <a href="http://developer.android.com/reference/android/widget/GridView.html" rel="noreferrer">GridView</a> is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.</p>
<p>This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen.
GridViews, much like ListViews reuse and recycle their views for better performance.</p>
<p>Whereas a <a href="http://developer.android.com/reference/android/widget/GridLayout.html" rel="noreferrer">GridLayout</a> is a layout that places its children in a rectangular grid.</p>
<p>It was introduced in API level 14, and was recently backported in the Support Library.
Its main purpose is to solve alignment and performance problems in other layouts.
Check out this <a href="http://android-developers.blogspot.com/2011/11/new-layout-widgets-space-and-gridlayout.html" rel="noreferrer">tutorial</a> if you want to learn more about GridLayout.</p> |
17,015,449 | How do I run .sh or .bat files from Terminal? | <p>I have a pretty basic problem here, that has happened so haphazardly to me that up until now, I've just ignored it. I downloaded tomcat web server and "Murach's Java Servlets and JSP" book is telling me to navigate to the tomcat/bin directory and start the server my typing in Terminal</p>
<p>$ startup</p>
<p>However, I get the error</p>
<pre><code>-bash: startup: command not found
</code></pre>
<p>The relevant files in this directory are startup.sh and startup.bat. Typing both of these returns the same error message</p>
<p>So my questions are, what are .bat and sh files, and how do I run these files? I've read several tutorials for different languages and software programs, and some times when the tutorial says execute a bunch of files in the command line, I get a "command not found" error. Sometimes it works, sometimes it doesn't. This is perplexing to me, so what are some common solutions to solving these sort of "command not found" Terminal problems?</p> | 17,015,495 | 11 | 0 | null | 2013-06-10 00:09:51.99 UTC | 10 | 2021-08-05 07:13:28.27 UTC | null | null | null | null | 1,484,555 | null | 1 | 42 | bash|tomcat|terminal | 313,960 | <p>The <code>.sh</code> is for *nix systems and <code>.bat</code> should be for Windows. Since your example shows a bash error and you mention Terminal, I'm assuming it's OS X you're using.</p>
<p>In this case you should go to the folder and type:</p>
<pre><code>./startup.sh
</code></pre>
<p><code>./</code> just means that you should call the script located in the current directory. (Alternatively, just type the full path of the <code>startup.sh</code>). If it doesn't work then, check if <code>startup.sh</code> has execute permissions.</p> |
16,717,461 | How can I `print` or `cat` when using parallel | <p>If I call a function using <code>parSapply</code> then <code>print</code>, <code>message</code> or <code>cat</code> statements inside that function don't seem to output to the console.</p>
<p>My process takes a very long time, so I need some way of seeing the progress and getting the results output as they are done. Are there any special commands that would allow me to print to the console from a parallel process?</p>
<p>Example:</p>
<pre><code>library(parallel)
oneloop = function(x) {
for(i in 1:50) {
a = rnorm(100000)
a = sort(a)
}
print(x)
message(x)
cat(x)
}
cl <- makeCluster(5)
output = parSapply(cl, 1:10, oneloop)
stopCluster(cl)
</code></pre> | 16,718,078 | 2 | 4 | null | 2013-05-23 15:04:13.143 UTC | 15 | 2015-01-29 19:11:02.49 UTC | 2013-05-23 15:23:15.13 UTC | null | 1,900,520 | null | 1,900,520 | null | 1 | 52 | r|io|parallel-processing | 12,784 | <p>Using <code>outfile</code> param in <code>makeCluster</code> you can redirect the output to a file and then check that file to see how your program progresses.</p>
<p>Interestingly on a Linux machine setting it to <code>""</code> outputs to the console, but that doesn't work for me on a Windows machine. File output works on both.</p> |
16,630,211 | JQuery get all elements by class name | <p>in the process of learning javscript and jquery, went through pages of google but can't seem to get this working. Basically I'm trying to collect innerhtml of classes, jquery seems to be suggested than plain javascript, into a document.write. </p>
<p>Here's the code so far;</p>
<pre><code><div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<script>
var mvar = $('.mbox').html();
document.write(mvar);
</script>
</code></pre>
<p>With this, only the first class shows under document.write. How can I show it all together like Block OneBlock TwoBlock Three? My ultimate goal with this is to show them comma seperated like Block One, Block Two, Block Three, Block Four. Thanks, bunch of relevant questions come up but none seem to be this simple.</p> | 16,630,214 | 5 | 1 | null | 2013-05-19 00:06:10.147 UTC | 8 | 2021-04-20 11:45:55.747 UTC | 2013-05-19 00:12:41.407 UTC | null | 205,997 | null | 1,443,455 | null | 1 | 82 | javascript|jquery | 212,461 | <p>One possible way is to use <a href="http://api.jquery.com/map/"><code>.map()</code></a> method:</p>
<pre><code>var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
</code></pre>
<p><strong>DEMO:</strong> <a href="http://jsfiddle.net/Y4bHh/">http://jsfiddle.net/Y4bHh/</a></p>
<p><strong>N.B.</strong> Please don't use <code>document.write</code>. For testing purposes <code>console.log</code> is the best way to go.</p> |
16,891,729 | Best Practices: Salting & peppering passwords? | <p>I came across a discussion in which I learned that what I'd been doing wasn't in fact salting passwords but peppering them, and I've since begun doing both with a function like:</p>
<pre><code>hash_function($salt.hash_function($pepper.$password)) [multiple iterations]
</code></pre>
<p>Ignoring the chosen hash algorithm (I want this to be a discussion of salts & peppers and not specific algorithms but I'm using a secure one), is this a secure option or should I be doing something different? For those unfamiliar with the terms:</p>
<ul>
<li><p>A <strong>salt</strong> is a randomly generated value usually stored with the string in the database designed to make it impossible to use hash tables to crack passwords. As each password has its own salt, they must all be brute-forced individually in order to crack them; however, as the salt is stored in the database with the password hash, a database compromise means losing both.</p></li>
<li><p>A <strong>pepper</strong> is a site-wide static value stored separately from the database (usually hard-coded in the application's source code) which is intended to be secret. It is used so that a compromise of the database would not cause the entire application's password table to be brute-forceable.</p></li>
</ul>
<p>Is there anything I'm missing and is salting & peppering my passwords the best option to protect my user's security? Is there any potential security flaw to doing it this way?</p>
<p><em>Note: Assume for the purpose of the discussion that the application & database are stored on separate machines, do not share passwords etc. so a breach of the database server does not automatically mean a breach of the application server.</em></p> | 16,896,216 | 5 | 2 | null | 2013-06-03 07:15:47.587 UTC | 132 | 2021-04-09 07:17:52.747 UTC | 2013-06-03 09:39:38.19 UTC | null | 168,868 | null | 2,294,775 | null | 1 | 173 | security|hash|passwords|salt|password-hash | 55,466 | <p>Ok. Seeing as I need to write about this <a href="https://stackoverflow.com/a/16597402/338665">over</a> and <a href="http://blog.ircmaxell.com/2012/04/properly-salting-passwords-case-against.html" rel="noreferrer">over</a>, I'll do one last canonical answer on pepper alone.</p>
<h1>The Apparent Upside Of Peppers</h1>
<p>It seems quite obvious that peppers should make hash functions more secure. I mean, if the attacker only gets your database, then your users passwords should be secure, right? Seems logical, right?</p>
<p>That's why so many people believe that peppers are a good idea. It "makes sense". </p>
<h1>The Reality Of Peppers</h1>
<p>In the security and cryptography realms, "make sense" isn't enough. Something has to be provable <strong>and</strong> make sense in order for it to be considered secure. Additionally, it has to be implementable in a maintainable way. The most secure system that can't be maintained is considered insecure (because if any part of that security breaks down, the entire system falls apart).</p>
<p>And peppers fit neither the provable or the maintainable models...</p>
<h1>Theoretical Problems With Peppers</h1>
<p>Now that we've set the stage, let's look at what's wrong with peppers.</p>
<ul>
<li><p><strong>Feeding one hash into another can be dangerous.</strong></p>
<p>In your example, you do <code>hash_function($salt . hash_function($pepper . $password))</code>.</p>
<p>We know from past experience that "just feeding" one hash result into another hash function can decrease the overall security. The reason is that both hash functions can become a target of attack. </p>
<p>That's why algorithms like <a href="http://en.wikipedia.org/wiki/PBKDF2" rel="noreferrer">PBKDF2</a> use special operations to combine them (hmac in that case).</p>
<p>The point is that while it's not a big deal, it is also not a trivial thing to just throw around. Crypto systems are designed to avoid "should work" cases, and instead focus on "designed to work" cases.</p>
<p>While this may seem purely theoretical, it's in fact not. For example, <a href="http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html" rel="noreferrer">Bcrypt cannot accept arbitrary passwords</a>. So passing <code>bcrypt(hash(pw), salt)</code> can indeed result in a far weaker hash than <code>bcrypt(pw, salt)</code> if <code>hash()</code> returns a binary string.</p></li>
<li><p><strong>Working Against Design</strong></p>
<p>The way bcrypt (and other password hashing algorithms) were designed is to work with a salt. The concept of a pepper was never introduced. This may seem like a triviality, but it's not. The reason is that a salt is not a secret. It is just a value that can be known to an attacker. A pepper on the other hand, by very definition is a cryptographic secret.</p>
<p>The current password hashing algorithms (bcrypt, pbkdf2, etc) all are designed to only take in one secret value (the password). Adding in another secret into the algorithm hasn't been studied at all.</p>
<p>That doesn't mean it is not safe. It means we don't know if it is safe. And the general recommendation with security and cryptography is that if we don't know, it isn't.</p>
<p>So until algorithms are designed and vetted by cryptographers for use with secret values (peppers), current algorithms shouldn't be used with them.</p></li>
<li><p><strong>Complexity Is The Enemy Of Security</strong></p>
<p>Believe it or not, <a href="http://www.schneier.com/news-038.html" rel="noreferrer">Complexity Is The Enemy Of Security</a>. Making an algorithm that looks complex may be secure, or it may be not. But the chances are quite significant that it's not secure. </p></li>
</ul>
<h1>Significant Problems With Peppers</h1>
<ul>
<li><p><strong>It's Not Maintainable</strong></p>
<p>Your implementation of peppers precludes the ability to rotate the pepper key. Since the pepper is used at the input to the one way function, you can never change the pepper for the lifetime of the value. This means that you'd need to come up with some wonky hacks to get it to support key rotation.</p>
<p>This is <strong>extremely</strong> important as it's required whenever you store cryptographic secrets. Not having a mechanism to rotate keys (periodically, and after a breach) is a huge security vulnerability.</p>
<p>And your current pepper approach would require every user to either have their password completely invalidated by a rotation, or wait until their next login to rotate (which may be never)...</p>
<p>Which basically makes your approach an immediate no-go.</p></li>
<li><p><strong>It Requires You To Roll Your Own Crypto</strong></p>
<p>Since no current algorithm supports the concept of a pepper, it requires you to either compose algorithms or invent new ones to support a pepper. And if you can't immediately see why that's a really bad thing:</p>
<blockquote>
<p>Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break.</p>
</blockquote>
<ul>
<li><a href="http://www.schneier.com/blog/archives/2011/04/schneiers_law.html" rel="noreferrer">Bruce Schneier</a></li>
</ul>
<p><strong>NEVER</strong> roll your own crypto...</p></li>
</ul>
<h1>The Better Way</h1>
<p>So, out of all the problems detailed above, there are two ways of handling the situation. </p>
<ul>
<li><p><strong>Just Use The Algorithms As They Exist</strong></p>
<p>If you use bcrypt or scrypt correctly (with a high cost), all but the weakest dictionary passwords should be statistically safe. The current record for hashing bcrypt at cost 5 is 71k hashes per second. At that rate even a 6 character random password would take years to crack. And considering my minimum recommended cost is 10, that reduces the hashes per second by a factor of 32. So we'd be talking only about 2200 hashes per second. At that rate, even some dictionary phrases or modificaitons may be safe.</p>
<p>Additionally, we should be checking for those weak classes of passwords at the door and not allowing them in. As password cracking gets more advanced, so should password quality requirements. It's still a statistical game, but with a proper storage technique, and strong passwords, everyone should be practically very safe...</p></li>
<li><p><strong>Encrypt The Output Hash Prior To Storage</strong></p>
<p>There exists in the security realm an algorithm designed to handle everything we've said above. It's a block cipher. It's good, because it's reversible, so we can rotate keys (yay! maintainability!). It's good because it's being used as designed. It's good because it gives the user no information.</p>
<p>Let's look at that line again. Let's say that an attacker knows your algorithm (which is required for security, otherwise it's security through obscurity). With a traditional pepper approach, the attacker can create a sentinel password, and since he knows the salt and the output, he can brute force the pepper. Ok, that's a long shot, but it's possible. With a cipher, the attacker gets nothing. And since the salt is randomized, a sentinel password won't even help him/her. So the best they are left with is to attack the encrypted form. Which means that they first have to attack your encrypted hash to recover the encryption key, and then attack the hashes. But there's a <strong>lot</strong> of research into the attacking of ciphers, so we want to rely on that.</p></li>
</ul>
<h1>TL/DR</h1>
<p>Don't use peppers. There are a host of problems with them, and there are two better ways: not using any server-side secret (yes, it's ok) and encrypting the output hash using a block cipher prior to storage.</p> |
25,805,599 | Got Unrecognized selector -replacementObjectForKeyedArchiver: crash when implementing NSCoding in Swift | <p>I created a Swift class that conforms to NSCoding. (Xcode 6 GM, Swift 1.0)</p>
<pre><code>import Foundation
private var nextNonce = 1000
class Command: NSCoding {
let nonce: Int
let string: String!
init(string: String) {
self.nonce = nextNonce++
self.string = string
}
required init(coder aDecoder: NSCoder) {
nonce = aDecoder.decodeIntegerForKey("nonce")
string = aDecoder.decodeObjectForKey("string") as String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(nonce, forKey: "nonce")
aCoder.encodeObject(string, forKey: "string")
}
}
</code></pre>
<p>But when I call...</p>
<p><code>let data = NSKeyedArchiver.archivedDataWithRootObject(cmd);</code></p>
<p>It crashes gives me this error.</p>
<pre><code>2014-09-12 16:30:00.463 MyApp[30078:60b] *** NSForwarding: warning: object 0x7a04ac70 of class '_TtC8MyApp7Command' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[MyApp.Command replacementObjectForKeyedArchiver:]
</code></pre>
<p>What should I do?</p> | 25,805,619 | 1 | 4 | null | 2014-09-12 09:56:46.737 UTC | 10 | 2018-02-07 06:45:59.62 UTC | 2015-12-21 05:25:16.887 UTC | null | 467,588 | null | 467,588 | null | 1 | 74 | ios|swift|xcode6|nscoding | 20,628 | <p>Although Swift class works without inheritance, but in order to use <code>NSCoding</code> you must <strong>inherit from <code>NSObject</code></strong>.</p>
<pre><code>class Command: NSObject, NSCoding {
...
}
</code></pre>
<p>Too bad the compiler error is not very informative :(</p> |
63,003,669 | How can I see my git secrets unencrypted? | <p>I had some secrets in my code and upon learning about GitHub Actions I decided to save them in the repository's secret menu for later use in my pipeline.</p>
<p>However, now I need to access these secrets to develop a new feature and I can't. Every time I try to see the value it asks me to update the secrets. There is no option to just "see" them.</p>
<p>I don't want to update anything I just want to see their values.</p>
<p>How can I see the unencrypted values of my secrets in the project?</p> | 63,009,069 | 2 | 5 | null | 2020-07-20 20:56:21.59 UTC | 5 | 2022-07-07 09:44:37.893 UTC | 2022-07-07 09:44:15.547 UTC | null | 3,001,761 | null | 1,337,392 | null | 1 | 29 | github|github-actions | 17,523 | <p>In order to see your GitHub Secrets follow these steps:</p>
<ol>
<li>Create a workflow that <code>echos</code> all the secrets to a file.</li>
<li>As the last step of the workflow, start a <a href="https://github.com/marketplace/actions/debugging-with-tmate" rel="noreferrer">tmate session</a>.</li>
<li>Enter the GitHub Actions runner via SSH (the SSH address will be displayed in the action log) and view your secrets file.</li>
</ol>
<p>Here is a complete working GitHub Action to do that:</p>
<pre><code>name: Show Me the S3cr3tz
on: [push]
jobs:
debug:
name: Debug
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v2
- name: Set up secret file
env:
DEBUG_PASSWORD: ${{ secrets.DEBUG_PASSWORD }}
DEBUG_SECRET_KEY: ${{ secrets.DEBUG_SECRET_KEY }}
run: |
echo $DEBUG_PASSWORD >> secrets.txt
echo $DEBUG_SECRET_KEY >> secrets.txt
- name: Run tmate
uses: mxschmitt/action-tmate@v2
</code></pre>
<p>The reason for using <code>tmate</code> in order to allow SSH access, instead of just running <code>cat secrets.txt</code>, is that GitHub Actions will automatically obfuscate any word that it had as a secret in the console output.</p>
<hr />
<p>That said - I agree with the commenters. You should normally avoid that. Secrets are designed so that you save them in your <em>own</em> secret keeping facility, and in addition, make them <em>readable</em> to GitHub actions. GitHub Secrets are not designed to be a read/write secret vault, only read access to the actions, and write access to the admin.</p> |
58,138,138 | Angular CLI ng command not found on Mac Os | <p>I looked at the numerous posts on here regarding this issue and tried them but had no success resolving this.</p>
<p>I am on MacOS and here is what I have done so far based on recommendations I have found here but I still get this error</p>
<pre><code> ~~ sudo npm uninstall -g angular-cli
~~ sudo npm uninstall -g @angular/cli
~~ sudo npm cache clean --force
~~ sudo npm install -g @angular/cli
</code></pre>
<p>This outputs:</p>
<pre><code>/usr/local/Cellar/node/11.10.0/bin/ng -> /usr/local/Cellar/node/11.10.0/lib/node_modules/@angular/cli/bin/ng
> @angular/[email protected] postinstall /usr/local/Cellar/node/11.10.0/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js
+ @angular/[email protected]
added 245 packages from 185 contributors in 8.784s
</code></pre>
<p>However, issuing command below does not work:</p>
<pre><code> ~~ ng version
-bash: ng: command not found
</code></pre>
<p>Some people suggesting linking so I tried that as well:</p>
<pre><code> ~~ sudo npm link @angular/cli
</code></pre>
<p>, which outputs following:</p>
<pre><code>/Users/dinob/node_modules/@angular/cli -> /usr/local/Cellar/node/11.10.0/lib/node_modules/@angular/cli
</code></pre>
<p>, but ng version is still not working:</p>
<pre><code> ~~ ng version
-bash: ng: command not found
</code></pre>
<p>Many posts suggest that there should be a directory <code>.npm-global</code> created under my /Users/dinob directory but I dont see it. I aonly see <code>.npm</code> directory, not <code>.npm-global</code>.</p>
<p>I also tried following:</p>
<p>uninstall angular as described above</p>
<p>brew update</p>
<p>brew upgrade node // this upgraded from 11.10.0 to 12.10.0</p>
<p>then repeat steps above to install angular/cli</p>
<p>still same problem, ng command not found</p>
<p>This is not a duplicate question as KenWhite suggests and I have reviewed all the posts on SO I could find (and more) regarding this issue, tried them and none of them solved the issue for me. </p>
<p>sudo npm install -g @angular/cli command completed and returned following paths but none of them @angular directory in them:</p>
<pre><code>/usr/local/Cellar/node/11.10.0/bin/ng -> /usr/local/Cellar/node/11.10.0/lib/node_modules/@angular/cli/bin/ng
</code></pre>
<p>Above, there is no bin folder:</p>
<pre><code>dinob @ /usr/local/Cellar/node/11.10.0
~~ ls -la
total 80
drwxr-xr-x 8 dinob staff 256 2 Oct 11:30 ./
drwxr-xr-x 5 dinob staff 160 27 Sep 09:29 ../
-rw-r--r--@ 1 dinob staff 8196 2 Oct 11:32 .DS_Store
-rw-r--r-- 1 dinob staff 26696 14 Feb 2019 README.md
drwxr-xr-x 3 dinob staff 96 14 Feb 2019 etc/
drwxr-xr-x 3 dinob staff 96 14 Feb 2019 include/
drwxr-xr-x 5 dinob staff 160 2 Oct 11:22 lib/
drwxr-xr-x 5 dinob staff 160 14 Feb 2019 share/
</code></pre>
<p>Same for this location <code>> @angular/[email protected] postinstall /usr/local/Cellar/node/11.10.0/lib/node_modules/@angular/cli</code>:</p>
<pre><code>dinob @ /usr/local/Cellar/node/11.10.0/lib/node_modules
~~ ls -la
total 16
drwxr-xr-x 6 dinob staff 192 2 Oct 11:22 ./
drwxr-xr-x 5 dinob staff 160 2 Oct 11:22 ../
-rw-r--r--@ 1 dinob staff 6148 2 Oct 11:27 .DS_Store
drwxr-xr-x 7 root staff 224 26 Sep 16:42 n/
drwxr-xr-x 26 dinob staff 832 2 Oct 11:28 npm/
drwxr-xr-x 6 dinob staff 192 15 Jul 16:32 react-native-cli/
</code></pre> | 58,207,895 | 7 | 4 | null | 2019-09-27 16:12:02.937 UTC | 8 | 2022-02-21 15:13:14.757 UTC | 2019-10-03 17:21:24.937 UTC | null | 3,453,898 | null | 3,453,898 | null | 1 | 33 | macos|angular-cli | 50,404 | <p>After days of googling and getting no help neither on here nor from @Angular github which is pretty much useless, was finally able to resolve the issue and get my angular ng command not found issue resolved following these steps:</p>
<p><strong>1. Instal nvm</strong></p>
<p>Issue these 3 commands to install nvm. (Angular documented steps <a href="https://angular.io/guide/setup-local" rel="noreferrer">https://angular.io/guide/setup-local</a> to setup your environment did not work for me). </p>
<p>So I installed nvm like so:</p>
<pre><code>curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash
export NVM_DIR="/Users/your-user-name/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
</code></pre>
<p>After this, make sure you restart terminal and you should be able to issue <code>nvm --version</code> to see version of installed nvm.</p>
<p><strong>2. Install node using nvm</strong></p>
<pre><code>nvm install stable
nvm install node
</code></pre>
<p><strong>3. Finally, install angular</strong></p>
<pre><code>npm install -g @angular/cli
</code></pre>
<p><strong>4. Restart terminal</strong></p>
<p>Restart terminal and you should be able to use <code>ng version</code> to see version installed on your system</p>
<pre><code> ~~ ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 8.3.6
Node: 12.11.1
OS: darwin x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.803.6
@angular-devkit/core 8.3.6
@angular-devkit/schematics 8.3.6
@schematics/angular 8.3.6
@schematics/update 0.803.6
rxjs 6.4.0
</code></pre>
<p>I can now create and start my project</p>
<pre><code>ng new my-test-project
ng serve my-test project
</code></pre>
<p><a href="https://i.stack.imgur.com/RIz24.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RIz24.png" alt="enter image description here"></a></p>
<p>I think SO should start getting serious about people down-voting questions or marking them as duplicates before reading them and even trying to understand what was asked and what the problem is.</p>
<p>It seems to be lots of people read the title and decide the fate of question just based on that and any disagreement ends up in blocking question entirely. </p>
<p>So much bias and hate on a site that is supposed to help. </p>
<p>Better alternatives are very much needed.</p>
<p><strong>UPDATE</strong></p>
<p>If you are like me and switched to use zsh shel instead of bash shell (since Catalina MacOs now uses zsh), you might have noticed that <code>ng version</code> has stopped working for you.</p>
<p>In that case, modify your .zshrc file by opening it in vim:</p>
<p><code>vi ~/.zshrc</code></p>
<p>In there, find this line:</p>
<pre><code>source $ZSH/oh-my-zsh.sh
</code></pre>
<p>Underneath this line, add following line:</p>
<pre><code>source /Users/Your-User-Name/.bash_profile
</code></pre>
<p>Save the file by hitting Esc key and typing <code>:wq</code> and hitting Enter</p>
<p>Restart your terminal</p>
<p>Reissue <code>ng version</code> and you should see it in your zsh shell:</p>
<p><a href="https://i.stack.imgur.com/BTH19.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BTH19.png" alt="enter image description here"></a></p> |
9,650,572 | Resize images in PHP without using third-party libraries? | <p>In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?</p>
<pre><code><?php
$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999);
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);
// Check if the file was sent through HTTP POST.
if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['userfile']['size'] <= 5000000) {
// Move the file to the path specified.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {
// ...
}
}
}
?>
</code></pre> | 9,655,694 | 6 | 6 | null | 2012-03-10 22:03:56.113 UTC | 8 | 2021-03-14 02:24:52.173 UTC | 2017-03-23 22:49:12.72 UTC | null | 962,844 | null | 962,844 | null | 1 | 14 | php|image|image-resizing | 79,056 | <p>Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.</p>
<pre><code>$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
</code></pre>
<p>To anyone else seeking a complete example, create two files:</p>
<pre><code><!-- send.html -->
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<center>
<div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">
Select an image.
<br/>
<br/>
<form action="receive.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" size="40">
<input type="submit" value="Send">
</form>
</div>
</center>
</body>
</code></pre>
<p></p>
<pre><code><?php
// receive.php
$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";
echo "File path:".$filePath."<br/>";
if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {
echo "File successfully received through HTTP POST.<br/>";
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['image']['size'] <= 5000000) {
echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";
// Resize and save the image.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
// Save the original image.
if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {
echo "Copied the original file to the specified destination.<br/>";
}
}
}
?>
</code></pre> |
10,101,700 | Moving matplotlib legend outside of the axis makes it cutoff by the figure box | <p>I'm familiar with the following questions:</p>
<p><a href="https://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-legend-outside-the-plot">Matplotlib savefig with a legend outside the plot</a></p>
<p><a href="https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot">How to put the legend out of the plot</a></p>
<p>It seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits. </p>
<p>Shrinking the axes, however, is not an ideal solution because it makes the data smaller making it actually more difficult to interpret; particularly when its complex and there are lots of things going on ... hence needing a large legend</p>
<p>The example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points.</p>
<p><a href="http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-plots" rel="noreferrer">http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-plots</a> </p>
<p><strong>What I would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legend.</strong></p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
ax.grid('on')
</code></pre>
<p>Notice how the final label 'Inverse tan' is actually outside the figure box (and looks badly cutoff - not publication quality!)
<img src="https://i.stack.imgur.com/0XtO2.png" alt="enter image description here"></p>
<p>Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a little confused why this is so difficult in python... Is there a historical reason? Is Matlab equally poor on this matter?</p>
<p>I have the (only slightly) longer version of this code on pastebin <a href="http://pastebin.com/grVjc007" rel="noreferrer">http://pastebin.com/grVjc007</a></p> | 10,154,763 | 4 | 3 | null | 2012-04-11 07:32:08.943 UTC | 100 | 2022-09-21 21:35:48.977 UTC | 2017-05-23 11:47:28.433 UTC | null | -1 | null | 359,474 | null | 1 | 270 | python|matplotlib|legend | 213,838 | <p>Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).</p>
<p>The code I am looking for is adjusting the savefig call to:</p>
<pre><code>fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
</code></pre>
<p>This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
</code></pre>
<p>This produces:</p>
<p><img src="https://i.imgur.com/qysSE4t.png" alt=""></p>
<p>[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm. </p> |
9,941,521 | using BETWEEN in WHERE condition | <p>I'd like the following function to select hotels with an accomodation between a certain <code>$minvalue</code> and <code>$maxvalue</code>. What would be the best way to do that?</p>
<pre><code>function gethotels($state_id,$city,$accommodation,$minvalue,$maxvalue,$limit,$pgoffset)
{
$this->db->limit($limit, $pgoffset);
$this->db->order_by("id", "desc");
$this->db->where('state_id',$state_id);
$this->db->where('city',$city);
// This one should become a between selector
$this->db->where($accommodation,$minvalue);
$result_hotels = $this->db->get('hotels');
return $result_hotels->result();
}
</code></pre> | 9,941,658 | 8 | 5 | null | 2012-03-30 10:48:32.143 UTC | 7 | 2022-03-10 09:22:27.3 UTC | 2017-05-14 16:04:32.58 UTC | null | 1,886,765 | null | 1,300,582 | null | 1 | 20 | php|codeigniter | 135,981 | <p>You should use</p>
<pre><code>$this->db->where('$accommodation >=', minvalue);
$this->db->where('$accommodation <=', maxvalue);
</code></pre>
<p>I'm not sure of syntax, so I beg your pardon if it's not correct.<br>
Anyway <code>BETWEEN</code> is implemented using >=min && <=max.<br>
This is the meaning of my example.</p>
<p><strong>EDITED:</strong><br>
Looking at <a href="http://web.archive.org/web/20120531112954/http://codeigniter.com/forums/viewthread/100048" rel="noreferrer">this link</a> I think you could write:</p>
<pre><code>$this->db->where("$accommodation BETWEEN $minvalue AND $maxvalue");
</code></pre> |
9,986,804 | PHP Fatal error: Call to undefined function mssql_connect() | <p>I've never used php before and am trying to connect to a SQL Server 2008 instance on a Windows machine running IIS7 and PHP5.3.</p>
<p>I have downloaded and installed <code>SQLSRV30.EXE</code> from <a href="http://www.microsoft.com/download/en/details.aspx?id=20098">here</a> in <code>C:\Program Files (x86)\PHP\ext</code> added this to <code>C:\Program Files (x86)\PHP\php.ini</code>:</p>
<pre><code>extension=php_sqlsrv_53_nts.dll
</code></pre>
<p>Then restarted the entire server. I still get fatal errors in my log file saying:</p>
<pre><code>PHP Fatal error: Call to undefined function mssql_connect()
</code></pre>
<p>What do I need to do to connect to Microsoft SQL Server 2008 from PHP 5.3 running on IIS7/Windows Server 2008? I'm sure it's something really dumb that I'm missing...</p>
<p><strong>FULL PHPINFO --></strong> <a href="http://demo.mandibleweb.com/zapified/hello.php">http://demo.mandibleweb.com/zapified/hello.php</a></p>
<p>phpinfo(): </p>
<pre><code>PHP Version 5.3.10
System
Windows NT MWD001 6.1 build 7601 (Windows Server 2008 R2 Standard Edition Service Pack 1) i586
Build Date
Feb 2 2012 20:10:58
Compiler
MSVC9 (Visual C++ 2008)
Architecture
x86
Configure Command
cscript /nologo configure.js "--enable-snapshot-build" "--enable-debug-pack" "--disable-zts" "--disable-isapi" "--disable-nsapi" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8-11g=C:\php-sdk\oracle\instantclient11\sdk,shared" "--with-enchant=shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet" "--with-mcrypt=static" "--disable-static-analyze"
Server API
CGI/FastCGI
Virtual Directory Support
disabled
Configuration File (php.ini) Path
C:\Windows
Loaded Configuration File
C:\Program Files (x86)\PHP\php.ini
</code></pre> | 9,986,908 | 3 | 1 | null | 2012-04-03 03:44:26.53 UTC | 9 | 2016-04-11 06:58:48.867 UTC | 2012-06-15 17:30:35.453 UTC | null | 367,456 | null | 585,552 | null | 1 | 20 | php|sql-server|iis|iis-7 | 208,105 | <p>I have just tried to install that extension on my dev server.</p>
<p>First, make sure that the extension is correctly enabled. Your <code>phpinfo()</code> output doesn't seem complete.</p>
<p>If it is indeed installed properly, your <code>phpinfo()</code> should have a section that looks like this:
<img src="https://i.stack.imgur.com/l62KZ.png" alt="enter image description here"></p>
<p>If you do not get that section in your <code>phpinfo()</code>. Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.</p>
<p>Finally, check your <code>extension_dir</code> setting. By default it's this: <code>extension_dir = "ext"</code>, for most of the time it works fine, but if it doesn't try: <code>extension_dir = "C:\PHP\ext"</code>.</p>
<p>===========================================================================</p>
<p><strong>EDIT given new info:</strong></p>
<p>You are using the wrong function. <code>mssql_connect()</code> is part of the <a href="http://www.php.net/manual/en/book.mssql.php">Mssql</a> extension. You are using microsoft's extension, so use <code>sqlsrv_connect()</code>, for the API for the microsoft driver, look at <code>SQLSRV_Help.chm</code> which should be extracted to your <code>ext</code> directory when you extracted the extension.</p> |
9,765,686 | Include referenced project's .config file | <p>Rather than <a href="https://stackoverflow.com/questions/2011434/preventing-referenced-assembly-pdb-and-xml-files-copied-to-output">excluding a file from the referenced output of an assembly</a>, I want to add one!</p>
<p>I have a console application project (BuildTest1) that references a second class library project (ClassLibrary1). The Visual Studio solution looks like this:</p>
<p><img src="https://i.stack.imgur.com/KWNea.png" alt="Solution layout"></p>
<p>I have a class library project that has an app.config. I want this .config file copied to the referring project's output, just like the .dll and .pdb files are. The config file for the class library is copied to the class library output directory as 'ClassLibrary1.dll.config'</p>
<p>I've tried adding this to the .exe project's .csproj file but it doesn't seem to make any difference:</p>
<pre><code> <PropertyGroup>
<AllowedReferenceRelatedFileExtensions>
.pdb;
.xml;
.config
</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
</code></pre> | 9,769,667 | 1 | 0 | null | 2012-03-19 06:02:41.257 UTC | 9 | 2012-03-19 11:53:27.827 UTC | 2017-05-23 12:10:19.847 UTC | null | -1 | null | 25,702 | null | 1 | 23 | visual-studio-2010|msbuild|msbuild-4.0 | 5,095 | <p>I was so close... I tracked this down to the MSBuild <a href="http://msdn.microsoft.com/en-us/library/9ad3f294.aspx" rel="noreferrer">ResolveAssemblyReference</a> task that is called from the ResolveAssemblyReferences target in Microsoft.Common.targets. This is what populates the ReferenceCopyLocalPaths item.</p>
<p>So looking at the pattern of files it was matching I discovered that the file extension .dll.config (rather than just .config) did the trick:</p>
<pre><code><PropertyGroup>
<AllowedReferenceRelatedFileExtensions>
.pdb;
.xml;
.dll.config
</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
</code></pre> |
10,005,509 | adb logcat hangs with "waiting for device" message | <p>When I type <code>adb devices</code> command on terminal, it shows device is connected </p>
<blockquote>
<p>List of devices attached </p>
<p>0123456789ABCDEF device</p>
</blockquote>
<p>But when I type <code>adb logcat</code> command, it hangs with below message </p>
<blockquote>
<p>waiting for device</p>
</blockquote>
<p>Can anybody tell me what is the problem behind this? I test the device on cts.</p> | 10,006,121 | 16 | 7 | null | 2012-04-04 05:41:23.243 UTC | 3 | 2021-12-22 11:08:52.493 UTC | 2013-05-17 05:44:08.693 UTC | null | 872,173 | null | 872,173 | null | 1 | 34 | android|adb|android-logcat|cts | 49,064 | <p>I am not pretty much sure if this works for you but can you please try the steps below:</p>
<pre><code># Kill and restart
$ adb kill-server
$ adb start-server
daemon not running. starting it now *
daemon started successfully *
# Device appears, but is listed as offline
$ adb devices
$ adb logcat
</code></pre> |
10,171,658 | Lose EF Code First Migration when working on different TFS branches? | <p>We are using TFS and have different branches for our Dev.</p>
<ol>
<li><p>in the branch A we made a migration to change a column size</p></li>
<li><p>in the branch B we made a migration to add a new table. This branch doesn not know about the branch A modification !!</p></li>
<li><p>both modification are merged to the main branch.</p></li>
</ol>
<p>When I do an update database, it does the 2 migration but at the end tells me there is pending changes. If I do an Add-Migration, it creates the same as the 1st migration (in branch A).</p>
<blockquote>
<p>Unable to update database to match the current model because there are pending
changes and automatic migration is disabled. Either write the pending model
changes to a code-based migration or enable automatic migration. Set
DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic
migration.
You can use the Add-Migration command to write the pending model changes to a
code-based migration.</p>
</blockquote>
<p>Is it because something is missing in the content of the property Target de IMigrationMetadata of my last migration since it didn't know about the 1st one ?</p>
<p>Is it possible to handle migrations in different TFS branches?</p> | 10,394,519 | 3 | 2 | null | 2012-04-16 09:29:34.973 UTC | 18 | 2019-12-02 21:08:14.033 UTC | 2012-04-16 09:46:27.99 UTC | null | 41,956 | null | 1,335,931 | null | 1 | 35 | .net|entity-framework|coldfusion|ef-code-first|entity-framework-migrations | 10,323 | <p>An EF migration step contains a metadata file, that has a signature of the model that is the result of the migration step. The problem when merging is that the signature of the migration done in branch B doesn't include the stuff done in the migration in branch A. As long as the migrations are in the branches, this is correct. When merging it becomes wrong.</p>
<p>To remedy it, you have to regenerate the meta-data of the latter migration with</p>
<pre><code>add-migration MyMigrationName
</code></pre>
<p>Running <code>add-migration</code> on an existing migration without the <code>-force</code> parameter will regenerate just the metadata.</p>
<p>I wrote an in depth walk-through of a merging scenario in the <a href="http://coding.abel.nu/2012/02/ef-migrations-and-a-merge-conflict/">EF Migrations and a Merge Conflict</a> post on my blog.</p> |
9,808,982 | CLR implementation of virtual method calls to interface members | <p>Out of curiosity: <em>how does the CLR dispatch virtual method calls to interface members to the correct implementation?</em></p>
<p>I know about the VTable that the CLR maintains for each type with method slots for each method, and the fact that for each interface it has an additional list of method slots that point to the associated interface method implementations. But I don't understand the following: how does the CLR efficiently determine which interface method slot list to pick from the type's VTable?</p>
<p>The article <a href="https://web.archive.org/web/20150515023057/https://msdn.microsoft.com/en-us/magazine/cc163791.aspx" rel="noreferrer">Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects</a> from the May 2005 issue of the MSDN Magazine talks about a process-level mapping table IVMap indexed by interface ID. Does this mean that all types in the same process have the same pointer to the same IVMap?</p>
<p>It also states that:</p>
<blockquote>
<p>If <code>MyInterface1</code> is implemented by two classes, there will be two
entries in the IVMap table. The entry will point back to the beginning
of the sub-table embedded within the <code>MyClass</code> method table.</p>
</blockquote>
<p>How does the CLR know which entry to pick? Does it do a linear search to find the entry that matches the current type? Or a binary search? Or some kind of direct indexing and have a map with possibly many empty entries in it?</p>
<p>I've also read the chapter on Interfaces in CLR via C# 3rd edition but it does not talk about this. Therefore, the answers to <a href="https://stackoverflow.com/questions/3262428/how-does-net-clr-implement-an-interface-internally">this other question</a> do not answer my question.</p> | 9,811,253 | 3 | 4 | null | 2012-03-21 16:39:21.597 UTC | 20 | 2016-10-30 13:19:22.507 UTC | 2017-05-23 12:32:14.49 UTC | null | -1 | null | 146,622 | null | 1 | 35 | c#|interface|clr|dispatch|method-call | 6,761 | <p><img src="https://i.stack.imgur.com/J5TZJ.gif" alt=".NET Stack"></p>
<p>If you take a look at diagram that was on the linked site, it may make it easier to understand. </p>
<blockquote>
<p>Does this mean that all types in the same process have the same pointer to the same IVMap?</p>
</blockquote>
<p>Yes, since it is at the domain level, it means everything in that AppDomain has the same IVMap.</p>
<blockquote>
<p>How does the CLR know which entry to pick? Does it do a linear search to find the entry that matches the current type? Or a binary search? Or some kind of direct indexing and have a map with possibly many empty entries in it?</p>
</blockquote>
<p>The classes are laid out with offsets, so everything has a relatively set area on where it would be. That makes things easier when looking for methods. It would search the IVMap table and find that method from the interface. From there, it goes to the MethodSlotTable and uses that class' implementation of the interface. The inteface map for the class holds the metadata, however, the implementation is treated just like any other method. </p>
<p>Again from the site you linked: </p>
<blockquote>
<p>Each interface implementation will have an entry in IVMap. If MyInterface1 is implemented by two classes, there will be two entries in the IVMap table. The entry will point back to the beginning of the sub-table embedded within the MyClass method table</p>
</blockquote>
<p>This means that each time an interface is implemented it has a unique record in the IVMap which points to the MethodSlotTable which in turn points to the implementation. So it knows which implementation to pick based on the class that is calling it as that IVMap record points to the MethodSlotTable in the class calling the method. So I imagine it is just a linear search through the IVMap to find the correct instance and then they are off and running.</p>
<hr>
<p>EDIT: To provide more info on the IVMap.</p>
<p>Again, from the link in the OP:</p>
<blockquote>
<p>The first 4 bytes of the first InterfaceInfo entry points to the TypeHandle of MyInterface1 (see Figure 9 and Figure 10). The next WORD (2 bytes) is taken up by Flags (where 0 is inherited from parent, and 1 is implemented in the current class). The WORD right after Flags is Start Slot, which is used by the class loader to lay out the interface implementation sub-table. </p>
</blockquote>
<p>So here we have a table where the number is the offset of bytes. This is just one record in the IVMap:</p>
<pre><code>+----------------------------------+
| 0 - InterfaceInfo |
+----------------------------------+
| 4 - Parent |
+----------------------------------+
| 5 - Current Class |
+----------------------------------+
| 6 - Start Slot (2 Bytes) |
+----------------------------------+
</code></pre>
<p>Suppose there are 100 interface records in this AppDomain and we need to find the implementation for each one. We just compare the 5th byte to see if it matches our current class and if it does, we jump to the code in the 6th byte. Since, each record is 8 bytes long, we would need to do something like this: (Psuedocode)</p>
<pre><code>findclass :
if (!position == class)
findclass adjust offset by 8 and try again
</code></pre>
<p>While it is still a linear search, in reality, it isn't going to take that long as the size of data being iterated isn't huge. I hope that helps.</p>
<hr>
<p>EDIT2: </p>
<p>So after looking at the diagram and wondering why there is no Slot 1 in the IVMap for the class in the diagram I re-read the section and found this:</p>
<blockquote>
<p>IVMap is created based on the Interface Map information embedded within the method table. Interface Map is created based on the metadata of the class during the MethodTable layout process. Once typeloading is complete, only IVMap is used in method dispatching.</p>
</blockquote>
<p>So the IVMap for a class is only loaded with the interfaces that the specific class inherits. It looks like it copies from the Domain IVMap but only keeps the interfaces that are pointed to. This brings up another question, how? Chances are it is the equivalent of how C++ does vtables where each entry has an offset and the Interface Map provides a list of the offsets to include in the IVMap. </p>
<p>If we look at the IVMap that could be for this entire domain:</p>
<pre><code>+-------------------------+
| Slot 1 - YourInterface |
+-------------------------+
| Slot 2 - MyInterface |
+-------------------------+
| Slot 3 - MyInterface2 |
+-------------------------+
| Slot 4 - YourInterface2 |
+-------------------------+
</code></pre>
<p>Assume there are only 4 implementations of Interface Map in this domain. Each slot would have an offset (similar to the IVMap record I posted earlier) and the IVMap for this class would use those offsets to access the record in the IVMap.</p>
<p>Assume each slot is 8 bytes with slot 1 starting at 0 so if we wanted to get slot 2 and 3 we would do something like this:</p>
<pre><code>mov ecx,edi
mov eax, dword ptr [ecx]
mov eax, dword ptr [ecx+08h] ; slot 2
; do stuff with slot 2
mov eax, dword ptr [ecx+10h] ; slot 3
; do stuff with slot 3
</code></pre>
<p>Please excuse my x86 as I'm not that familiar with it but I tried to copy what they have in the article that was linked to.</p> |
9,951,521 | Map JSON data to Knockout observableArray with specific view model type | <p>Is there a way to map a JSON data object to an observable array and then in turn have each item of the observable array be initialized into a specific type of view model?</p>
<p>I've looked at all of knockout's documentation along with the knockout and mapping examples here and I can't find any answer that works for what I'm after.</p>
<p>So, I have the following JSON data:</p>
<pre><code> var data = {
state : {
name : 'SD',
cities : [{
name : 'Sioux Falls',
streets : [{
number : 1
}, {
number : 3
}]
}, {
name : 'Rapid City',
streets : [{
number : 2
}, {
number : 4
}]
}]
}
};
</code></pre>
<p>And I have the following view models:</p>
<pre><code>var StateViewModel = function(){
this.name = ko.observable();
this.cities = ko.observableArray([new CityViewModel()]);
}
var CityViewModel = function(){
this.name = ko.observable();
this.streets = ko.observableArray([new StreetViewModel()]);
}
var StreetViewModel = function(){
this.number = ko.observable();
}
</code></pre>
<p>Is it possible, with the given data structure and using knockout's mapping plugin, to have the resulting StateViewModel contain an observableArray populated with 2 CityViewModels, and each CityViewModel containing an observableArray populated with 2 StreetViewModels?</p>
<p>Currently using the mapping plugin I'm able to get it to map to a StateViewModel, but the 'cities' and 'streets' collections are populated with generic objects instead of instances of my City and Street view models.</p>
<p>They end up with the correct observable properties and values on them, they're just not instances of my view models, which is what I'm after.</p> | 9,951,903 | 1 | 0 | null | 2012-03-30 23:18:21.41 UTC | 36 | 2015-04-20 18:45:15.367 UTC | 2015-04-20 18:45:15.367 UTC | null | 1,236,396 | null | 333,486 | null | 1 | 41 | json|knockout.js|knockout-mapping-plugin | 29,793 | <p>Check this <a href="http://jsfiddle.net/pTEbA/268/">http://jsfiddle.net/pTEbA/268/</a></p>
<pre><code>Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
function StateViewModel(data){
this.name = ko.observable();
ko.mapping.fromJS(data, mapping, this);
}
function CityViewModel(data) {
this.name = ko.observable();
ko.mapping.fromJS(data, mapping, this);
}
function StreetViewModel(data) {
this.name = ko.observable();
ko.mapping.fromJS(data, mapping, this);
}
var mapping = {
'cities': {
create: function(options) {
return new CityViewModel(options.data);
}
},
'streets': {
create: function(options) {
return new StreetViewModel(options.data);
}
}
}
var data = { state: {name:'SD', cities:[{name:'Sioux Falls',streets:[{number:1},{number:3}]},
{name:'Rapid City',streets:[{number:2},{number:4}]}]}};
var vm = new StateViewModel(data.state)
console.log(vm);
console.log(vm.getName());
console.log(vm.cities());
console.log(vm.cities()[0].getName());
console.log(vm.cities()[0].streets());
console.log(vm.cities()[0].streets()[0].getName());
</code></pre> |
9,840,629 | Create a file if one doesn't exist - C | <p>I want my program to open a file if it exists, or else create the file. I'm trying the following code but I'm getting a debug assertion at freopen.c. Would I be better off using fclose and then fopen immediately afterward?</p>
<pre><code>FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
freopen("scores.dat", "wb", fptr);
}
</code></pre> | 9,840,678 | 2 | 1 | null | 2012-03-23 14:09:07.067 UTC | 21 | 2016-08-18 11:27:15.557 UTC | 2013-10-07 21:46:33.973 UTC | null | 1,262,806 | null | 1,262,806 | null | 1 | 47 | c|fopen|fclose|freopen | 243,108 | <p>You typically have to do this in a single syscall, or else you will get a race condition.</p>
<p>This will open for reading and writing, creating the file if necessary.</p>
<pre><code>FILE *fp = fopen("scores.dat", "ab+");
</code></pre>
<p>If you want to read it and then write a new version from scratch, then do it as two steps.</p>
<pre><code>FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
</code></pre> |
28,026,648 | How to improve Dart performance of data conversion to/from binary? | <p>Doing some consulting work for a bigger German companies Future Technologies Group I have ported about 6000 lines of Java server side software to Dart. This should help to answer the question whether Dart can efficiently be used on the server. (Which itself would give a green light for Dart due to the searched for advantage of having one language for client and server side programming.)</p>
<p>Learning about Dart (which I really enjoyed working with) gave me an expectation of a performance penalty of 30-50% relative to Java but in any case no worse than 100% (twice as slow) which is the cutoff for the decision process mentioned above.</p>
<p>The port went smoothly. I learned a lot. Unit tests were fine. But the performance turned out to be extremly bad ... SEVEN times slower overall compared to the Java program.</p>
<p>Profiling the code revealed two main culprits: data conversion and file I/O. Maybe I'm doing something wrong? Before I go back to my client and they cancel their Dart research I would like to search some advice on how to improve things. Let's start with data conversion, the conversion of native Dart data types into various binary formats which can be used for effective transfer and storage of data.</p>
<p>Usually these conversions are simple and very fast because nothing has really to be converted from the used internal format but mostly stored into a buffer. I created a benchmark program which somehow reflects the typical use of these conversions in my program:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:typed_data';
import 'package:benchmark_harness/benchmark_harness.dart';
// Create a new benchmark by extending BenchmarkBase
class ConversionBenchmark extends BenchmarkBase {
Uint8List result;
ConversionBenchmark() : super("Conversion");
// The benchmark code.
void run() {
const int BufSize = 262144; // 256kBytes
const int SetSize = 64; // one "typical" set of data, gets repeated
ByteData buffer = new ByteData(BufSize);
double doubleContent = 0.0; // used to simulate double content
int intContent = 0; // used to simulate int content
int offset = 0;
for (int j = 0; j < buffer.lengthInBytes / SetSize; j++) {
// The following represents some "typical" conversion mix:
buffer.setFloat64(offset, doubleContent); offset += 8; doubleContent += 0.123;
for (int k = 0; k < 8; k++) { // main use case
buffer.setFloat32(offset, doubleContent); offset += 4; doubleContent += 0.123;
}
buffer.setInt32(offset, intContent); offset += 4; intContent++;
buffer.setInt32(offset, intContent); offset += 4; intContent++;
buffer.setInt16(offset, intContent); offset += 2; intContent++;
buffer.setInt16(offset, intContent); offset += 2; intContent++;
buffer.setInt8(offset, intContent); offset += 1; intContent++;
buffer.setInt8(offset, intContent); offset += 1; intContent++;
buffer.buffer.asUint8List(offset).setAll(0, "AsciiStrng".codeUnits); offset += 10;
// [ByteData] knows no other mechanism to transfer ASCII strings in
assert((offset % SetSize) == 0); // ensure the example content fits [SetSize] bytes
}
result = buffer.buffer.asUint8List(); // only this can be used for further processing
}
}
main() {
new ConversionBenchmark().report();
}
</code></pre>
<p>It is based on the benchmark harness from <a href="https://github.com/dart-lang/benchmark_harness">https://github.com/dart-lang/benchmark_harness</a>. For comparisions I used the following Java program based on a port of the Dart benchmark harness from <a href="https://github.com/bono8106/benchmark_harness_java">https://github.com/bono8106/benchmark_harness_java</a>:</p>
<pre class="lang-dart prettyprint-override"><code>package ylib.tools;
import java.nio.ByteBuffer;
public class ConversionBenchmark extends BenchmarkBase {
public ByteBuffer result;
public ConversionBenchmark() { super("Conversion"); }
// The benchmark code.
@Override protected void run() {
final int BufSize = 262144; // 256kBytes
final int SetSize = 64; // one "typical" set of data, gets repeated
ByteBuffer buffer = ByteBuffer.allocate(BufSize);
double doubleContent = 0.0; // used to simulate double content
int intContent = 0; // used to simulate int content
for (int j = 0; j < (buffer.capacity() / SetSize); j++) {
// The following represents some "typical" conversion mix:
buffer.putDouble(doubleContent); doubleContent += 0.123;
for (int k = 0; k < 8; k++) { // main use case
buffer.putFloat((float)doubleContent); doubleContent += 0.123;
}
buffer.putInt(intContent); intContent++;
buffer.putInt(intContent); intContent++;
buffer.putShort((short)intContent); intContent++;
buffer.putShort((short)intContent); intContent++;
buffer.put((byte)intContent); intContent++;
buffer.put((byte)intContent); intContent++;
buffer.put("AsciiStrng".getBytes());
//assert((buffer.position() % SetSize) == 0); // ensure the example content fits [SetSize] bytes
}
buffer.flip(); // needed for further processing
result = buffer; // to avoid the compiler optimizing away everything
}
public static void main(String[] args) {
new ConversionBenchmark().report();
}
}
</code></pre>
<p>The Java code runs almost exactly 10 times faster than the Dart code on my Intel Windows 7 machine. Both run in production mode on their respective VMs.</p>
<p>Is there an obvious error in the code? Or are there different Dart classes available to do the job? Any explanation as to why Dart is so much slower with these simple conversions? Or do I have completely wrong expectations with respect to Dart VM performance?</p> | 28,036,176 | 2 | 7 | null | 2015-01-19 14:16:17.913 UTC | 9 | 2015-01-23 16:12:34.49 UTC | 2015-01-19 20:32:56.57 UTC | null | 2,862,220 | null | 2,862,220 | null | 1 | 21 | performance|dart|data-conversion | 1,861 | <p>It is true that performance of byte data methods (<code>ByteData.setXYZ</code> and <code>ByteData.getXYZ</code>) is pretty bad on Dart VM compared to direct typed array access. We started working on the issue and initial results are promising[1].</p>
<p>In the mean time you can work around this unfortunate performance regression by rolling your own conversion to big endian using typed arrays (full code at[2]):</p>
<pre class="lang-dart prettyprint-override"><code>/// Writer wraps a fixed size Uint8List and writes values into it using
/// big-endian byte order.
class Writer {
/// Output buffer.
final Uint8List out;
/// Current position within [out].
var position = 0;
Writer._create(this.out);
factory Writer(size) {
final out = new Uint8List(size);
if (Endianness.HOST_ENDIAN == Endianness.LITTLE_ENDIAN) {
return new _WriterForLEHost._create(out);
} else {
return new _WriterForBEHost._create(out);
}
}
writeFloat64(double v);
}
/// Lists used for data convertion (alias each other).
final Uint8List _convU8 = new Uint8List(8);
final Float32List _convF32 = new Float32List.view(_convU8.buffer);
final Float64List _convF64 = new Float64List.view(_convU8.buffer);
/// Writer used on little-endian host.
class _WriterForLEHost extends Writer {
_WriterForLEHost._create(out) : super._create(out);
writeFloat64(double v) {
_convF64[0] = v;
out[position + 7] = _convU8[0];
out[position + 6] = _convU8[1];
out[position + 5] = _convU8[2];
out[position + 4] = _convU8[3];
out[position + 3] = _convU8[4];
out[position + 2] = _convU8[5];
out[position + 1] = _convU8[6];
out[position + 0] = _convU8[7];
position += 8;
}
}
</code></pre>
<p>Benchmarking this manual conversion on your test yields around 6x improvement:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:typed_data';
import 'package:benchmark_harness/benchmark_harness.dart';
import 'writer.dart';
class ConversionBenchmarkManual extends BenchmarkBase {
Uint8List result;
ConversionBenchmarkManual() : super("Conversion (MANUAL)");
// The benchmark code.
void run() {
const int BufSize = 262144; // 256kBytes
const int SetSize = 64; // one "typical" set of data, gets repeated
final w = new Writer(BufSize);
double doubleContent = 0.0; // used to simulate double content
int intContent = 0; // used to simulate int content
int offset = 0;
for (int j = 0; j < (BufSize / SetSize); j++) {
// The following represents some "typical" conversion mix:
w.writeFloat64(doubleContent); doubleContent += 0.123;
for (int k = 0; k < 8; k++) { // main use case
w.writeFloat32(doubleContent); doubleContent += 0.123;
}
w.writeInt32(intContent); intContent++;
w.writeInt32(intContent); intContent++;
w.writeInt16(intContent); intContent++;
w.writeInt16(intContent); intContent++;
w.writeInt8(intContent); intContent++;
w.writeInt8(intContent); intContent++;
w.writeString("AsciiStrng");
assert((offset % SetSize) == 0); // ensure the example content fits [SetSize] bytes
}
result = w.out; // only this can be used for further processing
}
}
</code></pre>
<p>[1] <a href="https://code.google.com/p/dart/issues/detail?id=22107" rel="noreferrer">https://code.google.com/p/dart/issues/detail?id=22107</a></p>
<p>[2] <a href="https://gist.github.com/mraleph/4eb5ccbb38904075141e" rel="noreferrer">https://gist.github.com/mraleph/4eb5ccbb38904075141e</a> </p> |
9,855,955 | Xcode-Increment build number only during ARCHIVE? | <p>I have found a few other posts that show how to add a script to increment the build number with a script:</p>
<p><a href="https://stackoverflow.com/questions/9258344/xcode-better-way-of-incrementing-build-number">Better way of incrementing build number?</a></p>
<p><a href="https://stackoverflow.com/questions/7371345/xcode-projects-build-number">Xcode project's "Build number"</a></p>
<p><a href="https://stackoverflow.com/questions/4694070/can-xcode-insert-the-version-number-into-a-librarys-filename-when-building">Can Xcode insert the version number into a library's filename when building?</a></p>
<p>But what I want to do, is only increase the build number when I use ARCHIVE (both before and after).</p>
<p>Example:
If current build number is 21, then when I choose Product > Archive the build number will be increased to 22, it will go through its process of building and creating the Archive file with the build number of 22, and then when it is finished archiving, it will increase the build number to 23.</p> | 9,856,402 | 3 | 3 | null | 2012-03-24 21:53:46.057 UTC | 32 | 2020-03-09 08:06:44.11 UTC | 2017-05-23 12:17:44.467 UTC | null | -1 | null | 570,759 | null | 1 | 56 | xcode|macos|xcode4|xcode4.2|osx-lion | 14,313 | <p>Add the following script, as in the example listed in the first link that you posted, BUT do it twice. Once at the beginning of the build and once at the end:</p>
<pre><code>if [ $CONFIGURATION == Release ]; then
echo "Bumping build number..."
plist=${PROJECT_DIR}/${INFOPLIST_FILE}
# increment the build number (ie 115 to 116)
buildnum=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${plist}")
if [[ "${buildnum}" == "" ]]; then
echo "No build number in $plist"
exit 2
fi
buildnum=$(expr $buildnum + 1)
/usr/libexec/Plistbuddy -c "Set CFBundleVersion $buildnum" "${plist}"
echo "Bumped build number to $buildnum"
else
echo $CONFIGURATION " build - Not bumping build number."
fi
</code></pre>
<p>Many thanks to the authors of the questions that you have linked to in your question for the information that got me started on this answer! </p> |
10,140,999 | CSV with comma or semicolon? | <p>How is a CSV file built in general? With commas or semicolons?
Any advice on which one to use?</p> | 10,141,147 | 10 | 3 | null | 2012-04-13 12:39:07.617 UTC | 16 | 2017-08-02 17:48:31.647 UTC | 2015-06-18 14:47:58.41 UTC | null | 13,295 | null | 1,194,415 | null | 1 | 99 | csv | 290,847 | <p>In Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.</p>
<p>Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.</p>
<p>If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is <code>,</code>, then go for it, otherwise I prefer <code>;</code> since it causes less problems with decimal points, digit grouping and does not appear in much text.</p> |
8,086,363 | List of JSON search engine APIs without quotas, like Bing? | <p>I'd like to display some custom search results.</p>
<p>I've looked at the JSON APIs of both Google and Microsoft (Bing). Unfortunately, Google has a limit on the amount of queries a day ($50 for a maximum of ten thousand queries). However, Bing allows an "unlimited" amount of queries a day, for free.</p>
<p>Are there other services, like Bing's JSON API, that do not have a query limit like Google's API?</p>
<p>A related question might be how services like Metacrawler can combine search results from several search engines, while the terms of services of these engines clearly state that these results may only be obtained through such (paid) API, and not through crawling.</p> | 8,157,344 | 3 | 2 | null | 2011-11-10 21:12:56.067 UTC | 8 | 2013-12-12 01:58:10.44 UTC | 2013-12-12 01:58:10.44 UTC | null | 881,229 | null | 45,974 | null | 1 | 24 | search-engine|google-search|bing | 22,498 | <p>Usually services and APIs have usage threshold, so as to enable experimentation and small-scale use without any hurdles and up-front obstacles, but open up possibility of offering better SLA and additional options with paid usage for apps that need that level of support.</p>
<p>That said looking on programmableweb.com for search APIs is probably an interesting option - see <a href="http://www.programmableweb.com/apis/directory/1?apicat=Search" rel="noreferrer">http://www.programmableweb.com/apis/directory/1?apicat=Search</a>.</p>
<p>I am also curious, what you're specifically looking for in terms of capabilities, what you'd like to see in the Bing API etc. Any feedback and I can relay to the team (since I am on the Bing team).</p> |
7,888,387 | The way to distinguish command-mode and insert-mode in Bash's Vi command line editing | <p>I'm always little bit confused when bash in vi-mode is switched to insert-mode, because it doesn't give any tip about used mode (command or edit).
Is there any way to distinguish mods? May be automatic change of cursor color or something like that?</p> | 32,614,367 | 3 | 5 | null | 2011-10-25 11:12:05.22 UTC | 22 | 2017-02-08 08:06:30.763 UTC | 2011-10-25 11:39:34.37 UTC | null | 998,523 | null | 998,523 | null | 1 | 63 | bash|vi|command-line-interface | 21,239 | <p>in /etc/inputrc (or ~/.inputrc) add this:</p>
<pre><code>set show-mode-in-prompt on
</code></pre>
<p>this will prefix your prompt with <b>+</b> while in insert-mode, and <b>:</b> while in command mode in bash 4.3</p>
<p><strong>EDIT:</strong>
in the latest version of bash 4.4, you will instead get a prompt prefixed with "(ins)" or "(cmd)" by default. but, you can change that:</p>
<pre><code>set vi-ins-mode-string "+"
set vi-cmd-mode-string ":"
</code></pre>
<p>also, you can use color codes like '\e[1;31m', but surround them with '\1' and '\2' to keep readline happy:</p>
<pre><code>set vi-cmd-mode-string "\1\e[1;31m\2:\1\e[0m\2"
</code></pre> |
11,961,331 | how to make form ignore password fields if blank (symfony2 forms) | <p>I have a simple user manager in my backend, and I want to be able to edit the user without setting a new password/repeating the old password every time.</p>
<p>Right now if I leave the password fields blank when editing a user, symfony2 complains that a password must be entered, and of course I want this functionality when I register new users, but when I edit them, I'd like for the form to just ignore the password boxes if they aren't filled out.</p>
<p>How is this accomplished?</p> | 12,013,202 | 8 | 0 | null | 2012-08-14 21:50:14.163 UTC | 9 | 2020-09-08 22:06:46.963 UTC | null | null | null | null | 942,230 | null | 1 | 20 | php|forms|symfony | 16,160 | <p>For someone else's reference, I worked this one out this way.</p>
<p>My formType:</p>
<pre><code>public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('username', 'text', array('label' => 'Servernamn '))
->add('plainPassword', 'repeated', array('type' => 'password', 'first_name' => 'Lösenord för server ', 'second_name' => 'Upprepa lösenord för server',));
$builder-> addValidator(new CallbackValidator(function(FormInterface $form){
$username = $form->get('username')->getData();
if (empty($username)) {
$form['username']->addError(new FormError("Du måste ange ett namn för servern"));
}
}));
}
</code></pre>
<p>My updateAction:</p>
<pre><code>public function updateServerAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('BizTVUserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Container entity.');
}
$originalPassword = $entity->getPassword();
$editForm = $this->createForm(new editServerType(), $entity);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$plainPassword = $editForm->get('plainPassword')->getData();
if (!empty($plainPassword)) {
//encode the password
$encoder = $this->container->get('security.encoder_factory')->getEncoder($entity); //get encoder for hashing pwd later
$tempPassword = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
$entity->setPassword($tempPassword);
}
else {
$entity->setPassword($originalPassword);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('Server'));
}
</code></pre>
<p>Thus updating my users password should it be set, otherwise keep the original password.</p> |
11,996,823 | Cakephp check if record exists | <p>I am wondering, is there a function that allows me to check instantly if a record in the database exists?</p>
<p>Right now I am using the following piece of code to detect if a record exists, but I can imagine there is a simpler/better way.</p>
<pre><code>$conditions = array(
'conditions' => array(
'User.id' => $this->Session->read('User.id'),
'User.activation_key' => $this->Session->read('User.key')
)
);
$result = $this->User->find('first', $conditions);
if (isset($result['User'])){
//do something
}
</code></pre>
<p>Is there something like:</p>
<pre><code>$conditions = array(
'conditions' => array(
'User.id' => $this->Session->read('User.id'),
'User.security_key' => $this->Session->read('User.key')
)
);
if ($this->User->exists($conditions)){
//do something
}
</code></pre>
<p>Okay, yes there is. It's called <code>exists()</code>, but I need the same, but with parameters, so I can add my own conditions to the check.</p>
<p>I have searched google, but I can't find any topic about this. Well, a lot about php and mysql, but not about cakephp. I need a cake specific answer. </p>
<p>Thanks for your time :)</p> | 11,996,931 | 1 | 0 | null | 2012-08-16 23:25:08.41 UTC | 10 | 2018-01-22 14:29:18.573 UTC | 2018-01-22 14:29:18.573 UTC | null | 7,040,040 | null | 1,110,760 | null | 1 | 37 | php|cakephp | 42,498 | <p>What you are looking for is <a href="http://api.cakephp.org/2.3/class-Model.html#_hasAny">Model::hasAny</a></p>
<p>Usage:</p>
<pre><code>$conditions = array(
'User.id' => $this->Session->read('User.id'),
'User.security_key' => $this->Session->read('User.key')
);
if ($this->User->hasAny($conditions)){
//do something
}
</code></pre> |
20,245,053 | Running Microsoft Access as a Scheduled Task | <p>I am seeking comments on how to schedule auto updates of a database (.accdb) since I am not very comfortable with the process I have set up.</p>
<p>Currently, it works as follow:</p>
<ol>
<li>Task Scheduler calls a .bat</li>
<li>.bat calls a .vbs</li>
<li>.vbs opens the database and calls a macro</li>
<li>The macro calls a function (VBA Level)</li>
<li>The function calls the update Subroutine</li>
</ol>
<p>I consider there are too many steps and the fact that it requires 2 external files (.Bat and .vbs) related to the database and stored on the system increase the risk that the procedure would break.</p>
<p>Apparently (but please tell me that I am wrong and how I can change it) .vbs cannot call a subroutine but only a macro. Identically, an access macro cannot call a subroutine but only a function if the user is expecting to enter the VB environment of the database. This is the reason why I called a function (VBA Level) that then calls the subroutine.</p>
<p>Hope some of you know how to shorten the steps and eventually get ride of the .bat and .vbs</p> | 20,251,788 | 5 | 5 | null | 2013-11-27 14:27:57.38 UTC | 8 | 2022-06-28 05:50:09.727 UTC | 2013-11-27 20:05:41.963 UTC | null | 2,144,390 | null | 2,830,928 | null | 1 | 16 | ms-access|batch-file|vbscript|auto-update | 68,630 | <p>To the best of my knowledge the shortest path for a Windows Scheduled Task to "do something useful in Access VBA" is:</p>
<p>Create a Public Function (not Sub) in the database. For example:</p>
<pre class="lang-vbs prettyprint-override"><code>Option Compare Database
Option Explicit
Public Function WriteToTable1()
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute "INSERT INTO Table1 (textCol) VALUES ('sched test')", dbFailOnError
Set cdb = Nothing
Application.Quit
End Function
</code></pre>
<p>Create a Macro in the database to invoke the function:</p>
<p><img src="https://i.stack.imgur.com/AWXyq.png" alt="Macro.png"></p>
<p>Create a Windows Scheduled Task to invoke MSACCESS.EXE with the appropriate parameters</p>
<p><img src="https://i.stack.imgur.com/rX1QF.png" alt="SchedTask.png"></p>
<p>In the above dialog box the values are:</p>
<p>Program/script:</p>
<pre class="lang-none prettyprint-override"><code>"C:\Program Files\Microsoft Office\Office14\MSACCESS.EXE"
</code></pre>
<p>Add arguments <strike>(optional)</strike>:</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\Public\schedTest.accdb /x DoSomething
</code></pre> |
3,715,644 | Key value pairs using JSON | <p>Is there a way to handle data structures using JSON object in a way of Key/ Value pairs?<br>
If so can some one elaborate how to access associated value object from the key </p>
<p>Assume that I have something like this </p>
<pre><code>KEY1 | VALUE OBJECT1 - (NAME: "XXXXXX", VALUE:100.0)
KEY2 | VALUE OBJECT2 - (NAME: "YYYYYYY", VALUE:200.0)
KEY3 | VALUE OBJECT3 - (NAME: "ZZZZZZZ", VALUE:500.0)
</code></pre> | 3,715,798 | 4 | 1 | null | 2010-09-15 07:50:31.577 UTC | 13 | 2017-01-04 23:10:40.407 UTC | 2010-09-15 07:57:20.273 UTC | null | 75,525 | null | 438,877 | null | 1 | 18 | javascript|jquery|json | 147,021 | <p>A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.</p>
<p>The JSON for that would look like this:</p>
<pre><code>{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}
</code></pre>
<p>Once you have parsed the JSON into a Javascript object (called <code>data</code> in the code below), you can for example access the object for <code>KEY2</code> and it's properties like this:</p>
<pre><code>var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);
</code></pre>
<p>If you have the key as a string, you can use index notation:</p>
<pre><code>var key = 'KEY3';
var obj = data[key];
</code></pre> |
3,349,677 | What are some practical projects to consider in trying to learn C? | <p>I've seen a lot of questions and answers on SO about why I should learn C. I know that it's low level, it'll give me an understanding of how things work at that level, and it'll make me a better programmer. I know some good books to be reading to help me learn C.</p>
<p>What I don't feel like I know are some practical projects I can work on to help me learn how the language is used. There's a lot of examples in the books I'm reading, and they're absolutely useful as far as reinforcing knowledge gained about the language itself. But I don't feel as if I'm gaining any insight into "real life" examples of what I can do with C.</p>
<p>My background: I'm a recent college grad who's doing application programming in C#. I'm enjoying doing programming exercises in C -- but I just feel like they're exercises. I know obviously I'm not going to become an expert right away and start doing amazing things. I just want some ideas for things I can do to help me become better but that feel like more than just exercises. (I want to clarify that I'm not opposed to doing these kinds of tasks to help me learn about the language. I just think I'd get more excited about learning if I was doing something that seemed more practical in nature.)</p>
<p>If this is "not a real question," I truly do apologize, and I know questions about learning C are all over SO. I'm not trying to be repetitive. I'm sold on the idea that I should learn the language, I just want to be able to have some real ideas of how I can start applying the knowledge.</p>
<h2>See Also</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/2220920/what-is-a-good-first-c-app-to-build-besides-hello-world">What is a good first C app to build, besides “Hello World”</a></li>
</ul> | 3,349,728 | 6 | 0 | null | 2010-07-28 03:22:24.297 UTC | 14 | 2010-08-02 02:37:16.28 UTC | 2017-05-23 12:10:19.847 UTC | null | -1 | null | 374,825 | null | 1 | 21 | c | 3,384 | <p>Here's some ideas for you to try:</p>
<ol>
<li>Store a file containing hashes of every file in your music directory, and report on changes.</li>
<li>Solve a Sudoku in the shortest possible time.</li>
<li>Send a file using TCP to another computer. (Write both server and client).</li>
<li>A program that broadcasts a list of public files (configured in a text file) over UDP, and then accepts TCP connections to download them.</li>
<li>A command line POP3 client.</li>
<li>Write a memory allocator, and hook into <code>malloc</code>.</li>
</ol>
<p>Congratulations on deciding to learn C. It is the most powerful language on Earth, and will give you the foundation you need to kick some programming butt.</p> |
3,961,730 | How to break a line in vim in normal mode? | <p>I would like to break a line (at the location of the cursor) in to two lines without leaving normal mode (entering insert or command-line mode). Is this possible?</p>
<p>I currently get to the location I want and hit 'i' to enter insert mode, 'enter' to break the line in two, then 'esc' to return to normal mode.</p>
<p>I am not trying to set a maximum line length or do any syntax or anything like that. I just want to break one line into two lines without leaving normal mode. 'J' joins the line the cursor is on to the line below it, which is handy. I want the opposite -- to break one line into two with a single command.</p> | 3,961,777 | 8 | 0 | null | 2010-10-18 17:35:56.643 UTC | 13 | 2020-07-02 21:17:21.837 UTC | null | null | null | null | 463,456 | null | 1 | 53 | vim|macvim | 18,553 | <p>Try this:</p>
<pre><code>:nnoremap <NL> i<CR><ESC>
</code></pre>
<p>then just press Ctrl-J whenever you want to split a line.</p> |
3,358,420 | Generating a SHA-256 hash from the Linux command line | <p>I know the string "foobar" generates the SHA-256 hash <code>c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2</code> using
<a href="http://hash.online-convert.com/sha256-generator" rel="noreferrer">http://hash.online-convert.com/sha256-generator</a></p>
<p>However the command line shell:</p>
<pre><code>hendry@x201 ~$ echo foobar | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f -
</code></pre>
<p>Generates a different hash. What am I missing?</p> | 3,358,428 | 8 | 3 | null | 2010-07-28 23:41:05.637 UTC | 67 | 2022-08-11 16:18:42.023 UTC | 2020-05-31 12:04:14.667 UTC | null | 63,550 | null | 4,534 | null | 1 | 318 | linux|shell|sha256 | 409,312 | <p><code>echo</code> will normally output a newline, which is suppressed with <code>-n</code>. Try this:</p>
<pre><code>echo -n foobar | sha256sum
</code></pre> |
3,535,722 | Eclipse won't compile, bad class file, wrong version | <p>I am trying to compile code checked out of SVN from another developer. Eclipse has been giving me a lot of trouble lately.</p>
<p>Here are my project-specific settings:
<img src="https://i.stack.imgur.com/Xogi8.jpg" alt="alt text"></p>
<p>This is what the compile section of my ant file:</p>
<pre><code><target name="compile" depends="build-common, init" description="Compile files. ">
<javac srcdir="${src_dir}" destdir="${build_dir}" debug="true" >
<classpath path="${tomcat_home}/lib/servlet-api.jar;" />
</javac>
</target>
</code></pre>
<p>When I compile ( using Ant ) I get an error message:</p>
<pre><code>compile:
[javac] Compiling 3 source files to H:\MYCOMPANY\portlets\build
[javac] H:\MYCOMPANY\portlets\src\com\mycompany\portlets\CourseList.java:3: cannot access java.io.IOException
[javac] bad class file: C:\Program Files\Java\jre1.6.0_07\lib\rt.jar(java/io/IOException.class)
[javac] class file has wrong version 49.0, should be 48.0
[javac] Please remove or make sure it appears in the correct subdirectory of the classpath.
[javac] import java.io.IOException;
[javac] ^
[javac] 1 error
</code></pre>
<p>What does this error mean? </p> | 3,535,747 | 9 | 0 | null | 2010-08-21 00:22:15.987 UTC | 1 | 2016-01-19 18:14:54.27 UTC | 2010-08-23 22:00:27.603 UTC | null | 28,351 | null | 28,351 | null | 1 | 8 | java|eclipse | 43,165 | <p>The class file version of 49.0 belongs to Java 1.5.x, whereas the one of 48.0 belongs to one of the Java 1.4.x version. The classfile structure had changed in 1.5 due to the introduction of several new features and changes made in the Java Language Specification.</p>
<p>From the error, one can deduce that a Java 1.4 classfile was expected, whereas a Java 1.5 classfile was found. It appears that the compiler is a Java 1.4 compiler, so you should attempt to verify whether you're using the right version of the Java compiler and also the right JDK (i.e. JDK home).</p>
<p><strong>ADDENDUM</strong></p>
<p>Ant tends to look for the javac executable in the $JAVA_HOME/bin/javac . If the JAVA_HOME environment variable has been set incorrectly, say to a Java 1.4 home, then there is a likelihood of getting the described error even in Eclipse.</p>
<p><strong>ADDENDUM #2</strong></p>
<p>The addition of entries to the PATH environment variable <em>could result</em> in altering the search classpath behavior of Ant, possibly resulting in a different tools.jar being used for the purpose of compiling the sources. This might be due to the jvm.dll from the JRE 1.4.2 installation being used to run Eclipse (and hence Ant).</p> |
3,773,396 | Declare variables at top of function or in separate scopes? | <p>Which is preferred, method 1 or method 2?</p>
<h3>Method 1:</h3>
<pre><code>LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
}
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
</code></pre>
<h3>Method 2:</h3>
<pre><code>LRESULT CALLBACK wpMainWindow(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rc;
switch (msg)
{
case WM_PAINT:
GetClientRect(hwnd, &rc);
hdc = BeginPaint(hwnd, &ps);
// drawing here
EndPaint(hwnd, &ps);
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
return 0;
}
</code></pre>
<p>In method 1, if msg = WM_PAINT when wpMainWindow function is called, does it allocate memory for all the variables on the stack at the beginning? or only when it enters the WM_PAINT scope?</p>
<p>Would method 1 only use the memory when the message is WM_PAINT, and method 2 would use the memory no matter what msg equaled?</p> | 3,773,458 | 9 | 5 | null | 2010-09-22 20:33:39.94 UTC | 26 | 2014-12-03 18:34:59.027 UTC | 2010-09-22 20:56:34.673 UTC | null | 15,168 | null | 394,242 | null | 1 | 48 | c++|c|function|stack | 30,656 | <p>Variables should be declared as locally as possible.</p>
<p>Declaring variables "at the top of the function" is always a disastrously bad practice. Even in C89/90 language, where variables can only be declared at the beginning of the block, it is better to declare them as locally as possible, i.e. at the beginning of smallest local block that covers the desired lifetime of the variable. Sometimes it might even make sense to introduce a "redundant" local block with the only purpose of "localizing" the variable declaration.</p>
<p>In C++ and C99, where it is possible to declare variable anywhere in the code, the answer is pretty straightforward: again, declare each variable as locally as possible, and as close as possible to the point where you use it the very first time. The primary rationale for that is that in most cases this will allow you to supply a meaningful initializer to the variable at the point of declaration (instead of declaring it without initializer or with a dummy initializer).</p>
<p>As for the memory usage, in general a typical implementation will immediately (as you enter the function) allocate the maximum space required for all variables that exist at the same time. However, your declaration habits might affect the exact size of that space. For example, in this code</p>
<pre><code>void foo() {
int a, b, c;
if (...) {
}
if (...) {
}
}
</code></pre>
<p>all three variables exist at the same time and generally the space for all three has to be allocated. But in this code</p>
<pre><code>void foo() {
int a;
if (...) {
int b;
}
if (...) {
int c;
}
}
</code></pre>
<p>only two variables exist at any given moment, meaning that space for only two variables will be allocated by a typical implementation (<code>b</code> and <code>c</code> will share the same space). This is another reason to declare variables as locally as possible.</p> |
8,202,048 | org.json.JSON Exception : End of input at character 0 | <p>I'm trying to parse json from android but I get this strange exception. My json data is</p>
<blockquote>
<p>{"id":"1","owner":"1","name":"gravitas","description":"is a fest","start_time":"0000-00-00 00:00:00","end_time":"0000-00-00 00:00:00","venue":"vellore","radius":"10","lat":"11","lng":"11","type":"type","ownername":"dilip","noofpolls":0,"noofquizes":0,"peopleattending":0,"result":true} </p>
</blockquote>
<p>and in android I do </p>
<pre><code>JSONObject j =new JSONObject(response);
Event pst = gson.fromJson(j.toString(), Event.class);
</code></pre>
<p>I get:</p>
<pre><code>org.json.JSONException: end of input at character 0 of
</code></pre>
<p>What's wrong with it? Here is the code...</p>
<pre><code>RestClient client = new RestClient("http://192.168.1.3/services/events/"+eve.getName());
try {
Log.i("MY INFO", "calling boston");
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("MY INFO", response);
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Event pst = null;
try {
JSONObject j =new JSONObject(response);
pst = gson.fromJson(j.toString(), Event.class);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code></pre> | 8,214,974 | 4 | 0 | null | 2011-11-20 14:09:39.663 UTC | 1 | 2019-12-06 08:44:01.657 UTC | 2016-11-15 13:39:44.093 UTC | null | 3,678,528 | null | 287,969 | null | 1 | 11 | android|json | 51,282 | <p>Oops! my bad I was supposed to use GET method.that url doesn't respond to POST requests so I was getting the org.json.JSON Exception : End of input at character 0.its because of this I got null response which generated that exception.</p> |
7,743,534 | Filter (search and replace) array of bytes in an InputStream | <p>I have an InputStream which takes the html file as input parameter. I have to get the bytes from the input stream .</p>
<p>I have a string: <code>"XYZ"</code>. I'd like to convert this string to byte format and check if there is a match for the string in the byte sequence which I obtained from the InputStream. If there is then, I have to replace the match with the bye sequence for some other string.</p>
<p>Is there anyone who could help me with this? I have used regex to find and replace. however finding and replacing byte stream, I am unaware of.</p>
<p>Previously, I use jsoup to parse html and replace the string, however due to some utf encoding problems, the file seems to appear corrupted when I do that.</p>
<p><strong>TL;DR: My question is:</strong></p>
<p>Is a way to find and replace a string in byte format in a raw InputStream in Java?</p> | 7,743,665 | 6 | 4 | null | 2011-10-12 16:44:31.687 UTC | 8 | 2022-04-15 05:17:03.033 UTC | 2014-11-28 11:50:38.477 UTC | null | 1,704,567 | user471450 | null | null | 1 | 24 | java|input|bytearray | 43,314 | <p>Not sure you have chosen the best approach to solve your problem.</p>
<p>That said, I don't like to (and have as policy not to) answer questions with "don't" so here goes...</p>
<p>Have a look at <a href="http://download.oracle.com/javase/6/docs/api/java/io/FilterInputStream.html" rel="noreferrer"><code>FilterInputStream</code></a>.</p>
<p>From the documentation:</p>
<blockquote>
<p>A FilterInputStream contains some other input stream, which it uses as its basic source of data, <strong>possibly transforming the data along the way</strong> or providing additional functionality. </p>
</blockquote>
<hr>
<p>It was a fun exercise to write it up. Here's a complete example for you:</p>
<pre><code>import java.io.*;
import java.util.*;
class ReplacingInputStream extends FilterInputStream {
LinkedList<Integer> inQueue = new LinkedList<Integer>();
LinkedList<Integer> outQueue = new LinkedList<Integer>();
final byte[] search, replacement;
protected ReplacingInputStream(InputStream in,
byte[] search,
byte[] replacement) {
super(in);
this.search = search;
this.replacement = replacement;
}
private boolean isMatchFound() {
Iterator<Integer> inIter = inQueue.iterator();
for (int i = 0; i < search.length; i++)
if (!inIter.hasNext() || search[i] != inIter.next())
return false;
return true;
}
private void readAhead() throws IOException {
// Work up some look-ahead.
while (inQueue.size() < search.length) {
int next = super.read();
inQueue.offer(next);
if (next == -1)
break;
}
}
@Override
public int read() throws IOException {
// Next byte already determined.
if (outQueue.isEmpty()) {
readAhead();
if (isMatchFound()) {
for (int i = 0; i < search.length; i++)
inQueue.remove();
for (byte b : replacement)
outQueue.offer((int) b);
} else
outQueue.add(inQueue.remove());
}
return outQueue.remove();
}
// TODO: Override the other read methods.
}
</code></pre>
<h2>Example Usage</h2>
<pre><code>class Test {
public static void main(String[] args) throws Exception {
byte[] bytes = "hello xyz world.".getBytes("UTF-8");
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
byte[] search = "xyz".getBytes("UTF-8");
byte[] replacement = "abc".getBytes("UTF-8");
InputStream ris = new ReplacingInputStream(bis, search, replacement);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
while (-1 != (b = ris.read()))
bos.write(b);
System.out.println(new String(bos.toByteArray()));
}
}
</code></pre>
<p>Given the bytes for the string <code>"Hello xyz world"</code> it prints:</p>
<pre><code>Hello abc world
</code></pre> |
8,283,588 | How to remove `//<![CDATA[` and end `//]]>`? | <p>How can I remove the <code>(//<![CDATA[ , //]]></code>) blocks; tags inside a <code>script</code> element.</p>
<pre><code><script type="text/javascript">
//<![CDATA[
var l=new Array();
..........................
..........................
//]]>
</script>
</code></pre>
<p>Looks like it can be done with <code>preg_replace()</code> but havent found a solution that works for me. </p>
<p>What regex would I use?</p> | 8,283,600 | 8 | 3 | null | 2011-11-27 04:09:42.443 UTC | 3 | 2020-01-02 16:15:48.49 UTC | 2011-11-27 04:16:20.787 UTC | null | 31,671 | null | 334,452 | null | 1 | 14 | php|regex|preg-replace|cdata | 42,911 | <p>The following regex will do it...</p>
<pre><code>$removed = preg_replace('/^\s*\/\/<!\[CDATA\[([\s\S]*)\/\/\]\]>\s*\z/',
'$1',
$scriptText);
</code></pre>
<p><a href="http://codepad.org/4zOOYEEB" rel="noreferrer">CodePad</a>.</p> |
7,888,944 | What do all of Scala's symbolic operators mean? | <p>Scala syntax has a lot of symbols. Since these kinds of names are difficult to find using search engines, a comprehensive list of them would be helpful.</p>
<p>What are all of the symbols in Scala, and what does each of them do?</p>
<p>In particular, I'd like to know about <code>-></code>, <code>||=</code>, <code>++=</code>, <code><=</code>, <code>_._</code>, <code>::</code>, and <code>:+=</code>.</p> | 7,890,032 | 12 | 6 | null | 2011-10-25 12:00:11.723 UTC | 306 | 2022-07-14 20:19:49.097 UTC | 2016-04-12 07:00:14.997 UTC | null | 402,884 | null | 515,054 | null | 1 | 430 | scala|operators | 126,605 | <p>I divide the operators, for the purpose of teaching, into <strong>four categories</strong>:</p>
<ul>
<li>Keywords/reserved symbols</li>
<li>Automatically imported methods</li>
<li>Common methods</li>
<li>Syntactic sugars/composition</li>
</ul>
<p>It is fortunate, then, that most categories are represented in the question:</p>
<pre><code>-> // Automatically imported method
||= // Syntactic sugar
++= // Syntactic sugar/composition or common method
<= // Common method
_._ // Typo, though it's probably based on Keyword/composition
:: // Common method
:+= // Common method
</code></pre>
<p>The exact meaning of most of these methods depend on the class that is defining them. For example, <code><=</code> on <code>Int</code> means <em>"less than or equal to"</em>. The first one, <code>-></code>, I'll give as example below. <code>::</code> is probably the method defined on <code>List</code> (though it <em>could</em> be the object of the same name), and <code>:+=</code> is probably the method defined on various <code>Buffer</code> classes.</p>
<p>So, let's see them.</p>
<h2>Keywords/reserved symbols</h2>
<p>There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:</p>
<pre><code>// Keywords
<- // Used on for-comprehensions, to separate pattern from generator
=> // Used for function types, function literals and import renaming
// Reserved
( ) // Delimit expressions and parameters
[ ] // Delimit type parameters
{ } // Delimit blocks
. // Method call and path separator
// /* */ // Comments
# // Used in type notations
: // Type ascription or context bounds
<: >: <% // Upper, lower and view bounds
<? <! // Start token for various XML elements
" """ // Strings
' // Indicate symbols and characters
@ // Annotations and variable binding on pattern matching
` // Denote constant or enable arbitrary identifiers
, // Parameter separator
; // Statement separator
_* // vararg expansion
_ // Many different meanings
</code></pre>
<p>These are all <em>part of the language</em>, and, as such, can be found in any text that properly describe the language, such as <a href="http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/ScalaReference.pdf" rel="noreferrer">Scala Specification</a>(PDF) itself.</p>
<p>The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:</p>
<pre><code>import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
</code></pre>
<p>I probably forgot some other meaning, though.</p>
<h2>Automatically imported methods</h2>
<p>So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.</p>
<p>These <em>can still be found</em> on <a href="http://www.scala-lang.org/api/current/index.html" rel="noreferrer">ScalaDoc</a>: you just have to know where to look for them. Or, failing that, look at the <a href="http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#index.index-_" rel="noreferrer">index</a> (presently broken on 2.9.1, but available on nightly).</p>
<p>Every Scala code has three automatic imports:</p>
<pre><code>// Not necessarily in this order
import _root_.java.lang._ // _root_ denotes an absolute path
import _root_.scala._
import _root_.scala.Predef._
</code></pre>
<p>The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods, since <a href="http://www.scala-lang.org/api/current/index.html#scala.Predef$" rel="noreferrer"><code>Predef</code></a> is an object itself.</p>
<p>Looking inside <code>Predef</code> quickly show some symbols:</p>
<pre><code>class <:<
class =:=
object <%<
object =:=
</code></pre>
<p>Any other symbol will be made available through an <em>implicit conversion</em>. Just look at the methods tagged with <code>implicit</code> that receive, as parameter, an object of type that is receiving the method. For example:</p>
<pre><code>"a" -> 1 // Look for an implicit from String, AnyRef, Any or type parameter
</code></pre>
<p>In the above case, <code>-></code> is defined in the class <a href="http://www.scala-lang.org/api/current/scala/Predef$$ArrowAssoc.html" rel="noreferrer"><code>ArrowAssoc</code></a> through the method <code>any2ArrowAssoc</code> that takes an object of type <code>A</code>, where <code>A</code> is an unbounded type parameter to the same method.</p>
<h2>Common methods</h2>
<p>So, many symbols are simply methods on a class. For instance, if you do</p>
<pre><code>List(1, 2) ++ List(3, 4)
</code></pre>
<p>You'll find the method <code>++</code> right on the ScalaDoc for <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List" rel="noreferrer">List</a>. However, there's one convention that you must be aware when searching for methods. Methods ending in colon (<code>:</code>) bind <em>to the right</em> instead of the left. In other words, while the above method call is equivalent to:</p>
<pre><code>List(1, 2).++(List(3, 4))
</code></pre>
<p>If I had, instead <code>1 :: List(2, 3)</code>, that would be equivalent to:</p>
<pre><code>List(2, 3).::(1)
</code></pre>
<p>So you need to look at the type found <em>on the right</em> when looking for methods ending in colon. Consider, for instance:</p>
<pre><code>1 +: List(2, 3) :+ 4
</code></pre>
<p>The first method (<code>+:</code>) binds to the right, and is found on <code>List</code>. The second method (<code>:+</code>) is just a normal method, and binds to the left -- again, on <code>List</code>.</p>
<h2>Syntactic sugars/composition</h2>
<p>So, here's a few syntactic sugars that may hide a method:</p>
<pre><code>class Example(arr: Array[Int] = Array.fill(5)(0)) {
def apply(n: Int) = arr(n)
def update(n: Int, v: Int) = arr(n) = v
def a = arr(0); def a_=(v: Int) = arr(0) = v
def b = arr(1); def b_=(v: Int) = arr(1) = v
def c = arr(2); def c_=(v: Int) = arr(2) = v
def d = arr(3); def d_=(v: Int) = arr(3) = v
def e = arr(4); def e_=(v: Int) = arr(4) = v
def +(v: Int) = new Example(arr map (_ + v))
def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
}
val Ex = new Example // or var for the last example
println(Ex(0)) // calls apply(0)
Ex(0) = 2 // calls update(0, 2)
Ex.b = 3 // calls b_=(3)
// This requires Ex to be a "val"
val Ex(c) = 2 // calls unapply(2) and assigns result to c
// This requires Ex to be a "var"
Ex += 1 // substituted for Ex = Ex + 1
</code></pre>
<p>The last one is interesting, because <em>any</em> symbolic method can be combined to form an assignment-like method that way.</p>
<p>And, of course, there's various combinations that can appear in code:</p>
<pre><code>(_+_) // An expression, or parameter, that is an anonymous function with
// two parameters, used exactly where the underscores appear, and
// which calls the "+" method on the first parameter passing the
// second parameter as argument.
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.