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,355,225 | Edit and create HTML file using Python | <p>I am currently working on an assignment for creating an HTML file using python. I understand how to read an HTML file into python and then edit and save it.</p>
<pre><code>table_file = open('abhi.html', 'w')
table_file.write('<!DOCTYPE html><html><body>')
table_file.close()
</code></pre>
<p>The problem with the above piece is it's just replacing the whole HTML file and putting the string inside write(). How can I edit the file and the same time keep it's content intact. I mean, writing something like this, but inside the <strong>body tags</strong></p>
<pre><code><link rel="icon" type="image/png" href="img/tor.png">
</code></pre>
<p>I need the link to automatically go in between the opening and closing body tags.</p> | 35,355,433 | 1 | 2 | null | 2016-02-12 05:08:03.733 UTC | 13 | 2022-06-15 21:54:59.01 UTC | 2022-06-15 21:54:59.01 UTC | null | 1,839,439 | null | 4,416,786 | null | 1 | 17 | python|html|python-3.x|python-import | 50,276 | <p>You probably want to <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer">read up on BeautifulSoup</a>:</p>
<pre><code>import bs4
# load the file
with open("existing_file.html") as inf:
txt = inf.read()
soup = bs4.BeautifulSoup(txt)
# create new link
new_link = soup.new_tag("link", rel="icon", type="image/png", href="img/tor.png")
# insert it into the document
soup.head.append(new_link)
# save the file again
with open("existing_file.html", "w") as outf:
outf.write(str(soup))
</code></pre>
<p>Given a file like</p>
<pre><code><html>
<head>
<title>Test</title>
</head>
<body>
<p>What's up, Doc?</p>
</body>
</html>
</code></pre>
<p>this produces</p>
<pre><code><html>
<head>
<title>Test</title>
<link href="img/tor.png" rel="icon" type="image/png"/></head>
<body>
<p>What's up, Doc?</p>
</body>
</html>
</code></pre>
<p>(note: it has munched the whitespace, but gotten the html structure correct).</p> |
28,296,517 | How to customize Bootstrap 3 tab color | <p>I want to create a customized tab using Bootstrap 3.</p>
<p>What I have done is -</p>
<pre><code><ul class="nav nav-tabs" id="myTab">
<script type="text/javascript">
$(document).ready(function() {
//1st (1-1 = 0) tab selected initialy
$("#myTab li:eq(0) a").tab('show');
});
</script>
<li><a data-toggle="tab" href="#sectionA">SEARCH</a></li>
<li><a data-toggle="tab" href="#sectionB">ADVANCED</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,
butcher voluptate nisi qui.
</div>
<div id="sectionB" class="tab-pane fade">
Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna.
</div>
</div>
</code></pre>
<p>And I am getting a tab like this-</p>
<p><img src="https://i.stack.imgur.com/LKq8F.jpg" alt="2"></p>
<p>But I want to have is a customized colored.
I am new in Bootstrap 3, so I don't know how to do it.</p>
<p>What I want is something like this-</p>
<p><img src="https://i.stack.imgur.com/i6A5V.jpg" alt="1">.</p>
<p>Can anyone help me please?</p>
<p>Thanks in advance for helping.</p> | 28,298,334 | 4 | 2 | null | 2015-02-03 10:23:10.19 UTC | 8 | 2020-03-30 17:08:11.903 UTC | 2019-03-12 14:32:51.587 UTC | null | 917,151 | null | 2,193,439 | null | 1 | 34 | html|css|twitter-bootstrap | 130,643 | <p>On the selector <code>.nav-tabs > li > a:hover</code> add <code>!important</code> to the <code>background-color</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-tabs{
background-color:#161616;
}
.tab-content{
background-color:#303136;
color:#fff;
padding:5px
}
.nav-tabs > li > a{
border: medium none;
}
.nav-tabs > li > a:hover{
background-color: #303136 !important;
border: medium none;
border-radius: 0;
color:#fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>
<li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>
</ul>
<div class="tab-content">
<div id="search" class="tab-pane fade in active">
Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,
butcher voluptate nisi qui.
</div>
<div id="advanced" class="tab-pane fade">
Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna.
</div>
</div></code></pre>
</div>
</div>
</p> |
8,508,190 | How do I unit test a custom ActionFilter in ASP.Net MVC | <p>So I'm creating a custom ActionFilter that's based mostly on this project <a href="http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx">http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx</a>.</p>
<p>I want a custom action filter that uses the http accept headers to return either JSON or Xml. A typical controller action will look like this:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Get)]
[AcceptTypesAttribute(HttpContentTypes.Json, HttpContentTypes.Xml)]
public ActionResult Index()
{
var articles = Service.GetRecentArticles();
return View(articles);
}
</code></pre>
<p>The custom filter overrides the OnActionExecuted and will serialize the object (in this example articles) as either JSON or Xml.</p>
<p><strong>My question is: how do I test this?</strong></p>
<ol>
<li>What tests do I write? I'm a TDD novice and am not 100% sure what I should be testing and what not to test. I came up with <code>AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()</code>, <code>AcceptsTypeFilterXml_RequestHeaderAcceptsXml_ReturnsXml()</code> and <code>AcceptsTypeFilter_AcceptsHeaderMismatch_ReturnsError406()</code>.</li>
<li>How do I test an ActionFilter in MVC that is testing the Http Accept Headers?</li>
</ol>
<p>Thanks. </p> | 8,508,700 | 2 | 1 | null | 2011-12-14 16:41:53.597 UTC | 5 | 2021-06-25 03:33:34.817 UTC | null | null | null | null | 68,631 | null | 1 | 31 | asp.net-mvc|unit-testing|tdd|actionfilterattribute | 22,580 | <p>You just need to test the filter itself. Just create an instance and call the <code>OnActionExecuted()</code> method with test data then check the result. It helps to pull the code apart as much as possible. Most of the heavy lifting is done inside the <code>CsvResult</code> class which can be tested individually. You don't need to test the filter on an actual controller. Making that work is the MVC framework's responsibility.</p>
<pre><code>public void AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()
{
var context = new ActionExecutedContext();
context.HttpContext = // mock an http context and set the accept-type. I don't know how to do this, but there are many questions about it.
context.Result = new ViewResult(...); // What your controller would return
var filter = new AcceptTypesAttribute(HttpContentTypes.Json);
filter.OnActionExecuted(context);
Assert.True(context.Result is JsonResult);
}
</code></pre> |
1,095,131 | Paste Excel data into html table | <p>Using Javascript, how do I create an HTML table that can "accept" numeric matrix data from excel (or google spreadsheet), via "copy" in the spreadsheet and then "paste" into the table in the browser. </p> | 1,095,255 | 4 | 2 | null | 2009-07-07 22:07:49.217 UTC | 9 | 2021-03-16 11:10:25.93 UTC | 2016-09-29 21:07:08.923 UTC | null | 4,370,109 | null | 134,566 | null | 1 | 27 | javascript|html-table|spreadsheet | 54,126 | <p>This would only work reliably on IE since Firefox (and likely others) don't allow access to the clipboard without specifically allowing it; the earlier suggestion of pasting into a textarea first might work better than this.</p>
<p>When you copy from a spreadsheet, generally the cells are separated with a tab (chr9) and the rows with a CR (chr13). This script converts the clipboard into a 2D array and then builds a table from it. Not too elegant but it seems to work copying data out of Excel.</p>
<pre><code><html>
<head>
<script language="javascript">
function clip() {
// get the clipboard text
var clipText = window.clipboardData.getData('Text');
// split into rows
clipRows = clipText.split(String.fromCharCode(13));
// split rows into columns
for (i=0; i<clipRows.length; i++) {
clipRows[i] = clipRows[i].split(String.fromCharCode(9));
}
// write out in a table
newTable = document.createElement("table")
newTable.border = 1;
for (i=0; i<clipRows.length - 1; i++) {
newRow = newTable.insertRow();
for (j=0; j<clipRows[i].length; j++) {
newCell = newRow.insertCell();
if (clipRows[i][j].length == 0) {
newCell.innerText = ' ';
}
else {
newCell.innerText = clipRows[i][j];
}
}
}
document.body.appendChild(newTable);
}
</script>
</head>
<body>
<input type="button" onclick="clip()">
</body>
</html>
</code></pre> |
621,516 | How can I set the max number of MySQL processes or threads? | <p><code>ps axuw| grep mysql</code> indicates only MySQL process, but if I run htop I can see 10 rows each one of them with a separate PID. So I wonder if they are threads or processes that for some reason I cannot see using ps.</p>
<p>Would it make any sense to try to limit them to two on my development machine, where I don't need concurrent access of many clients.</p>
<p>BTW Running on Ubuntu 8.10</p> | 621,527 | 4 | 0 | null | 2009-03-07 08:13:06.423 UTC | 7 | 2014-10-09 21:13:43.853 UTC | 2013-06-11 07:50:38.607 UTC | null | 225,037 | szabgab | 11,827 | null | 1 | 28 | mysql|multithreading|process | 64,716 | <p>You can set the max number of threads in your my.ini like this:</p>
<pre><code>max_connections=2
</code></pre>
<p>However you might also want to set this:</p>
<pre><code>thread_cache_size=1
</code></pre>
<p>The thread cache controls how many it keeps open even when nothing is happening.</p> |
747,521 | How can I list all variables that are in a given scope? | <p>I know I can list all of the package and lexcial variables in a given scope using <a href="http://search.cpan.org/dist/PadWalker/PadWalker.pm" rel="noreferrer"><code>Padwalker</code></a>'s <code>peek_our</code> and <code>peek_my</code>, but how can I get the names and values of all of the global variables like <code>$"</code> and <code>$/</code>?</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use PadWalker qw/peek_our peek_my/;
use Data::Dumper;
our $foo = 1;
our $bar = 2;
{
my $foo = 3;
print Dumper in_scope_variables();
}
print Dumper in_scope_variables();
sub in_scope_variables {
my %in_scope = %{peek_our(1)};
my $lexical = peek_my(1);
#lexicals hide package variables
while (my ($var, $ref) = each %$lexical) {
$in_scope{$var} = $ref;
}
##############################################
#FIXME: need to add globals to %in_scope here#
##############################################
return \%in_scope;
}
</code></pre> | 748,206 | 4 | 0 | null | 2009-04-14 13:19:20.597 UTC | 11 | 2019-08-05 05:44:30.553 UTC | null | null | null | null | 78,259 | null | 1 | 34 | perl | 16,280 | <p>You can access the symbol table, check out p. 293 of "Programming Perl"
Also look at "Mastering Perl: <a href="http://www252.pair.com/comdog/mastering_perl/" rel="noreferrer">http://www252.pair.com/comdog/mastering_perl/</a>
Specifically: <a href="http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html" rel="noreferrer">http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html</a></p>
<p>Those variables you are looking for will be under the main namespace</p>
<p>A quick Google search gave me:</p>
<pre><code>{
no strict 'refs';
foreach my $entry ( keys %main:: )
{
print "$entry\n";
}
}
</code></pre>
<p>You can also do</p>
<pre><code>*sym = $main::{"/"}
</code></pre>
<p>and likewise for other values</p>
<p>If you want to find the type of the symbol you can do (from mastering perl):</p>
<pre><code>foreach my $entry ( keys %main:: )
{
print "-" x 30, "Name: $entry\n";
print "\tscalar is defined\n" if defined ${$entry};
print "\tarray is defined\n" if defined @{$entry};
print "\thash is defined\n" if defined %{$entry};
print "\tsub is defined\n" if defined &{$entry};
}
</code></pre> |
1,339,352 | How do I set -Dfile.encoding within ant's build.xml? | <p>I've got java source files with iso-8859-1 encoding. When I run <em>ant</em>, I get "warning: unmappable character for encoding UTF-8". I can avoid this if I run <em>ant -Dfile.encoding=iso-8859-1</em> or add <em>encoding="ISO-8859-1"</em> to each javac statement.</p>
<p>Is there a way to set the property globally within build.xml? <em><property name="file.encoding" value="ISO-8859-1"></em> does not work. I know that I can add a foo=ISO-8859-1 property and set encoding="${foo}" to each javac statement, but I'm trying to avoid that.</p> | 1,339,430 | 4 | 1 | null | 2009-08-27 07:09:54.717 UTC | 9 | 2015-10-14 15:13:12.037 UTC | 2009-08-27 07:27:34.51 UTC | null | 21,234 | null | 13,365 | null | 1 | 48 | java|ant|character-encoding|javac | 88,621 | <p>A few options:</p>
<ol>
<li>add <code>-Dfile.encoding=iso-8859-1</code> to your <code>ANT_OPTS</code> environment variable</li>
<li>use <code><presetdef></code> to setup defaults for all of your <code><javac></code> invocations</li>
</ol> |
838,404 | Implementing a HashMap in C | <p>How to go about creating a Hashmap in C from scratch as is present in C++ STL?</p>
<p>What parameters would be taken into consideration and how would you test the hashmap? As in, what would the benchmark test cases be which you would run before you could say that your hashmap is complete?</p> | 838,413 | 4 | 0 | null | 2009-05-08 05:50:11.117 UTC | 32 | 2020-08-08 03:26:49.1 UTC | 2020-08-08 03:26:49.1 UTC | null | 6,553,328 | null | 103,286 | null | 1 | 59 | c|data-structures|hashmap | 159,661 | <p>Well if you know the basics behind them, it shouldn't be too hard. </p>
<p>Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.</p>
<p>When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place. </p>
<p>Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).</p>
<p>Check out this fast hash table implementation:</p>
<p><a href="https://attractivechaos.wordpress.com/2009/09/29/khash-h/" rel="noreferrer">https://attractivechaos.wordpress.com/2009/09/29/khash-h/</a></p> |
683,211 | Method Syntax in Objective-C | <p>Can someone explain this method declaration syntax for me? In this function, the number of rows of a UIPickerView (slot machine UI on the iPhone) is being returned. From my understanding, the Method is called '<code>pickerView</code>', and returns an NSInteger. </p>
<p>It passes in a pointer to the UIPickerview called '<code>pickerView</code>' ... first, why is the method called the same name as the parameter? </p>
<p>Next there is NSInteger parameter called component that tells us which component we are counting the rows for. The logic to decide which is in the body of the method. </p>
<p>What is '<code>numberOfRowsInComponent</code>? It seems to describe the value we are returning, but it is in the middle of the parameters. </p>
<pre><code>- (NSInteger) pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
if (component == kStateComponent)
return [self.states count];
return[self.zips count];
}
</code></pre> | 683,290 | 4 | 0 | null | 2009-03-25 20:01:24.057 UTC | 90 | 2019-12-05 13:42:35.78 UTC | 2019-12-05 13:42:35.78 UTC | epatel | 1,033,581 | null | 82,780 | null | 1 | 180 | objective-c|syntax|methods | 98,730 | <p>Objective-C methods are designed to be self documenting, and they borrow from the rich tradition of Smalltalk.</p>
<p>I'll try to explain what you have here, <code>-(NSInteger) pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component</code>.</p>
<ul>
<li><p><code>- (NSInteger)</code><br>
This first portion indicates that this is an Objective C <strong>instance</strong> method that returns a NSInteger object. the <code>-</code> (dash) indicates that this is an <strong>instance</strong> method, where a <code>+</code> would indicate that this is a <strong>class</strong> method. The first value in parenthesis is the return type of the method. </p></li>
<li><p><code>pickerView:</code><br>
This portion is a part of the <strong>message name</strong>. The <strong>full message name</strong> in this case is <code>pickerView:numberOfRowsInComponent:</code>. The Objective-C runtime takes this method information and sends it to the indicated receiver. In pure C, this would look like<br>
<code>NSInteger pickerView(UIPickerView* pickerView, NSInteger component)</code>. However, since this is Objective-C, additional information is packed into the message name. </p></li>
<li><p><code>(UIPickerView*)pickerView</code><br>
This portion is part of the <strong>input</strong>. The input here is of type <code>UIPickerView*</code> and has a local variable name of pickerView. </p></li>
<li><p><code>numberOfRowsInComponent:</code><br>
This portion is the second part of the <strong>message name</strong>. As you can see here, message names are split up to help indicate what information you are passing to the receiver. Thus, if I were to message an object myObject with the variables foo and bar, I would type:<br>
<code>[myObject pickerView:foo numberOfRowsInComponent:bar];</code><br>
as opposed to C++ style:<br>
<code>myObject.pickerView(foo, bar);</code>.</p></li>
<li><p><code>(NSInteger)component</code><br>
This is the last portion of the <strong>input</strong>. the input here is of type <code>NSInteger</code> and has a local variable name of component.</p></li>
</ul> |
19,732,972 | How to make the navigation bar transparent | <p>How can I make the navigation bar transparent on Android 4.4.X and above?</p>
<p>I have searched in the documentation, but found nothing about this.</p> | 19,733,218 | 2 | 0 | null | 2013-11-01 18:25:09.13 UTC | 11 | 2015-09-02 12:59:03.827 UTC | 2014-08-20 13:34:34.6 UTC | null | 2,182,545 | null | 2,182,545 | null | 1 | 31 | android|android-4.4-kitkat | 45,065 | <p>I have taken this from the change log for <a href="http://developer.android.com/about/versions/android-4.4.html" rel="noreferrer">Android KitKat (4.4)</a>:</p>
<blockquote>
<p><strong>Translucent system bars</strong></p>
<p>You can now make the system bars partially translucent with new themes, <a href="http://developer.android.com/reference/android/R.style.html#Theme_Holo_NoActionBar_TranslucentDecor" rel="noreferrer"><code>Theme.Holo.NoActionBar.TranslucentDecor</code></a> and <a href="http://developer.android.com/reference/android/R.style.html#Theme_Holo_Light_NoActionBar_TranslucentDecor" rel="noreferrer"><code>Theme.Holo.Light.NoActionBar.TranslucentDecor</code></a>. By enabling translucent system bars, your layout will fill the area behind the system bars, so you must also enable <a href="http://developer.android.com/reference/android/R.attr.html#fitsSystemWindows" rel="noreferrer"><code>fitsSystemWindows</code></a> for the portion of your layout that should not be covered by the system bars.</p>
<p>If you're creating a custom theme, set one of these themes as the parent theme or include the <a href="http://developer.android.com/reference/android/R.attr.html#windowTranslucentNavigation" rel="noreferrer"><code>windowTranslucentNavigation</code></a> and <a href="http://developer.android.com/reference/android/R.attr.html#windowTranslucentStatus" rel="noreferrer"><code>windowTranslucentStatus</code></a> style properties in your theme.</p>
</blockquote>
<p>Hope this helps get you started.</p> |
19,825,283 | Redirect to a page/URL after alert button is pressed | <p>i have referred to this two questions <a href="https://stackoverflow.com/questions/7157029/call-php-page-under-javascript-function">call php page under Javascript function</a> and <a href="https://stackoverflow.com/questions/9394131/go-to-url-after-ok-button-in-alert-is-pressed">Go to URL after OK button in alert is pressed</a>. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:</p>
<p>processor.php</p>
<pre><code> if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
</code></pre>
<p>it's not displ ying anything(no alert box and not redirecting). when i delet this part <code>echo 'window.location= "index.php"';</code> it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.</p> | 19,825,307 | 6 | 0 | null | 2013-11-06 23:47:29.28 UTC | 5 | 2022-03-04 11:06:39.55 UTC | 2017-05-23 12:03:09.083 UTC | null | -1 | null | 2,922,814 | null | 1 | 12 | javascript|php | 212,753 | <p>You're missing semi-colons after your javascript lines. Also, <code>window.location</code> should have <code>.href</code> or <code>.replace</code> etc to redirect - <a href="https://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript">See this post for more information.</a></p>
<pre><code>echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
</code></pre>
<p>For clarity, try leaving PHP tags for this:</p>
<pre><code>?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
</code></pre>
<p>NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons <strong>are</strong> required in the first example.</p> |
2,955,280 | MXMLC and 64bit JRE | <p>Are there any workarounds to get the Flex compiler to work with a 64bit JRE? If I use an MXMLC task in an Ant buildfile in Eclipse it works fine but if I try to use MXMLC from the command line (or try the Run... command from FDT in Eclipse) it fails, telling me ...</p>
<p>"Error loading: C:\Program Files\Java\jrrt-1.6.0\jre\bin\jrockit\jvm.dll"</p>
<p>(this is with a 64bit JRockit runtime but that shouldn't matter).</p> | 3,064,938 | 2 | 0 | null | 2010-06-02 05:47:59.837 UTC | 12 | 2016-05-10 01:33:37.26 UTC | null | null | null | null | 356,105 | null | 1 | 28 | flash|64-bit|java|mxmlc | 15,778 | <p>There is currently no support for using the Flex compiler with the 64 bit JRE. Instead, have the compiler use a 32 bit JRE.</p>
<p>To do so, you'll need to edit the jvm.config file located in FLEX_HOME\bin. Within jvm.config, set <code>java.home</code> to the location of a 32bit JRE. If you don't already have a 32bit JRE, download it.</p>
<p>Example:</p>
<pre><code>java.home=C:/Program Files (x86)/Java/jre6
</code></pre>
<p>If you like this answer, please click the up arrow to the left.</p> |
48,860,158 | changing ggplot2::facet_wrap title from the default | <p>Is there any possible way to change the labels for the facet_wrap variable, as displayed below. So, for example, instead of <code>cyl: 4</code>, <code>cyl: 6</code>, <code>cyl: 8</code>, I want it to read <code>condition: 4</code>, <code>condition: 6</code>, <code>condition: 8</code>. Of course, I can just do this by renaming the variable, but that's not what I want. This is a much simpler version of a custom function where I can't just rename a variable anyway I like. </p>
<p>Another way to put this is, do I have any freedom to label the <code>facet_wrap</code> anyway I like? Kinda like how <code>x</code> aesthetic variable in <code>ggplot2</code> can have some name (e.g. <code>cyl</code>) in the dataframe (<code>mtcars</code>), but I can still replace it with my own name using <code>labs(x = "cylinder")</code>). I want to have something similar for <code>facet_wrap</code>. </p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
library(datasets)
library(ggplot2)
data(mtcars)
# creating a dataframe
df <- dplyr::group_by(mtcars, .dots = c('cyl', 'am')) %>%
dplyr::summarize(counts = n()) %>%
dplyr::mutate(perc = (counts / sum(counts)) * 100) %>%
dplyr::arrange(desc(perc))
# preparing the plot
ggplot2::ggplot(df, aes('', counts)) +
geom_col(
position = 'fill',
color = 'black',
width = 1,
aes(fill = factor(am))
) +
facet_wrap(~cyl, labeller = "label_both") + # faceting by `cyl` variable
geom_label(
aes(label = paste0(round(perc), "%"), group = factor(am)),
position = position_fill(vjust = 0.5),
color = 'black',
size = 5,
show.legend = FALSE
) +
coord_polar(theta = "y")
</code></pre>
<p><img src="https://i.imgur.com/bsVLUYB.png" alt=""></p>
<p>Created on 2018-02-19 by the <a href="http://reprex.tidyverse.org" rel="noreferrer">reprex package</a> (v0.2.0).</p> | 48,860,657 | 2 | 0 | null | 2018-02-19 05:45:54.24 UTC | 9 | 2018-02-19 17:26:14.94 UTC | null | null | null | null | 7,973,626 | null | 1 | 9 | r|ggplot2|data-visualization | 17,604 | <p>To change the facet labels you can provide a named vector of labels to the <code>labeller</code> argument in <code>facet_wrap</code>:</p>
<pre><code>labeller = labeller(cyl =
c("4" = "condition: 4",
"6" = "condition: 6",
"8" = "condition: 8"))
</code></pre>
<p>Here is the full plot code:</p>
<pre><code>ggplot2::ggplot(df, aes('', counts)) +
geom_col(
position = 'fill',
color = 'black',
width = 1,
aes(fill = factor(am))
) +
facet_wrap(~cyl, labeller = labeller(cyl =
c("4" = "condition: 4",
"6" = "condition: 6",
"8" = "condition: 8")
))
geom_label(
aes(label = paste0(round(perc), "%"), group = factor(am)),
position = position_fill(vjust = 0.5),
color = 'black',
size = 5,
show.legend = FALSE
) +
coord_polar(theta = "y")
</code></pre>
<p><a href="https://i.stack.imgur.com/ASIJt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ASIJt.png" alt="enter image description here"></a></p>
<p>EDIT based on the comments where a function to return labels is requested:</p>
<p>perhaps something like this:</p>
<pre><code>label_facet <- function(original_var, custom_name){
lev <- levels(as.factor(original_var))
lab <- paste0(custom_name, ": ", lev)
names(lab) <- lev
return(lab)
}
ggplot2::ggplot(df, aes('', counts)) +
geom_col(
position = 'fill',
color = 'black',
width = 1,
aes(fill = factor(am))
) +
facet_wrap(~cyl, labeller = labeller(cyl = label_facet(df$cyl, "grouping"))) +
geom_label(
aes(label = paste0(round(perc), "%"), group = factor(am)),
position = position_fill(vjust = 0.5),
color = 'black',
size = 5,
show.legend = FALSE
) +
coord_polar(theta = "y")
</code></pre>
<p><a href="https://i.stack.imgur.com/YyDiF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YyDiF.png" alt="enter image description here"></a></p>
<pre><code>sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] bindrcpp_0.2 ggplot2_2.2.1 dplyr_0.7.4 RMOA_1.0 rJava_0.9-9 RMOAjars_1.0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.14 bindr_0.1 magrittr_1.5 munsell_0.4.3 colorspace_1.3-2 R6_2.2.2 rlang_0.1.4
[8] plyr_1.8.4 tools_3.4.2 grid_3.4.2 gtable_0.2.0 yaml_2.1.14 lazyeval_0.2.1 assertthat_0.2.0
[15] digest_0.6.13 tibble_1.4.1 glue_1.2.0 labeling_0.3 compiler_3.4.2 pillar_1.0.1 scales_0.5.0.9000
[22] pkgconfig_2.0.1
</code></pre> |
38,089,200 | What is CGLIB in Spring Framework? | <p>What is CGLIB and how it is related to Spring? Do we have to define usage of CGLIB explicitly when using Spring Framework?</p> | 38,094,536 | 1 | 0 | null | 2016-06-29 02:10:22.92 UTC | 9 | 2020-06-02 08:40:37.897 UTC | 2018-01-08 13:51:36.613 UTC | null | 814,702 | null | 1,042,646 | null | 1 | 35 | spring|code-generation|cglib | 21,771 | <p>Ref Spring <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-introduction-proxies" rel="noreferrer">docs</a>.
What is CGLIB & how is it related to Spring?</p>
<blockquote>
<p>CGLIB is a code generation library. Spring uses CGLIB, to generate proxies.</p>
</blockquote>
<p>Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied. </p>
<p>Yes, you have to tell spring to use CGLIB based proxies explicitly.</p>
<p><strong>Via xml:</strong></p>
<p><code><aop:aspectj-autoproxy proxy-target-class="true"/></code> <strong>proxy-target-class</strong> property is set to true will cause CGLIB-based proxying to be in effect.</p>
<p><strong>Via Annotation:</strong></p>
<pre><code>@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig {
// ...
}
</code></pre>
<p>There is no need to add CGLIB to your classpath. As of Spring 3.2, CGLIB is repackaged and included in the spring-core JAR. </p>
<p>You may have look at <a href="https://stackoverflow.com/questions/15568112/using-proxy-target-class-true-with-spring-beans">this</a> too.</p> |
41,568,111 | Flexbox with one fixed column width | <p>I am trying to acheive a <code>flexbox</code> with two columns, the left that is of a fixed width and the right that scales as the page size is altered. For example:</p>
<pre><code><style>
.flex_container {
display: flex;
width: 100%;
}
.flex_col_left {
width: 200px;
}
.flex_col_right {
width: 85%;
}
</style>
<div class = "flex_container">
<div class = "flex_col_left">
.....
</div>
<div class = "flex_col_right">
.....
</div>
<div>
</code></pre>
<p>This works to an extent but it does not feel right as I am mixing px and %. Is it incorrect to do it this way and if so what might be a better solution?</p>
<p>EDIT Classes naming issue was a typo and now fixed.</p> | 41,568,169 | 2 | 0 | null | 2017-01-10 11:47:23.503 UTC | 10 | 2017-01-10 11:57:57.6 UTC | 2017-01-10 11:55:13.487 UTC | null | 1,842,939 | null | 1,842,939 | null | 1 | 38 | css|flexbox | 37,646 | <p>Instead of setting width in <code>%</code> on right column you can just use <code>flex: 1</code> and it will take rest of free width in a row.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex_container {
display: flex;
width: 100%;
}
.flex_item_left {
width: 200px;
background: lightgreen;
}
.flex_item_right {
flex: 1;
background: lightblue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex_container">
<div class="flex_item_left">
.....
</div>
<div class="flex_item_right">
.....
</div>
<div></code></pre>
</div>
</div>
</p> |
23,036,062 | Can't use Scanner.nextInt() and Scanner.nextLine() together | <p>I have to get a string input and an integer input, but there order of input should be that integer comes first then user should be asked for string input</p>
<pre><code>Scanner in = new Scanner(System.in);
input = in.nextLine();
k = in.nextInt();
in.close();
</code></pre>
<p>The above code works fine but if I take an integer input first like in the following code</p>
<pre><code>Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
</code></pre>
<p>then it throws the java.lang.ArrayIndexOutOfBoundsException.</p>
<p>Here's the complete code of my source file:</p>
<pre><code>import java.util.Scanner;
</code></pre>
<p>public class StringSwap {</p>
<pre><code>public static void main(String args[]) {
String input;
int k;
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
int noOfCh = noOfSwapCharacters(input);
originalString(input, noOfCh, k);
}
public static int noOfSwapCharacters(String s) {
char cS[] = s.toCharArray();
int i = 0, postCounter = 0;
while (cS[i] != '\0') {
if (cS[i] != '\0' && cS[i + 1] != '\0') {
cS[cS.length - 1 - postCounter] = '\0';
postCounter++;
}
i++;
}
return postCounter;
}
public static void originalString(String s, int noOfCh, int k) {
int counter = 1, chCounter = 0;
char cArray[] = s.toCharArray();
String post = "";
String pre = "";
String finalString = "";
char temp;
for (int i = 1; i <= k; i++) {
chCounter = 0;
counter = 1;
post = "";
pre = "";
for (int j = 0; j < cArray.length; j++) {
if (counter % 2 == 0 && chCounter <= noOfCh) {
temp = cArray[j];
post = temp + post;
cArray[j] = '\0';
chCounter++;
}
counter++;
}
for (int h = 0; h < cArray.length; h++) {
if (cArray[h] != '\0')
pre = pre + cArray[h];
}
finalString = pre + post;
for (int l = 0; l < finalString.length(); l++) {
cArray[l] = finalString.charAt(l);
}
}
System.out.println(finalString);
}
</code></pre>
<p>}</p>
<p>Kindly point out what I am doing wrong here.</p> | 23,036,112 | 1 | 0 | null | 2014-04-12 21:01:07.2 UTC | 10 | 2014-04-12 21:06:56.55 UTC | null | null | null | null | 1,609,548 | null | 1 | 14 | java|java.util.scanner | 26,163 | <p>The problem is the <code>'\n'</code> character that follows your integer. When you call <code>nextInt</code>, the scanner reads the <code>int</code>, but it does not consume the <code>'\n'</code> character after it; <code>nextLine</code> does that. That is why you get an empty line instead of the string that you were expecting to get.</p>
<p>Let's say your input has the following data:</p>
<pre><code>12345
hello
</code></pre>
<p>Here is how the input buffer looks initially (<code>^</code> represents the position at which the <code>Scanner</code> reads the next piece of data):</p>
<pre><code>1 2 3 4 5 \n h e l l o \n
^
</code></pre>
<p>After <code>nextInt</code>, the buffer looks like this:</p>
<pre><code>1 2 3 4 5 \n h e l l o \n
^
</code></pre>
<p>The first <code>nextLine</code> consumes the <code>\n</code>, leaving your buffer like this:</p>
<pre><code>1 2 3 4 5 \n h e l l o \n
^
</code></pre>
<p>Now the <code>nextLine</code> call will produce the expected result. Therefore, to fix your program, all you need is to add another call to <code>nextLine</code> after <code>nextInt</code>, and discard its result:</p>
<pre><code>k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();
</code></pre> |
47,295,871 | Is there a way to use pipenv with Jupyter notebook? | <p>Is there a way to use pipenv with Jupyter notebook?</p>
<p>Or more specifically, with an atom nteract/hydrogen python 3 kernel?</p> | 47,296,960 | 4 | 0 | null | 2017-11-14 21:55:12.143 UTC | 77 | 2022-06-19 18:33:10.963 UTC | 2018-04-13 18:16:22.283 UTC | null | 33,264 | null | 3,731,467 | null | 1 | 93 | python|jupyter|pipenv | 44,816 | <p>Just tried the following with success.</p>
<p>In your project folder:</p>
<pre><code>pipenv install ipykernel
pipenv shell
</code></pre>
<p>This will bring up a terminal in your virtualenv like this:</p>
<pre><code>(my-virtualenv-name) bash-4.4$
</code></pre>
<p>In that shell do:</p>
<pre><code>python -m ipykernel install --user --name=my-virtualenv-name
</code></pre>
<p>Launch jupyter notebook:</p>
<pre><code>jupyter notebook
</code></pre>
<p>In your notebook, Kernel -> Change Kernel. Your kernel should now be an option.</p>
<p><a href="https://i.stack.imgur.com/htimC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/htimC.png" alt="Change Kernel Screenshot"></a></p>
<p>Source: <a href="https://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs/" rel="noreferrer">IPythonNotebookVirtualenvs</a></p> |
1,531,934 | Only get specific columns | <p>Can I make my EF objects retrieve only specific columns in the sql executed? If I am executing the below code to retrieve objects, is there something I can do to only get certain columns if wanted?</p>
<pre><code>public IEnumerable<T> GetBy(Expression<Func<T, bool>> exp)
{
return _ctx.CreateQuery<T>(typeof(T).Name).Where<T>(exp);
}
</code></pre>
<p>This would generate a select clause that contains all columns. But, if I have a column that contains a large amount of data that really slows down the query, how can I have my objects exclude that column from the sql generated?</p>
<p>If my table has Id(int), Status(int), Data(blob), how can I make my query be</p>
<pre><code>select Id, Status from TableName
</code></pre>
<p>instead of </p>
<pre><code>select Id, Status, Data from TableName
</code></pre>
<p>From the suggestion below, my method is</p>
<pre><code>public IEnumerable<T> GetBy(Expression<Func<T, bool>> exp, Expression<Func<T, T>> columns)
{
return Table.Where<T>(exp).Select<T, T>(columns);
}
</code></pre>
<p>And I'm calling it like so</p>
<pre><code>mgr.GetBy(f => f.Id < 10000, n => new {n.Id, n.Status});
</code></pre>
<p>However, I'm getting a compile error: </p>
<blockquote>
<p>Cannot implicitly convert type 'AnonymousType#1' to 'Entities.BatchRequest'</p>
</blockquote> | 1,532,034 | 1 | 0 | null | 2009-10-07 14:19:14.943 UTC | 14 | 2017-01-30 09:25:30.5 UTC | 2017-01-30 09:25:30.5 UTC | null | 107,625 | null | 166,882 | null | 1 | 40 | entity-framework | 51,931 | <p>Sure. Projection does this:</p>
<pre><code>var q = from r in Context.TableName
select new
{
Id = r.Id,
Status = r.Status
}
</code></pre>
<p>Here's an actual example (obviously, my DB has different tables than yours). I added my EF model to LINQPad and typed the following query:</p>
<pre><code>from at in AddressTypes
select new
{
Id = at.Id,
Code = at.Code
}
</code></pre>
<p>LINQPad shows me that the generated SQL is:</p>
<pre><code>SELECT
1 AS [C1],
[Extent1].[AddressTypeId] AS [AddressTypeId],
[Extent1].[Code] AS [Code]
FROM
[dbo].[AddressType] AS [Extent1]
</code></pre>
<p>None of the other fields from the table are included.</p>
<p><strong>Responding to updated question</strong></p>
<p>Your <code>columns</code> argument says it takes a type T and returns the same type. Therefore, the expression you pass must conform to this, or you need to change the type of the argument, i.e.:</p>
<pre><code>public IEnumerable<U> GetBy<U>(Expression<Func<T, bool>> exp, Expression<Func<T, U>> columns)
{
return Table.Where<T>(exp).Select<T, U>(columns);
}
</code></pre>
<p>Now the expression can return any type you care to use.</p> |
20,273,995 | Custom map style in MapKit | <p>I am looking for a way to implement a custom map style in iOS 7, just like you can do with <a href="https://developers.google.com/maps/documentation/javascript/styling" rel="nofollow noreferrer">Google Maps</a>. I have found some posts saying that this is not possible with MapKit, but they are all posted a while back. To clarify, by style I am talking about custom colors and preferably also fonts. Example of custom Google Map style below.</p>
<p><a href="https://i.stack.imgur.com/fw7LT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fw7LT.jpg" alt="enter image description here"></a><br>
<sub>(source: <a href="http://www.servendesign.com/wp-content/uploads/2011/12/zaarley-custom-google-maps.jpg" rel="nofollow noreferrer">servendesign.com</a>)</sub> </p>
<p>I would really prefer using MapKit for performance reasons, but if it is not supported I am open to using other frameworks as well. The ones that I have seen are MapBox and Cloudmade, and of course the Google Maps SDK.</p>
<p>Is there a way of doing it with MapKit? If not, what is the best way to go?</p> | 20,274,924 | 3 | 0 | null | 2013-11-28 20:02:37.983 UTC | 10 | 2019-10-24 23:20:33.803 UTC | 2019-09-09 11:11:09.623 UTC | null | 4,751,173 | null | 1,373,572 | null | 1 | 13 | ios|google-maps|mapkit|mapbox|cloudmade | 19,793 | <p><code>MKMapView</code> does not expose the properties you're interested in customizing. The Google Maps SDK does support custom colors and icons for markers, which may be sufficient for your purposes.</p>
<p>Edit: Stay tuned for iOS 11, which may offer this level of customization.</p> |
21,559,775 | VBScript to open a dialog to select a filepath | <p>At present I am opening a file with my vbscript as follows: </p>
<pre><code>strFile = "C:\Users\test\file.txt"
Set objFile = objFSO.OpenTextFile(strFile)
</code></pre>
<p>I would like to change this so that a file can be selected/navigated to by the user and that file is used in the script. How can I add this ability? I have tried to search for how to load a file dialog/prompt the user for a file etc just not sure how to complete in a VBScript.</p> | 21,565,999 | 3 | 0 | null | 2014-02-04 17:52:24.95 UTC | 5 | 2019-05-06 16:42:24.82 UTC | 2014-02-04 18:12:46.327 UTC | null | 1,359,668 | null | 1,523,603 | null | 1 | 11 | vba|vbscript|filepath | 63,076 | <p>There is another solution I found interesting from <a href="http://social.technet.microsoft.com/Forums/scriptcenter/en-US/a3b358e8-15ae-4ba3-bca5-ec349df65ef6/windows7-vbscript-open-file-dialog-box-fakepath?forum=ITCG">MS TechNet</a> less customization but gets what you wanted to achieve. This returns the full path of the selected file.</p>
<pre><code>Set wShell=CreateObject("WScript.Shell")
Set oExec=wShell.Exec("mshta.exe ""about:<input type=file id=FILE><script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>""")
sFileSelected = oExec.StdOut.ReadLine
wscript.echo sFileSelected
</code></pre> |
34,973,456 | How to change text of a TextView in navigation drawer header? | <p>I want to change the text of a TextView inside the navigation drawer header. But I get this error:</p>
<blockquote>
<p>java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference</p>
</blockquote>
<hr>
<p><strong>activity_main.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p><strong>nav_header_main</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/slide_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/tvHeaderIcon"
android:layout_width="60dp"
android:layout_height="60dp"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/app_name"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/tvHeaderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</code></pre>
<p><strong>MainActivity.java</strong></p>
<pre><code>TextView tvHeaderName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHeaderName= (TextView) findViewById(R.id.tvHeaderName);
tvHeaderName.setText("Saly");
}
</code></pre>
<p>How can I do this?</p> | 38,418,531 | 11 | 0 | null | 2016-01-24 08:00:32.84 UTC | 29 | 2021-08-21 21:37:21.77 UTC | 2016-01-24 09:00:50.107 UTC | null | 336,557 | null | 3,360,327 | null | 1 | 108 | java|android|textview | 97,685 | <p>Use function getHeaderView on your navigationView:</p>
<pre><code>NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = (TextView) headerView.findViewById(R.id.navUsername);
navUsername.setText("Your Text Here");
</code></pre> |
35,143,283 | Google Drive API v3 Migration | <p>I decided to migrate from Google Drive API v2 to v3 and it was not an easy task. Even thought Google wrote this <a href="https://developers.google.com/drive/v3/web/migration">documentation</a>, there are many gaps in it and there is not much information about this on the web.</p>
<p>I'm sharing here what I have found.</p> | 35,143,284 | 2 | 1 | null | 2016-02-02 01:00:07.827 UTC | 14 | 2022-01-14 12:12:36.917 UTC | 2016-02-02 01:09:15.337 UTC | null | 1,718,678 | null | 1,718,678 | null | 1 | 19 | google-drive-api | 11,785 | <p>First, read the official docs: <a href="https://developers.google.com/drive/api/v2/v2-to-v3-reference" rel="nofollow noreferrer">v2 to v3 reference</a> | <a href="https://developers.google.com/drive/api/v2/v3versusv2" rel="nofollow noreferrer">Drive API v3 versus v2</a> | <a href="https://developers.google.com/drive/api/v2/migrate-to-v3" rel="nofollow noreferrer">Migrate to v3</a></p>
<hr>
<h2>Download</h2>
<p><a href="https://developers.google.com/drive/api/v3/manage-downloads" rel="nofollow noreferrer">Download</a> has changed. The field <code>downloadUrl</code> does not exist anymore. Now, it can be achieved with this:</p>
<pre><code>service.files().get(fileId).executeMediaAndDownloadTo(outputStream);
</code></pre>
<p>I tried the new field <code>webContentLink</code> but it returns HTML content, instead of the file's content. In other words, it gives you the link to the Drive web UI.</p>
<hr>
<h2>Upload</h2>
<p>Upload only requires to change the word <code>insert</code> for <code>create</code>, nothing more.</p>
<hr>
<h2>Trash / Update</h2>
<p>I wasted some time with this one . Used to be a simple <code>service.files().trash(fileId).execute()</code>.
Docs say</p>
<blockquote>
<p>files.trash -> files.update with {'trashed':true}</p>
</blockquote>
<p>The <a href="https://developers.google.com/drive/api/v2/reference/files/update#examples_1" rel="nofollow noreferrer">example code</a> for <code>update</code> on v2 makes a <code>get</code> on the file, sets new values and then calls <code>update</code>.</p>
<p>On v3, using <code>update</code> like that throws this exception:</p>
<pre><code>{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "The resource body includes fields which are not directly writable.",
"reason" : "fieldNotWritable"
} ],
"message" : "The resource body includes fields which are not directly writable."
}
</code></pre>
<p>The solution is to create an empty <code>File</code> setting only the new values:</p>
<pre><code>File newContent = new File();
newContent.setTrashed(true);
service.files().update(fileId, newContent).execute();
</code></pre>
<p>Note: <code>File</code> refers to <code>com.google.api.services.drive.model.File</code> (it is not <code>java.io.File</code>).</p>
<hr>
<h2>List</h2>
<p>Files returned by <code>service.files().list()</code> does not contain information now, i.e. every field is null. If you want <code>list</code> on v3 to behave like in v2, call it like this:</p>
<pre><code>service.files().list().setFields("nextPageToken, files");
</code></pre>
<p>Docs on <a href="https://developers.google.com/drive/api/v3/search-files" rel="nofollow noreferrer">Search for files and folders</a> use <code>setFields("nextPageToken, files(id, name)")</code> but there is no documentation on how to get all the info for a file. Now you know, just include "files".</p>
<hr>
<h2>Fields</h2>
<blockquote>
<p>Full resources are no longer returned by default. Use the <code>fields</code> query parameter to request specific fields to be returned. If left unspecified only a subset of commonly used fields are returned.</p>
</blockquote>
<p>That last part is not totally true, since you are forced to use <code>setFields</code> in some cases. For example, if you use <code>service.about().get().execute()</code> you will get this error:</p>
<pre><code>"The 'fields' parameter is required for this method."
</code></pre>
<p>which is solved by calling <code>service.about().get().setFields("user, storageQuota").execute()</code>, for instance.</p>
<p>At the end of the docs is mentioned as:</p>
<blockquote>
<p>The <code>fields</code> query parameter should be specified for methods which return</p>
</blockquote>
<hr>
<p>For the rest of the changes, just follow the Google table on the docs.</p> |
20,869,904 | C++ handling of excess precision | <p>I'm currently looking at <a href="http://www.cs.cmu.edu/afs/cs/project/quake/public/code/predicates.c">code which does multi-precision floating-point arithmetic</a>. To work correctly, that code requires values to be reduced to their final precision at well-defined points. So even if an intermediate result was computed to an <a href="http://en.wikipedia.org/wiki/Extended_precision#x86_Extended_Precision_Format">80 bit extended precision</a> floating point register, at some point it has to be rounded to <a href="http://en.wikipedia.org/wiki/Double-precision_floating-point_format">64 bit double</a> for subsequent operations.</p>
<p>The code uses a macro <code>INEXACT</code> to describe this requirement, but doesn't have a perfect definition. The <a href="http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Optimize-Options.html#index-ffloat-store-900">gcc manual</a> mentions <code>-fexcess-precision=standard</code> as a way to force well-defined precision for cast and assignment operations. However, it also writes:</p>
<blockquote>
<p>‘-fexcess-precision=standard’ is not implemented for languages other than C</p>
</blockquote>
<p>Now I'm thinking about porting those ideas to C++ (comments welcome if anyone knows an existing implementation). So it seems I can't use that switch for C++. <strong>But what is the g++ default behavior in absence of any switch? Are there more C++-like ways to control the handling of excess precision?</strong></p>
<p>I guess that for my current use case, I'll probably use <code>-mfpmath=sse</code> in any case, which should not incur any excess precision as far as I know. But I'm still curious.</p> | 20,870,215 | 2 | 0 | null | 2014-01-01 14:58:09.98 UTC | 9 | 2014-01-09 17:14:55.723 UTC | null | null | null | null | 1,468,366 | null | 1 | 13 | c++|gcc|floating-point|floating-point-precision|extended-precision | 2,145 | <blockquote>
<p>Are there more C++-like ways to control the handling of excess precision?</p>
</blockquote>
<p>The C99 standard defines <code>FLT_EVAL_METHOD</code>, a compiler-set macro that defines how excess precision should happen in a C program (many C compilers still behave in a way that does not exactly conform to the most reasonable interpretation of the value of <code>FP_EVAL_METHOD</code> that they define: older GCC versions generating 387 code, Clang when generating 387 code, …). Subtle points in relation with the effects of <code>FLT_EVAL_METHOD</code> were clarified in the C11 standard.</p>
<p>Since the 2011 standard, C++ <a href="http://en.cppreference.com/w/cpp/types/climits/FLT_EVAL_METHOD" rel="noreferrer">defers to C99</a> for the definition of <code>FLT_EVAL_METHOD</code> (header cfloat).</p>
<p>So GCC should simply allow <code>-fexcess-precision=standard</code> for C++, and hopefully it eventually will. The same semantics as that of C are already in the C++ standard, they only need to be implemented in C++ compilers.</p>
<hr>
<blockquote>
<p>I guess that for my current use case, I'll probably use -mfpmath=sse in any case, which should not incur any excess precision as far as I know.</p>
</blockquote>
<p>That is the usual solution. </p>
<p>Be aware that C99 also defines <code>FP_CONTRACT</code> in math.h that you may want to look at: it relates to the same problem of some expressions being computed at a higher precision, striking from a completely different side (the modern fused-multiply-add instruction instead of the old 387 instruction set). This is a pragma to decide whether the compiler is allowed to replace source-level additions and multiplications with FMA instructions (this has the effect that the multiplication is virtually computed at infinite precision, because this is how this instruction works, instead of being rounded to the precision of the type as it would be with separate multiplication and addition instructions). This pragma has apparently not been incorporated in the C++ standard (as far as I can see).</p>
<p>The default value for this option is implementation-defined and some people argue for the default to be to allow FMA instructions to be generated (for C compilers that otherwise define <code>FLT_EVAL_METHOD</code> as 0).
You should, in C, future-proof
your code with:</p>
<pre><code>#include <math.h>
#pragma STDC FP_CONTRACT off
</code></pre>
<p>And the equivalent incantation in C++ if your compiler documents one.</p>
<hr>
<blockquote>
<p>what is the g++ default behavior in absence of any switch?</p>
</blockquote>
<p>I am afraid that the answer to this question is that GCC's behavior, say, when generating 387 code, is nonsensical. See the description of the <a href="http://gcc.gnu.org/ml/gcc-patches/2008-11/msg00105.html" rel="noreferrer">situation</a> that motivated Joseph Myers to fix the situation for C. If g++ does not implement <code>-fexcess-precision=standard</code>, it probably means that 80-bit computations are randomly rounded to the precision of the type when the compiler happened to have to spill some floating-point registers to memory, leading the program below to print "foo" in some circumstances outside the programmer's control:</p>
<pre><code>if (x == 0.0) return;
... // code that does not modify x
if (x == 0.0) printf("foo\n");
</code></pre>
<p>… because the code in the ellipsis caused <code>x</code>, that was held in an 80-bit floating-point register, to be spilt to a 64-bit slot on the stack.</p> |
18,814,559 | PHP Upload form, PDF, Doc & Docx | <p>I'm struggling to make this upload code work for a docx file, it works okay for doc and pdf..</p>
<pre><code>$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
</code></pre>
<p>this is part of a project from a while ago and i honestly can't remember how to do it..</p>
<p>I know it's not the most secure upload method, but if someone could help it would be appreciated!</p>
<p>I'm thinking i need to add another line here:</p>
<pre><code>if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)
</code></pre>
<p>Just not sure what.. Help is appreciated!</p>
<p>Edit:
So i've got to this stage (with the help of comments!)</p>
<pre><code>$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
//if ((($_FILES["file"]["type"] == "application/pdf")
//|| ($_FILES["file"]["type"] == "application/msword"))
if (($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats- officedocument.wordprocessingml.document"))
&& ($_FILES["file"]["size"] < 20000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
</code></pre>
<p>But now its coming up with: Parse error: syntax error, unexpected T_BOOLEAN_AND in /var/sites/s/stanation.com/public_html/forms/process/insert.php on line 30</p> | 18,814,707 | 3 | 0 | null | 2013-09-15 16:14:28.43 UTC | 0 | 2018-08-14 10:53:46.783 UTC | 2013-09-15 16:46:12.11 UTC | null | 1,260,444 | null | 1,260,444 | null | 1 | 4 | php|html|upload | 47,632 | <p>For <code>docx</code> check this MIME type</p>
<pre><code>application/vnd.openxmlformats-officedocument.wordprocessingml.document
</code></pre>
<p>EDIT :</p>
<p>Here's the code . You're missing parenthesis</p>
<pre><code><?php
$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (($_FILES["file"]["type"] == "application/pdf") || ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") && ($_FILES["file"]["size"] < 20000000) && in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Success";
}
}
</code></pre> |
24,019,807 | How to compare a model with no random effects to a model with a random effect using lme4? | <p>I can use gls() from the nlme package to build mod1 with no random effects.
I can then compare mod1 using AIC to mod2 built using lme() which does include a random effect.</p>
<pre><code>mod1 = gls(response ~ fixed1 + fixed2, method="REML", data)
mod2 = lme(response ~ fixed1 + fixed2, random = ~1 | random1, method="REML",data)
AIC(mod1,mod2)
</code></pre>
<p>Is there something similar to gls() for the lme4 package which would allow me to build mod3 with no random effects and compare it to mod4 built using lmer() which does include a random effect?</p>
<pre><code>mod3 = ???(response ~ fixed1 + fixed2, REML=T, data)
mod4 = lmer(response ~ fixed1 + fixed2 + (1|random1), REML=T, data)
AIC(mod3,mod4)
</code></pre> | 24,020,669 | 2 | 0 | null | 2014-06-03 16:04:11.56 UTC | 11 | 2021-12-08 14:26:33.353 UTC | 2014-06-03 16:31:24.327 UTC | null | 190,277 | null | 3,703,460 | null | 1 | 21 | r|lme4|mixed-models|nlme | 19,037 | <p>With modern (>1.0) versions of <code>lme4</code> you can make a direct comparison between <code>lmer</code> fits and the corresponding <code>lm</code> model, <strong>but</strong> you have to use ML --- it's hard to come up with a sensible analogue of the "REML criterion" for a model without random effects (because it would involve a linear transformation of the data that set all of the fixed effects to zero ...)</p>
<p>You should be aware that there are theoretical issues with information-theoretic comparisons between models with and without variance components: see the <a href="https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html" rel="noreferrer">GLMM FAQ</a> for more information.</p>
<pre><code>library(lme4)
fm1 <- lmer(Reaction~Days+(1|Subject),sleepstudy, REML=FALSE)
fm0 <- lm(Reaction~Days,sleepstudy)
AIC(fm1,fm0)
## df AIC
## fm1 4 1802.079
## fm0 3 1906.293
</code></pre>
<p>I prefer output in this format (delta-AIC rather than raw AIC values):</p>
<pre><code>bbmle::AICtab(fm1,fm0)
## dAIC df
## fm1 0.0 4
## fm0 104.2 3
</code></pre>
<p>To test, let's simulate data with no random effect (I had to try a couple of random-number seeds to get an example where the among-subject std dev was actually estimated as zero):</p>
<pre><code>rr <- simulate(~Days+(1|Subject),
newparams=list(theta=0,beta=fixef(fm1),
sigma=sigma(fm1)),
newdata=sleepstudy,
family="gaussian",
seed=103)[[1]]
ss <- transform(sleepstudy,Reaction=rr)
fm1Z <- update(fm1,data=ss)
VarCorr(fm1Z)
## Groups Name Std.Dev.
## Subject (Intercept) 0.000
## Residual 29.241
fm0Z <- update(fm0,data=ss)
all.equal(c(logLik(fm0Z)),c(logLik(fm1Z))) ## TRUE
</code></pre> |
36,186,831 | How do I hide the VueJS syntax while the page is loading? | <p>maybe this is a trivial question.</p>
<p>so, when I run my vuejs application on browser with enables throttling download speed (sets to low connection). I got unfinished vue syntax output in browser.</p>
<p><a href="https://i.stack.imgur.com/0wTIv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0wTIv.png" alt="Vue js syntax appear in browser"></a></p>
<p>I know we can trick this out with showing <strong>loading image</strong> before entire page has loaded, but it's there any best solution to fix this?</p> | 36,187,668 | 12 | 0 | null | 2016-03-23 19:15:02.47 UTC | 41 | 2022-07-15 22:23:51.007 UTC | 2018-10-08 20:09:23.48 UTC | null | 304,151 | null | 2,230,192 | null | 1 | 191 | javascript|vue.js | 67,049 | <p>You can use the <a href="https://v2.vuejs.org/v2/api/#v-cloak" rel="nofollow noreferrer">v-cloak</a> directive, which will hide the Vue instance until the compilation finishes, if you combine it with the right CSS.</p>
<p>HTML:</p>
<pre><code><div v-cloak>{{ message }}</div>
</code></pre>
<p>CSS:</p>
<pre><code>[v-cloak] { display: none; }
</code></pre> |
44,527,956 | Python: ufunc 'add' did not contain a loop with signature matching types dtype('S21') dtype('S21') dtype('S21') | <p>I have two dataframes, which both have an <code>Order ID</code> and a <code>date</code>. </p>
<p>I wanted to add a flag into the first dataframe <code>df1</code>: if a record with the same <code>order id</code> and <code>date</code> is in dataframe <code>df2</code>, then add a <code>Y</code>:</p>
<pre><code>[ df1['R'] = np.where(orders['key'].isin(df2['key']), 'Y', 0)]
</code></pre>
<p>To accomplish that, I was going to create a key, which would be the concatenation of the <code>order_id</code> and <code>date</code>, but when I try the following code:</p>
<pre><code>df1['key']=df1['Order_ID']+'_'+df1['Date']
</code></pre>
<p>I get this error</p>
<pre><code>ufunc 'add' did not contain a loop with signature matching types dtype('S21') dtype('S21') dtype('S21')
</code></pre>
<p>df1 looks like this: </p>
<pre><code>Date | Order_ID | other data points ...
201751 4395674 ...
201762 3487535 ...
</code></pre>
<p>These are the datatypes:</p>
<pre><code>df1.info()
RangeIndex: 157443 entries, 0 to 157442
Data columns (total 6 columns):
Order_ID 157429 non-null object
Date 157443 non-null int64
...
dtypes: float64(2), int64(2), object(2)
memory usage: 7.2+ MB
df1['Order_ID'].values
array(['782833030', '782834969', '782836416', ..., '783678018',
'783679806', '783679874'], dtype=object)
</code></pre> | 44,528,113 | 2 | 0 | null | 2017-06-13 17:27:19.83 UTC | 4 | 2022-07-30 23:24:50.517 UTC | 2017-06-13 17:45:59.087 UTC | null | 5,393,381 | null | 5,187,157 | null | 1 | 36 | python|pandas|numpy|dataframe|concatenation | 126,599 | <p>The problem is that you can't add an object array (containing strings) to a number array, that's just ambiguous:</p>
<pre><code>>>> import pandas as pd
>>> pd.Series(['abc', 'def']) + pd.Series([1, 2])
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')
</code></pre>
<p>You need to explicitly convert your <code>Dates</code> to <code>str</code>.</p>
<p>I don't know how to do that efficiently in pandas but you can use:</p>
<pre><code>df1['key'] = df1['Order_ID'] + '_' + df1['Date'].apply(str) # .apply(str) is new
</code></pre> |
43,833,895 | How to Include JS file in ionic 3 | <p>Im looking for a way to access a variable from external js file which i included in assets/data folder</p>
<p>below is what i tried</p>
<p>placed <strong><code>test.js</code></strong> in <strong>assets/data folder</strong></p>
<p>in <strong><code>test.js</code></strong> added variable <code>testvar = "heloo from external js";</code></p>
<p>added script tag in <code>src/index.html</code> <code><script src="assets/data/test.js"></script></code></p>
<p>in <code>app.component.ts</code> i added this line after imports;<code>declare var testvar: any;</code></p>
<p>in constructor added this line to log the value <code>console.log(testvar);</code></p>
<p>result is <strong><em>error</em></strong> : <strong><em>ERROR ReferenceError: testvar is not defined</em></strong></p>
<p>so, how can i use my js variable in typescript ?</p> | 44,134,679 | 5 | 0 | null | 2017-05-07 16:30:08.987 UTC | 12 | 2019-11-13 10:55:33.537 UTC | 2017-05-07 16:36:28.883 UTC | null | 4,826,457 | null | 5,160,386 | null | 1 | 22 | angular|typescript|ionic2|ionic3 | 58,901 | <p><strong>This solution only worked for me</strong></p>
<blockquote>
<p>Put the import js in <code>src/index.html</code> header tag, before the
<code>build/polyfills.js</code> and <code>build/main.js</code> (they are in body tag);</p>
</blockquote>
<p>Example : I created a file <code>src/assets/test.js</code> with a <code>var testvar</code>, imported in <code>src/index.html</code> and then in <code>src/app/app.component.ts</code> declared <code>declare var testvar;</code>.</p>
<p><strong>test.js</strong></p>
<pre><code>var testvar = "Hello from external js";
</code></pre>
<p><strong>index.html</strong></p>
<pre><code>...
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">
<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
<script src="assets/js/test.js"></script> //here, not in body
...
</code></pre>
<p><strong>app.componet.ts</strong></p>
<pre><code>declare var testvar;
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
constructor(private statusbar : StatusBar, splashScreen: SplashScreen) {
alert(testvar);
...
</code></pre> |
49,694,134 | Angular Material: How to close all mat-dialogs and sweet-alerts on logout | <p>I wanted to close all my dialog's (mat-dialog, bootstrap modals & sweet alerts) on logout in Angular. This is how it was done in AngularJS (version 1.5):</p>
<pre><code>function logout() {
//hide $mdDialog modal
angular.element('.md-dialog-container').hide();
//hide any open $mdDialog modals & backdrop
angular.element('.modal-dialog').hide();
angular.element('md-backdrop').remove();
//hide any open bootstrap modals & backdrop
angular.element('.inmodal').hide();
angular.element('.fade').remove();
//hide any sweet alert modals & backdrop
angular.element('.sweet-alert').hide();
angular.element('.sweet-overlay').remove();
}
</code></pre>
<p>How can I do this in Angular? Using <code>$('.mat-dialog-container')</code> or <code>$('.inmodal')</code> does't give me an option to do <code>hide()</code> or <code>close()</code></p>
<p>I tried doing this, but I wan't able to get the element reference:</p>
<pre><code>import { ElementRef, Injectable, ViewChild } from '@angular/core';
import { MatDialog, MatDialogContainer, MatDialogRef } from '@angular/material';
export class MyClass
{
@ViewChild('.mat-dialog-container') _matDialog: ElementRef;
@ViewChild('.mat-dialog-container') _matDialogRef:MatDialogRef<MatDialog>;
constructor() { }
function logout()
{
//access the dialogs here
}
}
</code></pre> | 49,762,913 | 2 | 0 | null | 2018-04-06 13:38:19.273 UTC | 2 | 2021-03-12 15:12:45.023 UTC | 2018-08-30 20:02:38.597 UTC | null | 2,658,683 | null | 2,609,095 | null | 1 | 33 | angular|angular-material|ng-bootstrap|sweetalert2 | 32,691 | <p>This is what i have done to close any open <code>mat-dialog</code> throughout the application:</p>
<pre><code>import {MatDialog} from '@angular/material';
export class myClass {
constructor(private dialogRef: MatDialog) {
}
logOut()
{
this.dialogRef.closeAll();
}
}
</code></pre>
<p>If you would like to close only a specific dialog you can loop through <code>dialogRef.openDialogs</code> and close the respective dialog using <code>close()</code></p>
<p>This is how you can close any open/active sweet alert dialog:</p>
<pre><code>const sweetAlertCancel = document.querySelector('.swal2-cancel') as HTMLElement;
if (sweetAlertCancel) {
sweetAlertCancel.click(); //only if cancel button exists
}
const sweetAlertConfirm = document.querySelector('.swal2-confirm') as HTMLElement;
if (sweetAlertConfirm) {
sweetAlertConfirm.click(); //if cancel doesn't exist , confirm is the equivalent for Ok button
}
</code></pre>
<p>Unlike <code>material-dialog</code> there is no method available to close or hide all open sweet alert dialog's. This is what i'm able to do so far.</p> |
50,840,511 | google.cloud import storage: cannot import storage | <p>I tried to run the code bellow by following the google tutorials i found here: <a href="https://cloud.google.com/docs/authentication/production" rel="noreferrer">https://cloud.google.com/docs/authentication/production</a></p>
<pre><code>def implicit():
from google.cloud import storage
# If you don't specify credentials when constructing the client, the
# client library will look for credentials in the environment.
project = 'my_project_name'
storage_client = storage.Client(project=project)
# Make an authenticated API request
buckets = list(storage_client.list_buckets())
print(buckets)
implicit()
</code></pre>
<p>But it keeps giving me the following error:</p>
<pre><code>Traceback (most recent call last):
File "[PATH]/scratch_5.py", line 13, in <module>
implicit()
File "[PATH]/scratch_5.py", line 2, in implicit
from google.cloud import storage
ImportError: cannot import name storage
</code></pre>
<p>Could someone help me with this?</p> | 50,841,078 | 3 | 0 | null | 2018-06-13 15:04:08.483 UTC | 2 | 2020-10-28 14:56:23.93 UTC | 2018-06-13 15:44:19.487 UTC | null | 4,482,491 | null | 9,707,310 | null | 1 | 33 | python|google-cloud-platform|google-cloud-storage | 72,344 | <p>I see you are trying to use the <a href="https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-python" rel="noreferrer">Google Cloud Storage client libraries</a>.</p>
<p>In order to use it, you should first make sure that it is installed in your machine:</p>
<pre><code>pip install --upgrade google-cloud-storage
</code></pre>
<p>And then, you should probably set up authentication (if you are using <a href="https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-python" rel="noreferrer">Application Default Credentials</a>, from the documentation you mentioned), by setting up the <code>GOOGLE_APPLICATION_CREDENTIALS</code> environment variable in the machine where you are running the code, like below. If you are using Windows, follow the <a href="https://cloud.google.com/storage/docs/reference/libraries#setting_up_authentication" rel="noreferrer">steps presented in the documentation</a>, instead.</p>
<pre><code>export GOOGLE_APPLICATION_CREDENTIALS="/path/to/file.json"
</code></pre>
<p>Alternatively, you can try <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually" rel="noreferrer">using explicit credentials</a>. The only difference between the one you shared (using implicit credentials obtained from the environment) and one using explicit credentials, is that when you declare the GCS client, you should do something like:</p>
<pre><code>storage_client = storage.Client.from_service_account_json('/path/to/SA_key.json')
</code></pre>
<p>Once all this is ready, you should have no issues with running the sample code you provided. In order to keep learning about GCS and its client libraries, feel free to search on the documentation I linked and have a look at the <a href="https://google-cloud-python.readthedocs.io/en/latest/storage/client.html" rel="noreferrer">library reference page</a>.</p> |
39,928,401 | Recover DB password stored in my DBeaver connection | <p>I forgot the password of a dev instance (irresponsible.. yeah, I am working on it). I have the connection saved in my DBeaver with the password. I am still able to connect using that connection. DBeaver is not showing it in plain text. Is there anyway I can retrieve the password? Asking DBA to reset the password is the last resort. I tried to copy paste to a notepad, copying is disabled apparently.</p> | 39,928,445 | 10 | 1 | null | 2016-10-08 03:33:15.07 UTC | 51 | 2022-07-02 23:21:45.727 UTC | 2020-05-06 17:19:27.65 UTC | null | 792,066 | null | 6,934,076 | null | 1 | 111 | dbeaver | 94,609 | <h2>Edit: For DBeaver 6.1.3+</h2>
<p>The credential file is located ~/Library/DBeaverData/workspace6/General/.dbeaver/credentials-config.json (I was on Mac) and it follows a different encryption strategy than it's predecessors. Please refer the next answer to see how to decrypt. It works like a charm.</p>
<h2>Pre- DBeaver 6.1.3</h2>
<p>Follow these steps (My DBeaver version was 3.5.8 and it was on Mac OsX El Capitan)</p>
<ol>
<li>Locate the file in which DBeaver stores the connection details. For
me, it was in this location
<code>~/.dbeaver/General/.dbeaver-data-sources.xml</code>. This file is hidden,
so keep that in mind when you look for it.</li>
<li>Locate your interested Datasource Definition node in that file.</li>
<li><strong>Decrypt the password:</strong> Unfortunately, everything is in plain text except password; Password is in some kind of Encrypted form. Decrypt it to plain-text using this <a href="https://bugdays.com/dbeaver-password-decrypter" rel="noreferrer">tool</a>.</li>
</ol>
<h1>Or</h1>
<p>I put together a quick and dirty <a href="https://github.com/so-random-dude/oneoffcodes/blob/master/SimpleStringEncrypter.java" rel="noreferrer">Java program</a> by copying core of DBeaver's method for decrypting the password. Once you have the Encrypted password string, just execute this program, it will convert the password to plain text and prints it</p>
<h1>How to run it</h1>
<p>On Line Number 13, just replace <code>OwEKLE4jpQ==</code> with whatever encrypted password you are finding in <code>.dbeaver-data-sources.xml</code> file for your interested datasource. Compile it and run it, it will print the plain-text password.</p>
<p><a href="https://github.com/jaisonpjohn/dbeaver-password-retriever/blob/master/SimpleStringEncrypter.java" rel="noreferrer">https://github.com/jaisonpjohn/dbeaver-password-retriever/blob/master/SimpleStringEncrypter.java</a></p>
<h1>Edit</h1>
<p>Apparently, this is a "Popular" mistake. So I have deployed an AWS lambda function with the aforementioned code. Use this at your own risk, you will never know whether I am logging your password or not </p>
<pre><code>curl https://lmqm83ysii.execute-api.us-west-2.amazonaws.com/prod/dbeaver-password-decrypter \
-X POST --data "OwEKLE4jpQ=="
</code></pre>
<h1>Edit 2</h1>
<p>Even better, here is the UI <a href="https://bugdays.com/dbeaver-password-decrypter" rel="noreferrer">https://bugdays.com/dbeaver-password-decrypter</a>. This goes without saying, use this at your own risk </p> |
29,392,529 | Hide RecyclerView scrollbar | <p>How can I remove the scrollbar in my recyclerview?
I've tried with <code>mRecyclerView.setScrollBarSize(0);</code> but it's not working. (Actually, it doesn't do anything, whatever the value I set).</p> | 29,956,318 | 2 | 2 | null | 2015-04-01 13:47:48.05 UTC | 1 | 2020-03-23 12:29:44.63 UTC | null | null | null | null | 2,535,024 | null | 1 | 34 | android|android-recyclerview | 24,362 | <p>Put <code>android:scrollbars="none"</code> like this:</p>
<pre><code><android.support.v7.widget.RecyclerView
android:id="@+id/RecyclerViewId"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
</android.support.v7.widget.RecyclerView>
</code></pre>
<h2><strong>Update for androidx library</strong> :</h2>
<pre><code> <androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
</androidx.recyclerview.widget.RecyclerView>
</code></pre> |
46,786,986 | How and where to use ::ng-deep? | <p>I'm new to Angular 4, so could anyone please explain how and where to use <code>::ng-deep</code> in Angular 4?</p>
<p>Actually I want to overwrite some of the CSS properties of the child components from the parent components. Moreover is it supported on IE11?</p>
<p>Thanks for the help.</p> | 46,787,145 | 7 | 1 | null | 2017-10-17 09:34:24.03 UTC | 43 | 2022-09-09 18:22:18.193 UTC | 2021-01-28 07:01:22.897 UTC | null | -1 | null | 8,778,646 | null | 1 | 193 | css|angular|angular-template | 323,788 | <p>Usually <strong><code>/deep/ “shadow-piercing”</code></strong> combinator can be used to force a style down to <strong><code>child components</code></strong>. This selector had an alias >>> and now has another one called ::ng-deep.</p>
<p>since <strong><code>/deep/ combinator</code></strong> has been deprecated, it is recommended to use <code>::ng-deep</code></p>
<p><strong>For example:</strong></p>
<pre><code><div class="overview tab-pane" id="overview" role="tabpanel" [innerHTML]="project?.getContent( 'DETAILS')"></div>
</code></pre>
<p>and <strong><code>css</code></strong></p>
<pre><code>.overview {
::ng-deep {
p {
&:last-child {
margin-bottom: 0;
}
}
}
}
</code></pre>
<p>it will be applied to child components</p> |
4,213,095 | Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL? | <p>I have a DLL that allocates memory and returns it. Function in DLL is like this:</p>
<pre><code>void Foo( unsigned char** ppMem, int* pSize )
{
* pSize = 4;
* ppMem = malloc( * pSize );
for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i;
}
</code></pre>
<p>Also, i have a python code that access this function from my DLL:</p>
<pre><code>from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
mem = POINTER( c_ubyte )()
size = c_int( 0 )
Foo( byref( mem ), byref( size ) ]
print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
</code></pre>
<p>I'm expecting that <code>print</code> will show "4 0 1 2 3" but it shows "4 221 221 221 221" O_O. Any hints what i'm doing wrong?</p> | 4,218,409 | 1 | 2 | null | 2010-11-18 09:02:25.237 UTC | 12 | 2021-10-07 21:54:13.793 UTC | 2010-11-18 14:12:35.667 UTC | null | 68,063 | null | 69,882 | null | 1 | 27 | python|ctypes | 28,398 | <p>Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function <code>__stdcall</code> so <code>windll</code> could be used in the Python code. The other option is to use <code>__cdecl</code> (normally the default) and use <code>cdll</code> instead of <code>windll</code> in the Python code.</p>
<p>mydll.c (cl /W4 /LD mydll.c)</p>
<pre class="lang-c prettyprint-override"><code>
#include <stdlib.h>
__declspec(dllexport) void __stdcall Foo(unsigned char** ppMem, int* pSize)
{
char i;
*pSize = 4;
*ppMem = malloc(*pSize);
for(i = 0; i < *pSize; i++)
(*ppMem)[i] = i;
}
</code></pre>
<p>demo.py (Python 2/3 and 32-/64-bit compatible)</p>
<pre class="lang-py prettyprint-override"><code>from __future__ import print_function
from ctypes import *
Foo = WinDLL('./mydll').Foo
Foo.argtypes = POINTER(POINTER(c_ubyte)), POINTER(c_int)
Foo.restype = None
mem = POINTER(c_ubyte)()
size = c_int()
Foo(byref(mem),byref(size))
print(size.value, mem[0], mem[1], mem[2], mem[3])
</code></pre>
<p>Output</p>
<pre class="lang-none prettyprint-override"><code>4 0 1 2 3
</code></pre> |
26,583,669 | Looking to give MailChimp dynamic content? | <p>Ok so I'm looking to send out a weekly scheduled email with MailChimp.
The email is to contain the newest 20 of the stock list (car stocklist of garage) to their subscribers.</p>
<p>I can't seem to get this to work with an RSS feed as imagined so i wondered is there any other way to get some formatted HTML (in a PHP file) into the body of MailChimp template on a weekly basis?</p>
<p>Many thanks.</p> | 27,711,344 | 2 | 0 | null | 2014-10-27 08:37:07.193 UTC | 8 | 2019-02-12 12:21:24.693 UTC | null | null | null | null | 857,782 | null | 1 | 13 | php|html|email|dynamic|mailchimp | 21,752 | <p>If looking to inject custom content into a template at the time of sending, I would recommend having a look into creating a custom template that uses our template language.</p>
<p>If you've created a custom template within MailChimp using our template language to specify editable content areas: <a href="http://templates.mailchimp.com/getting-started/template-language/" rel="noreferrer">http://templates.mailchimp.com/getting-started/template-language/</a>, then you would be able to update those content areas via the API.</p>
<p>To do this, you'll want to make either a campaigns/create call: <a href="https://apidocs.mailchimp.com/api/2.0/campaigns/create.php" rel="noreferrer">https://apidocs.mailchimp.com/api/2.0/campaigns/create.php</a> or a campaigns/update call: <a href="https://apidocs.mailchimp.com/api/2.0/campaigns/update.php" rel="noreferrer">https://apidocs.mailchimp.com/api/2.0/campaigns/update.php</a> and specify the section and content that you'd like to change as part of the 'content' parameter. the content 'sections' will correspond to the mc:edit tags that were added to the custom template.</p>
<p>You also have the ability to customize your content, like adding a first name to a greeting in the body of your content for instance, even further with the use of merge tags. I highly recommend checking those out as well and consider using them in your content if you need that level of customization: Getting Started with Merge Tags: <a href="http://kb.mailchimp.com/merge-tags/using/getting-started-with-merge-tags" rel="noreferrer">http://kb.mailchimp.com/merge-tags/using/getting-started-with-merge-tags</a></p> |
20,346,456 | How to establish socket connection using the command line | <p>How can I establish my socket connection using the Windows command line?</p>
<p>For example, my socket IP and port num is <code>192.168.1.180:9760</code></p>
<p>I just want to send commands to that IP from the command line.</p> | 20,346,608 | 2 | 1 | null | 2013-12-03 08:45:41.017 UTC | 2 | 2016-08-26 10:26:31.673 UTC | 2016-08-26 10:26:31.673 UTC | null | 321,731 | null | 2,901,888 | null | 1 | 12 | windows|sockets|batch-file | 45,568 | <p>You can use "netcat", or "nc" as it is sometimes called.</p>
<p>So if the server is using UDP on port 9760, you can use:</p>
<pre><code>nc -u 192.168.1.180 9760
</code></pre> |
6,485,127 | How can I delete/unset the properties of a JavaScript object? | <blockquote>
<p><strong>Possible Duplicates:</strong> <br />
<a href="https://stackoverflow.com/questions/1596782">How can I unset a JavaScript variable?</a> <br />
<a href="https://stackoverflow.com/questions/208105">How do I remove a property from a JavaScript object?</a></p>
</blockquote>
<p>I'm looking for a way to remove/unset the properties of a JavaScript object, so they'll no longer come up if I loop through the object doing <code>for (var i in myObject)</code>. How can this be done?</p> | 6,485,155 | 2 | 2 | null | 2011-06-26 16:19:55.18 UTC | 5 | 2021-07-19 13:22:09.047 UTC | 2021-07-19 13:15:00.72 UTC | null | 63,550 | null | 49,153 | null | 1 | 130 | javascript|jquery | 124,874 | <p>Simply use <code>delete</code>, but be aware that you should read fully what the effects are of using this:</p>
<pre><code> delete object.index; //true
object.index; //undefined
</code></pre>
<p>But if I was to use like so:</p>
<pre><code>var x = 1; //1
delete x; //false
x; //1
</code></pre>
<p>But if you do wish to delete variables in the global namespace, you can use its global object such as <code>window</code>, or using <code>this</code> in the outermost scope, i.e.,</p>
<pre><code>var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true
</code></pre>
<p><em><a href="http://perfectionkills.com/understanding-delete/" rel="noreferrer">Understanding delete</a></em></p>
<p>Another fact is that using delete on an array will not remove the index, but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity. When it comes to arrays you should use <code>splice</code> which is a prototype of the array object.</p>
<p>Example Array:</p>
<pre><code>var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";
</code></pre>
<p>If I was to do:</p>
<pre><code>delete myCars[1];
</code></pre>
<p>the resulting array would be:</p>
<pre><code>["Saab", undefined, "BMW"]
</code></pre>
<p>But using splice like</p>
<pre><code>myCars.splice(1,1);
</code></pre>
<p>would result in:</p>
<pre><code>["Saab", "BMW"]
</code></pre> |
7,534,407 | How to write event log using vbscript | <p>I want to write event log when this vbscript run. How to i can?</p>
<p>Thanks for any help.</p> | 7,534,449 | 3 | 0 | null | 2011-09-23 20:22:23.99 UTC | 3 | 2011-09-27 15:50:33.87 UTC | null | null | null | null | 911,383 | null | 1 | 5 | vbscript|event-log | 38,857 | <p>Like so:</p>
<pre><code>Set shell = CreateObject("WScript.Shell")
shell.LogEvent 4, "Your Message Here"
</code></pre>
<p>The 4 is a severity level. You can learn more about the <code>LogEvent</code> method on <a href="http://msdn.microsoft.com/en-us/library/b4ce6by3(v=VS.85).aspx" rel="noreferrer">MSDN</a>.</p> |
7,138,021 | jquery add remove class onclick | <p>i have any navigation menu !</p>
<pre><code> <div class="nav">
<ul class="navigation">
<li class="selected"><a href="#">HOME</a></li>
<li><a href="#">PROFILE></a></li>
<li><a href="#">CONTACTUS</a></li>
<li><a href="#">ABOATUS</a></li>
</ul>
</div>
</code></pre>
<p>Now how to add selected class after click to any ( profile, Contactus, aboutus ) and remove selected home using Jquery.</p>
<p>Thanks</p> | 7,138,134 | 3 | 0 | null | 2011-08-21 11:38:44.823 UTC | 9 | 2012-03-15 15:08:57.057 UTC | null | null | null | null | 892,965 | null | 1 | 11 | jquery|navigation|addclass|removeclass | 39,813 | <p>On the assumption that you want to have only <em>one</em> element of class-name <code>selected</code> I suggest:</p>
<pre><code>$('ul.navigation li a').click(
function(e) {
e.preventDefault(); // prevent the default action
e.stopPropagation(); // stop the click from bubbling
$(this).closest('ul').find('.selected').removeClass('selected');
$(this).parent().addClass('selected');
});
</code></pre>
<p><a href="http://jsfiddle.net/davidThomas/eMx7X/" rel="noreferrer">JS Fiddle demo</a>.</p> |
24,399,294 | Android: AsyncTask to make an HTTP GET Request? | <p>I'm new to Android development. My question is, do I use AsyncTask in order to make an HTTP GET request (JSON response)? Is this correct? Does anyone know where I can see an example of this if this is indeed true? If not, could you correct me? Thanks!</p> | 24,399,320 | 8 | 2 | null | 2014-06-25 02:32:23.667 UTC | 5 | 2022-05-14 10:53:24.603 UTC | 2017-07-17 07:47:36.15 UTC | null | 192,373 | null | 2,020,101 | null | 1 | 20 | android|android-asynctask|httprequest | 91,410 | <p>Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.</p>
<p><strong>example:</strong></p>
<pre><code>class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet("YOU URLS TO JSON");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
}
</code></pre> |
24,134,693 | How to uninstall the "Microsoft Advertising SDK" Visual Studio extension? | <p>One of the extensions listed in Visual Studio (2012 for me) is the "Microsoft Advertising SDK for Windows 8.1". I like to uninstall extensions I don't need, but this one won't allow me. if I hover the (enabled!) button it says in a tooltip:</p>
<blockquote>
<p>This product cannot be uninstalled via extensions and updates</p>
</blockquote>
<p>It looks like this:</p>
<p><img src="https://i.stack.imgur.com/VGiiz.png" alt="extensions"></p>
<p>On second inspection I see a similar (more helpful) message bottom right:</p>
<blockquote>
<p>You need to use the Programs and Features pane in the Windows Control Panel to remove this extension.</p>
</blockquote>
<p>Easy enough, no? But it's not there!</p>
<p><img src="https://i.stack.imgur.com/18lU5.png" alt="uninstalls"></p>
<p>Or:</p>
<p><img src="https://i.stack.imgur.com/LlgEK.png" alt="uninstalls search"></p>
<p><strike>In addition to the instructions on screen I also searched. The only helpful source was <a href="http://msdn.microsoft.com/en-us/library/advertising-windows-prereqs%28v=msads.10%29.aspx" rel="noreferrer">this MSDN page</a> that says basically the same thing.</strike> <em>Link is now broken</em>.</p>
<p><strike>Commenters mentioned that <a href="http://visualstudiogallery.msdn.microsoft.com/3d3fa204-0641-4317-ab2c-50092f732edb" rel="noreferrer">the extension web page</a> (see "Reviews" and "Q AND A" tabs) has a few similar complaints. I've cross-posted this question there as well.</strike> <em>Link is now broken, but if you search others are complaining still on the MSDN forums</em>.</p>
<p>In any case: is there an easy way to uninstall this extension?</p> | 24,449,757 | 7 | 2 | null | 2014-06-10 06:54:17.62 UTC | 68 | 2016-11-20 20:57:02.3 UTC | 2016-11-20 20:57:02.3 UTC | null | 419,956 | null | 419,956 | null | 1 | 179 | visual-studio|visual-studio-extensions | 19,743 | <p>Run the following from an <strong>elevated</strong> Powershell prompt:</p>
<pre><code>gwmi Win32_Product -Filter "Name LIKE 'Microsoft Advertising%'"
</code></pre>
<p>And it should show the culprits:</p>
<pre><code>IdentifyingNumber : {6AB13C21-C3EC-46E1-8009-6FD5EBEE515B}
Name : Microsoft Advertising SDK for Windows 8.1 - ENU
Vendor : Microsoft Corporation
Version : 8.1.30809.0
Caption : Microsoft Advertising SDK for Windows 8.1 - ENU
IdentifyingNumber : {6AC81125-8485-463D-9352-3F35A2508C11}
Name : Microsoft Advertising SDK for Windows Phone 8.1 XAML - ENU
Vendor : Microsoft Corporation
Version : 8.1.40427.0
Caption : Microsoft Advertising SDK for Windows Phone 8.1 XAML - ENU
IdentifyingNumber : {5C87A4DB-31C7-465E-9356-71B485B69EC8}
Name : Microsoft Advertising SDK for Windows Phone - ENU
Vendor : Microsoft Corporation
Version : 6.2.960.0
Caption : Microsoft Advertising SDK for Windows Phone - ENU
IdentifyingNumber : {EBD9DB6D-180B-4C59-9622-B75CC4B32C94}
Name : Microsoft Advertising Service Extension for Visual Studio
Vendor : Microsoft Corporation
Version : 12.0.40402.0
Caption : Microsoft Advertising Service Extension for Visual Studio
</code></pre>
<p>Then to actually uninstall add <code>| foreach { $_.Uninstall() }</code> to the command like so:</p>
<pre><code>gwmi Win32_Product -Filter "Name LIKE 'Microsoft Advertising%'" | foreach { $_.Uninstall() }
</code></pre>
<p>Which should display for each one:</p>
<pre><code>__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
PSComputerName :
</code></pre>
<p>The important thing to look for is <code>ReturnValue : 0</code> which means success. If you get <code>ReturnValue : 1603</code> it likely means your Powershell prompt wasn't elevated (running as admin). (Full list of ReturnValues documented <a href="http://msdn.microsoft.com/en-us/library/aa390890(v=vs.85).aspx" rel="noreferrer">here</a>)</p> |
21,421,526 | Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs | <p>I've looked at a couple of other possible solutions on SO but didn't see any that were doing what I was doing.</p>
<p>Currently I have been able to parse a string and detect hash tags with the following code:</p>
<pre><code>mystring = mystring.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, "$1<span class='hash_tag'>$2</span>").replace(/\s*$/, "");
</code></pre>
<p>And this successfully detects all sorts of #hashtags. However it also detects anchors in URLs, such as: <a href="http://www.example.com/#anchor" rel="noreferrer">http://www.example.com/#anchor</a> - I can't work out how to modify what I have to exclude anchors while keeping it flexible.</p>
<p>Thanks</p> | 21,422,891 | 3 | 3 | null | 2014-01-29 03:35:40.073 UTC | 9 | 2017-06-18 03:17:58.883 UTC | 2014-01-29 03:42:39.843 UTC | null | 1,054,245 | null | 2,981,412 | null | 1 | 16 | javascript|jquery|regex|parsing | 19,714 | <p>Here's a regex to match hashtag(#) if it has a space before it or it's beginning of string.. like so:</p>
<pre><code>(^|\s)(#[a-z\d-]+)
</code></pre>
<p>Working regex example:</p>
<p><a href="http://regex101.com/r/pJ4wC5" rel="noreferrer">http://regex101.com/r/pJ4wC5</a></p>
<p>Javascript:</p>
<pre><code>var string = '#hello This is an #example of some text with #hash-tags - http://www.example.com/#anchor but dont want the link';
string = string.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");
console.log(string);
</code></pre>
<p>Output:</p>
<pre><code><span class='hash_tag'>#hello</span> This is an <span class='hash_tag'>#example</span> of some text with <span class='hash_tag'>#hash-tags</span> - http://www.example.com/#anchor but dont want the link
</code></pre> |
21,778,632 | Put two textviews side by side in a layout | <p>I have two textviews i need to put side by side in a layout and I have to respect two rules:</p>
<ul>
<li><p>Textview2 needs always to be displayed entirely.</p></li>
<li><p>Textview1 has to be cropped if there is no enough room in the layout.</p></li>
</ul>
<p>Examples:</p>
<p>Textview1|textview2</p>
<p>Teeeeeeeeeeeeeeeeeeeextview1...|textview2</p>
<p>Any ideas?</p>
<p>The only way I found that might work is to create a drawable with the text of textview2 and affect it as coumpoundDrawable to textview1.</p> | 21,779,017 | 4 | 3 | null | 2014-02-14 11:50:36.187 UTC | 8 | 2020-05-13 04:17:47.283 UTC | 2014-02-14 12:56:37.553 UTC | null | 1,176,435 | null | 1,176,435 | null | 1 | 25 | android|textview | 39,186 | <p>Wrap the two TextViews in a LinearLayout. Assign a layout weight of 0 to textview2 and a layout weight of 1 to textview2. </p>
<p>See here for more info: <a href="http://developer.android.com/guide/topics/ui/layout/linear.html#Weight">Linear Layout Weight</a></p>
<p>If you play with the example below you'll see that the LinearLayout first allocates space to textview2 (with weight 0) and then allocates whatever remains to textview1 (with weight 1). If there is insufficient space to accommodate both TextViews, textview1 will be ellipsized first. In the example below textview2 will only ever become ellipsized if the LinearLayout is smaller than the size of textview2 itself. Assign a specific layout width to the FrameLayout and see what happens.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="match_parent"
android:background="#FF0000FF">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFFF0000"
android:ellipsize="end"
android:maxLines="1"
android:text="textview1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#FF00FF00"
android:ellipsize="end"
android:maxLines="1"
android:text="textview2" />
</LinearLayout>
</FrameLayout>
</code></pre> |
2,161,052 | How to create an "inkblot" chart with R? | <p>How can I create a chart like</p>
<p><a href="http://junkcharts.typepad.com/junk_charts/2010/01/leaving-ink-traces.html" rel="noreferrer">http://junkcharts.typepad.com/junk_charts/2010/01/leaving-ink-traces.html</a></p>
<p>where several time series (one per country) are displayed horizontally as symmetric areas?</p>
<p>I think if I could display one time series in this way, it is easy to generalize to several using mfrow.</p>
<p>Sample data: </p>
<pre><code>#Solar energy production in Europe, by country (EC),(1 000 toe)
Country,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007
Belgium,1,1,1,1,1,1,2,2,3,3,3,5
Bulgaria,-,-,-,-,-,-,-,-,-,-,-,-
Czech Republic,0,0,0,0,0,0,0,0,2,2,3,4
Denmark,6,7,7,8,8,8,9,9,9,10,10,11
Germany (including ex-GDR from 1991),57,70,83,78,96,150,184,216,262,353,472,580
Estonia,-,-,-,-,-,-,-,-,-,-,-,-
Ireland,0,0,0,0,0,0,0,0,0,0,1,1
Greece,86,89,93,97,99,100,99,99,101,102,109,160
Spain,26,23,26,29,33,38,43,48,58,65,83,137
France,15,16,17,18,26,19,19,18,19,22,29,37
Italy,8,9,11,11,12,14,16,18,21,30,38,56
Cyprus,32,33,34,35,35,34,35,36,40,41,43,54
Latvia,-,-,-,-,-,-,-,-,-,-,-,-
Lithuania,-,-,-,-,-,-,-,-,-,-,-,-
Luxembourg (Grand-Duché),0,0,0,0,0,0,0,0,1,2,2,2
Hungary,0,0,0,0,0,1,2,2,2,2,2,3
Netherlands,6,7,8,10,12,14,16,19,20,22,22,23
Austria,42,48,55,58,64,69,74,80,86,92,101,108
Poland,0,0,0,0,0,0,0,0,0,0,0,0
Portugal,16,16,17,18,18,19,20,21,21,23,24,28
Romania,0,0,0,0,0,0,0,0,0,0,0,0
Slovenia,-,-,-,-,-,-,-,-,-,-,-,-
Slovakia,0,0,0,0,0,0,0,0,0,0,0,0
Finland,0,0,0,0,1,1,1,1,1,1,1,1
Sweden,4,4,5,5,5,6,4,5,5,6,6,9
United Kingdom,6,6,7,7,11,13,16,20,25,30,37,46
Croatia,0,0,0,0,0,0,0,0,0,0,0,1
Turkey,159,179,210,236,262,287,318,350,375,385,402,420
Iceland,-,-,-,-,-,-,-,-,-,-,-,-
Norway,0,0,0,0,0,0,0,0,0,0,0,0
Switzerland,18,19,21,23,24,26,23,24,25,26,28,30
#-='Not applicable' or 'Real zero' or 'Zero by default' :=Not available "
#Source of Data:,Eurostat, http://spreadsheets.google.com/ccc?key=0Agol553XfuDZdFpCQU1CUVdPZ3M0djJBSE1za1NGV0E&hl=en_GB
#Last Update:,30.04.2009
#Date of extraction:,17 Aug 2009 07:41:12 GMT, http://epp.eurostat.ec.europa.eu/tgm/table.do?tab=table&init=1&plugin=1&language=en&pcode=ten00082
</code></pre> | 2,161,338 | 4 | 1 | null | 2010-01-29 09:43:52.26 UTC | 10 | 2015-09-22 18:17:35.75 UTC | 2010-01-30 21:14:13.507 UTC | null | 121,332 | null | 216,064 | null | 1 | 11 | graphics|r | 1,936 | <p>You can use <code>polygon</code> in base graphics, for instance</p>
<pre><code>x <- seq(as.POSIXct("1949-01-01", tz="GMT"), length=36, by="months")
y <- rnorm(length(x))
plot(x, y, type="n", ylim=c(-1,1)*max(abs(y)))
polygon(c(x, rev(x)), c(y, -rev(y)), col="cornflowerblue", border=NA)
</code></pre>
<p><strong>Update</strong>: Using <code>panel.polygon</code> from <code>lattice</code>:</p>
<pre><code>library("lattice")
library("RColorBrewer")
df <- data.frame(x=rep(x,3),
y=rnorm(3*length(x)),
variable=gl(3, length(x)))
p <- xyplot(y~x|variable, data=df,
ylim=c(-1,1)*max(abs(y)),
layout=c(1,3),
fill=brewer.pal(3, "Pastel2"),
panel=function(...) {
args <- list(...)
print(args)
panel.polygon(c(args$x, rev(args$x)),
c(args$y, -rev(args$y)),
fill=args$fill[panel.number()],
border=NA)
})
print(p)
</code></pre> |
2,054,218 | Formatting floats in Objective C | <p>I need to format a float (catchy title, he?) to 2 decimal places, but only if those decimal places have values that aren't zero. Example:</p>
<p>I have a NSTextField named 'answer', after I do some math with a couple of floats, I want to assign my 'answerFloat' variable to the 'answer' NSTextField. So far I've got:</p>
<pre><code>[answer setStringValue:[NSString stringWithFormat:@"%.2f", answerFloat]];
</code></pre>
<p>But that sets something like 45 to 45.00. I want whole numbers to be displayed without the zeroes, and any decimal numbers to be displayed with their respective decimal values.</p>
<p>Do I need to run some kind of check before giving it to stringWithFormat? Or does NSString offer a way to handle this?</p> | 2,054,276 | 4 | 0 | null | 2010-01-13 03:39:22.12 UTC | 7 | 2012-05-09 19:08:47.107 UTC | 2012-05-09 19:08:47.107 UTC | null | 44,390 | null | 177,218 | null | 1 | 33 | objective-c|string|cocoa|formatting|floating-point | 43,598 | <p>Have you tried the <code>%g</code> format specifier?</p>
<pre><code>NSLog([NSString stringWithFormat:@"%g, %g", 45.0, 45.5]);
</code></pre>
<blockquote>
<p>2010-01-12 19:54:38.651 foo[89884:10b]
45, 45.5</p>
</blockquote> |
1,833,581 | When to use intern() on String literals | <p>I see a lot of legacy code like this:</p>
<pre><code>class A {
public static final String CONSTANT = "value".intern();
...
}
</code></pre>
<p>I don't see any reason for the intern(), as in the Javadoc one can read: "All literal strings and string-valued constant expressions are interned." Is there some intent of this, maybe in past revisions of the language?</p> | 1,833,726 | 4 | 2 | null | 2009-12-02 15:21:27.983 UTC | 17 | 2017-08-20 22:10:45.66 UTC | 2013-08-22 07:25:39.45 UTC | null | 545,127 | null | 191,446 | null | 1 | 38 | java|string|string-interning | 5,889 | <p>This is a technique to ensure that <code>CONSTANT</code> is not actually a constant.</p>
<p>When the Java compiler sees a reference to a final static primitive or String, it inserts the actual value of that constant into the class that uses it. If you then change the constant value in the defining class but don't recompile the using class, it will continue to use the old value.</p>
<p>By calling intern() on the "constant" string, it is no longer considered a static constant by the compiler, so the using class will actually access the defining class' member on each use.</p>
<hr>
<p>JLS citations:</p>
<ul>
<li><p>definition of a compile-time constant: <a href="http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#5313" rel="noreferrer">http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#5313</a></p></li>
<li><p>implication of changes to a compile-time constant (about halfway down the page): <a href="http://docs.oracle.com/javase/specs/jls/se6/html/binaryComp.html#45139" rel="noreferrer">http://docs.oracle.com/javase/specs/jls/se6/html/binaryComp.html#45139</a></p></li>
</ul> |
2,251,699 | SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE" | <p>I've never seen the syntax <code>INSERT OR REPLACE INTO names (id, name) VALUES (1, "John")</code> used in SQL before, and I was wondering why it's better than <code>UPDATE names SET name = "John" WHERE id = 1</code>. Is there any good reason to use one over the other. Is this syntax specific to SQLite?</p> | 2,251,708 | 4 | 0 | null | 2010-02-12 12:18:03.15 UTC | 19 | 2022-07-27 15:02:00.533 UTC | 2018-05-24 17:32:57.683 UTC | null | 42,223 | null | 74,118 | null | 1 | 72 | sqlite|upsert | 136,402 | <p>UPDATE will not do anything if the row does not exist.</p>
<p>Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.</p> |
1,961,255 | Rename files using a regex with bash | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1086502/rename-multiple-files-at-once-in-unix">rename multiple files at once in unix</a> </p>
</blockquote>
<p>I would like to rename all files from a folder using a regex (add a name to the end of name) and move to another folder. </p>
<p>It my opinion, it should be looking like this:</p>
<pre><code>mv -v ./images/*.png ./test/*test.png
</code></pre>
<p>but it does not work.</p>
<p>Can anyone suggest me a solution?</p> | 1,961,270 | 4 | 2 | null | 2009-12-25 14:42:06.173 UTC | 20 | 2018-06-24 14:47:33.513 UTC | 2018-06-24 14:47:33.513 UTC | null | 123,109 | null | 193,718 | null | 1 | 77 | regex|bash | 101,936 | <p>Try this:</p>
<pre><code>for x in *.png;do mv $x test/${x%.png}test.png;done
</code></pre> |
2,176,991 | How would I display a TIFF images in all web browsers? | <p>How do I handle <a href="http://en.wikipedia.org/wiki/Tagged_Image_File_Format" rel="nofollow noreferrer">TIFF</a> images in HTML pages?</p>
<p>I have tried using the embed tag, object id, img, etc. But, I am unable to display the TIFF image in the HTML page.</p>
<p>I am not using Java, .NET, or any other alternatives in my project.</p>
<p><strong>UPDATE:</strong> Safari supports TIFF image loading. How can I load TIFF images in other browsers (IE, Mozilla, Firefox, etc.)?</p> | 2,177,012 | 4 | 0 | null | 2010-02-01 13:38:48.19 UTC | 18 | 2021-12-06 13:55:05.15 UTC | 2021-12-06 13:55:05.15 UTC | null | 13,420,795 | null | 144,300 | null | 1 | 101 | html|image|tiff | 219,474 | <p>This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:</p>
<p><a href="http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support" rel="noreferrer">http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support</a></p>
<p>Where are you getting the tiff images from? Is it possible for them to be generated in a different format?</p>
<p>If you have a static set of images then I'd recommend using something like <a href="http://www.corel.com/servlet/Satellite/gb/en/Product/1184951547051" rel="noreferrer">PaintShop Pro</a> to batch convert them, changing the format.</p>
<p>If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.</p> |
10,690,466 | Redirect to a hash from the controller using "RedirectToAction" | <p>Hello I want to return an anchor from Mvc Controller </p>
<p>Controller name= DefaultController;</p>
<pre><code>public ActionResult MyAction(int id)
{
return RedirectToAction("Index", "region")
}
</code></pre>
<p>So that the url when directed to index is </p>
<pre><code>http://localhost/Default/#region
</code></pre>
<p>So that </p>
<pre><code><a href=#region>the content should be focus here</a>
</code></pre>
<p>I am not asking if you can do it like this: <a href="https://stackoverflow.com/questions/7904835/how-can-i-add-an-anchor-tag-to-my-url">How can I add an anchor tag to my URL?</a></p> | 10,690,511 | 4 | 2 | null | 2012-05-21 18:19:03.163 UTC | 17 | 2018-09-13 14:10:39.98 UTC | 2017-05-23 12:02:40.56 UTC | null | -1 | null | 475,337 | null | 1 | 94 | asp.net-mvc|asp.net-mvc-3|asp.net-mvc-4 | 26,314 | <p>I found this way:</p>
<pre><code>public ActionResult MyAction(int id)
{
return new RedirectResult(Url.Action("Index") + "#region");
}
</code></pre>
<p>You can also use this verbose way:</p>
<pre><code>var url = UrlHelper.GenerateUrl(
null,
"Index",
"DefaultController",
null,
null,
"region",
null,
null,
Url.RequestContext,
false
);
return Redirect(url);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ee703653.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ee703653.aspx</a></p> |
28,807,774 | PHP - Add one week to a user defined date | <p>There's more than likely going to be a duplicate for this question, but I'm struggling to find a precise answer for my problem. </p>
<p>The user enters a starting date for a client's rent (on a form on a previous page), then it needs to generate the next date (one week later) that the client is required to pay. For example: </p>
<pre><code>$start_date = $_POST['start_date'];
$date_to_pay = ???
</code></pre>
<p>Lets say the user enters in 2015/03/02: </p>
<pre><code>$start_date = "2015/03/02";
</code></pre>
<p>I then want the date to pay to be equal to a week later (2015/03/09): </p>
<pre><code>$date_to_pay = "2015/03/09";
</code></pre>
<p>How would one go around doing this? Many thanks.</p> | 28,807,856 | 5 | 3 | null | 2015-03-02 10:41:26.56 UTC | 1 | 2020-06-17 05:32:58.677 UTC | null | null | null | null | 4,453,899 | null | 1 | 15 | php|html | 39,436 | <p>You can try this</p>
<pre><code>$start_date = "2015/03/02";
$date = strtotime($start_date);
$date = strtotime("+7 day", $date);
echo date('Y/m/d', $date);
</code></pre> |
26,109,851 | Code signing is required for product type Unit Test Bundle in SDK iOS 8.0 | <p>Getting </p>
<blockquote>
<p>Code signing is required for product type 'Unit Test Bundle' in SDK
'iOS 8.0'</p>
</blockquote>
<p>My app target is code signing just fine - but my test target is not. I bought a new computer, created a new development certificate from the computer, updated the provisioning profile accordingly, installed both, but can't get past this code signing error.</p>
<p>Any way of wiping all certs/profiles locally so I can reinstall?</p>
<p>Probably some kind of bug.</p> | 26,372,701 | 11 | 1 | null | 2014-09-29 22:21:50.497 UTC | 24 | 2017-01-03 09:57:06.627 UTC | null | null | null | null | 1,543,216 | null | 1 | 129 | ios|objective-c|xcode | 106,013 | <p>The problem is the project is under source control and every time I pull the .xcodeproj is updated. And since my provisioning profile is different than the one in source control, the Unit Test target automatically switches to "Do not code sign". So I simply have to set the profile there after each git pull.</p>
<p>Apparently if deploying to a device, if there is a unit test target, it must be code signed.</p>
<p>Steps:</p>
<p>1) Change target to your test target (AppnameTests)</p>
<p><img src="https://i.stack.imgur.com/khXSU.png" alt="enter image description here"></p>
<p>2) Make sure "Code Signing Identity" is NOT "Don't Code Sign". Pick a profile to sign with</p>
<p><img src="https://i.stack.imgur.com/R4Ex9.png" alt="enter image description here"></p>
<p>That is all I had to change to get it to work.</p> |
26,091,744 | JSHint thinks Jasmine functions are undefined | <p>I've got a Grunt setup which uses Karma+Jasmine and JSHint. Whenever I run JSHint on my spec file, I get a series of "undefined" errors, most of which are for Jasmine's built-in functions. For example:</p>
<pre><code>Running "jshint:test" (jshint) task
js/main.spec.js
3 |describe("loadMatrix()", function() {
^ 'describe' is not defined.
4 | it("should not assign a value if no arg is passed.", function() {
^ 'it' is not defined.
</code></pre>
<p>(I also get some undefined errors for the variables and functions from the JS file that my spec is meant to test against, but I'm not sure why that is and it may be a separate issue.)</p>
<p>My Karma config file has <code>frameworks: [ "jasmine" ]</code> in it, I don't have any globals set for JSHint, and I don't have a <code>.jshintrc</code> file since I'm configuring it in Grunt. I did try adding Jasmine's functions as JSHint globals in my Gruntfile at one point, but setting them as either <code>true</code> or <code>false</code> didn't make a difference—the errors still persisted when JSHint ran.</p>
<p>What am I missing? I can't seem to do anything to get JSHint to skip definition checking for Jasmine's functions in my spec file.</p> | 26,133,415 | 4 | 2 | null | 2014-09-29 02:29:02.523 UTC | 5 | 2015-12-11 13:14:53.74 UTC | null | null | null | user1282270 | null | null | 1 | 29 | javascript|gruntjs|jasmine|karma-runner|jshint | 12,560 | <p>MINOR CORRECTION - there should be "" around predef in the .jshintrc file.</p>
<p>Fixed by adding this to the <code>jshint</code> options in my <code>Gruntfile.coffee</code>:</p>
<pre><code>predef: [
"jasmine"
"describe"
"xdescribe"
"before"
"beforeEach"
"after"
"afterEach"
"it"
"xit"
"it"
"inject"
"expect"
"spyOn"
]
</code></pre>
<p><code>.jshintrc</code>:</p>
<pre><code>"predef": [
"jasmine",
"describe",
"xdescribe",
"before",
"beforeEach",
"after",
"afterEach",
"it",
"xit",
"it",
"inject",
"expect",
"spyOn",
]
</code></pre> |
7,523,741 | How do you check if a website is online in C#? | <p>I want my program in C# to check if a website is online prior to executing, how would I make my program ping the website and check for a response in C#?</p> | 7,523,808 | 5 | 4 | null | 2011-09-23 02:47:48.503 UTC | 13 | 2021-02-08 06:19:18.933 UTC | null | null | null | null | 763,725 | null | 1 | 39 | c# | 65,405 | <p>You have use <code>System.Net.NetworkInformation.Ping</code> see below.</p>
<pre><code>var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.google.com");
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
return;
</code></pre> |
7,671,220 | Creating method dynamically, and executing it | <p><strong>Background:</strong></p>
<p>I want to define few <code>static</code> methods in C# , and generate IL code as byte array, from one of these methods, selected at runtime (on client), and send the byte array over network to another machine (server) where it should be executed after re-generating the IL code from the byte array. </p>
<p><strong>My Attempt:</strong> (<a href="http://en.wikipedia.org/wiki/Proof_of_concept">POC</a>)</p>
<pre><code>public static class Experiment
{
public static int Multiply(int a, int b)
{
Console.WriteLine("Arguments ({0}, {1})", a, b);
return a * b;
}
}
</code></pre>
<p>And then I get the IL code of the method body, as:</p>
<pre><code>BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
MethodInfo meth = typeof(Experiment).GetMethod("Multiply", flags);
byte[] il = meth.GetMethodBody().GetILAsByteArray();
</code></pre>
<p>So far I didn't create anything dynamically. But I've IL code as byte array, and I want to create an assembly, then a module in it, then a type, then a method - all dynamically. When creating the method body of the dynamically created method, I use the IL code which I got using reflection in the above code.</p>
<p>The code-generation code is as follows:</p>
<pre><code>AppDomain domain = AppDomain.CurrentDomain;
AssemblyName aname = new AssemblyName("MyDLL");
AssemblyBuilder assemBuilder = domain.DefineDynamicAssembly(
aname,
AssemblyBuilderAccess.Run);
ModuleBuilder modBuilder = assemBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = modBuilder.DefineType("MyType",
TypeAttributes.Public | TypeAttributes.Class);
MethodBuilder mb = tb.DefineMethod("MyMethod",
MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard,
typeof(int), // Return type
new[] { typeof(int), typeof(int) }); // Parameter types
mb.DefineParameter(1, ParameterAttributes.None, "value1"); // Assign name
mb.DefineParameter(2, ParameterAttributes.None, "value2"); // Assign name
//using the IL code to generate the method body
mb.CreateMethodBody(il, il.Count());
Type realType = tb.CreateType();
var meth = realType.GetMethod("MyMethod");
try
{
object result = meth.Invoke(null, new object[] { 10, 9878 });
Console.WriteLine(result); //should print 98780 (i.e 10 * 9878)
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
</code></pre>
<p>But instead of printing <code>98780</code> on the output window, it throws an exception saying,</p>
<blockquote>
<p>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeLoadException: Could not load type 'Invalid_Token.0x0100001E' from assembly 'MyDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.<br>
at MyType.MyMethod(Int32 value1, Int32 value2)
[...]</p>
</blockquote>
<p>Please help me figuring out the cause of the error, and how to fix it.</p> | 8,194,550 | 6 | 2 | null | 2011-10-06 07:14:01.48 UTC | 12 | 2011-11-25 09:33:25.047 UTC | 2011-11-19 14:06:29.283 UTC | null | 415,784 | null | 415,784 | null | 1 | 27 | c#|reflection|cil|reflection.emit|il | 9,568 | <p>Run ildasm.exe on an arbitrary assembly. Use View + Show token values and look at some disassembled code. You'll see that the IL contains references to other methods and variables through a number. The number is an index into the metadata tables for an assembly.</p>
<p>Perhaps you now see the problem, you cannot transplant a chunk of IL from one assembly to another unless that target assembly has the <em>same metadata</em>. Or unless you replace the metadata token values in the IL with values that match the metadata of the target assembly. This is wildly impractical of course, you essentially end up duplicating the assembly. Might as well make a copy of the assembly. Or for that matter, might as well use the existing IL in the original assembly.</p>
<p>You need to think this through a bit, it is pretty unclear what you actually try to accomplish. The System.CodeDom and Reflection.Emit namespaces are available to dynamically generate code.</p> |
14,231,170 | SELECT with LIMIT in Codeigniter | <p>I have a site develop in Codeigniter, and in my model I have a function like this:</p>
<pre><code>function nationList($limit=null, $start=null) {
if ($this->session->userdata('language')=="it")
$this->db->select('nation.id, nation.name_it as name');
if ($this->session->userdata('language')=="en")
$this->db->select('nation.id, nation.name_en as name');
$this->db->from('nation');
$this->db->order_by("name", "asc");
$this->db->limit($limit, $start);
$query = $this->db->get();
$nation = array();
foreach ($query->result() as $row)
array_push($nation, $row);
return $nation;
}
</code></pre>
<p>And if into my controller I call the function without limit and start doesn't return result like this:</p>
<pre><code>$data["nationlist"] = $this->Nation_model->nationList();
</code></pre>
<p>Instead if I set limit and start works!
If limit and start are null, Why doesn't return result? I don't want to make a second function or a control if limit and start are null.
How can I solve this when limit and start are null without a control or a second function to make useful the code and more efficient? </p> | 14,231,248 | 3 | 7 | null | 2013-01-09 08:37:54.9 UTC | 3 | 2020-07-15 08:19:59.75 UTC | null | null | null | null | 1,427,138 | null | 1 | 20 | php|sql|codeigniter | 186,196 | <p>Try this...</p>
<pre><code>function nationList($limit=null, $start=null) {
if ($this->session->userdata('language') == "it") {
$this->db->select('nation.id, nation.name_it as name');
}
if ($this->session->userdata('language') == "en") {
$this->db->select('nation.id, nation.name_en as name');
}
$this->db->from('nation');
$this->db->order_by("name", "asc");
if ($limit != '' && $start != '') {
$this->db->limit($limit, $start);
}
$query = $this->db->get();
$nation = array();
foreach ($query->result() as $row) {
array_push($nation, $row);
}
return $nation;
}
</code></pre> |
14,106,248 | Yeoman inside ExpressJS | <p>I'd still like to try to get an example running w/ Yeoman and Express. </p>
<p>I tried the following and it worked "okay", but I'm stuck merging the routes. (over simplified for readability)</p>
<pre><code>mkdir test
cd test
express
mkdir app
cd app
mkdir js
cd js
yeoman angular
</code></pre>
<p>Then I changed "output:dist" to "output:../../public" in the Gruntfile.js</p>
<p>Now, both servers run okay on their own (e.g. yeoman server and node app.js). I can also run 'yeoman build' now to output the minified JS to /public in the express app. </p>
<p>I'm a bit fuzzy on how the routes might merge? I would like / to pull up the Angular route and not the express route, etc. The angular-express-seed examples on github look okay, but I would still like Yeoman integrated into the project. </p>
<p>Any suggestions would be appreciated. </p> | 14,112,102 | 6 | 0 | null | 2012-12-31 21:38:30.817 UTC | 15 | 2013-11-20 14:00:52.017 UTC | null | null | null | null | 1,637,301 | null | 1 | 24 | node.js|angularjs|express|yeoman | 8,269 | <p>I would recommend this structure for yeoman + expressjs:</p>
<pre><code>mkdir app
cd app
yeoman angular
express .
</code></pre>
<p>So your dir tree should look like this:</p>
<pre><code>.
├── app
│ ├── 404.html
│ ├── favicon.ico
│ ├── index.html
│ ├── robots.txt
│ ├── scripts
│ │ ├── controllers
│ │ │ └── main.js
│ │ ├── vendor
│ │ │ ├── angular.js
│ │ │ ├── angular.min.js
│ │ │ ├── es5-shim.min.js
│ │ │ └── json3.min.js
│ │ └── yeoman-test.js
│ ├── styles
│ │ └── main.css
│ └── views
│ └── main.html
├── app.js
├── Gruntfile.js
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── user.js
├── test
│ ├── lib
│ │ └── angular-mocks.js
│ └── spec
│ └── controllers
│ └── main.js
├── testacular.conf.js
└── views
├── index.jade
└── layout.jade
</code></pre>
<p>You can remove the now redundant <code>public</code> directory (we're going to serve from <code>app</code> instead):</p>
<pre><code>rm -rf public
</code></pre>
<p>And now in <code>app.js</code>, you need to change which dir to serve static files from. Change this line:</p>
<pre><code>app.use(express.static(path.join(__dirname, 'public')));
</code></pre>
<p>to this:</p>
<pre><code>app.use(express.static(path.join(__dirname, 'app')));
</code></pre>
<p>And that should be about it. There's one careat in that you now have two "index" files -- one in <code>views/index.jade</code>, and the other in <code>app/index.html</code>. Removing the <code>app/index.html</code> currently breaks yeoman, so my advice is to get rid of the route for <code>app/index.jade</code> and just make edits to <code>index.html</code>.</p>
<p>Hope this helps!</p> |
14,161,415 | mysql process cannot be stopped | <p>I have recently installed 5.5.28-29.2 Percona Server (GPL), Release 29.2 in a Ubuntu 12.04 OS Desktop. I have tried to stop the server using different methods:</p>
<pre><code>- sudo /etc/init.d/mysql stop
- sudo kill -9 pid
- mysqladmin -u root -p shutdown
</code></pre>
<p>All this methods stop the process, however it starts up automatically after it dies. I have checked syslog (/var/log/syslog/) and always shows me the next trace:</p>
<pre><code>Jan 4 17:50:44 kernel: [ 1915.494219] init: mysql main process (17311) killed by KILL signal
Jan 4 17:50:44 kernel: [ 1915.494245] init: mysql main process ended, respawning
Jan 4 17:50:44 kernel: [ 1915.500025] type=1400 audit(1357318244.557:48): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=18458 comm="apparmor_parser"
Jan 4 17:50:46 /etc/mysql/debian-start[18501]: Upgrading MySQL tables if necessary.
Jan 4 17:50:46 /etc/mysql/debian-start[18504]: /usr/bin/mysql_upgrade: the '--basedir' option is always ignored
Jan 4 17:50:46 /etc/mysql/debian-start[18504]: Looking for 'mysql' as: /usr/bin/mysql
Jan 4 17:50:46 /etc/mysql/debian-start[18504]: Looking for 'mysqlcheck' as: /usr/bin/mysqlcheck
Jan 4 17:50:46 /etc/mysql/debian-start[18504]: This installation of MySQL is already upgraded to 5.5.28, use --force if you still need to run mysql_upgrade
Jan 4 17:50:46 /etc/mysql/debian-start[18515]: Checking for insecure root accounts.
Jan 4 17:50:46 /etc/mysql/debian-start[18520]: Triggering myisam-recover for all MyISAM tables
</code></pre>
<p>Do you know the reason why the process restarts automatically ?
Thank you in advance!!</p> | 15,960,688 | 7 | 0 | null | 2013-01-04 16:58:11.42 UTC | 8 | 2017-10-25 12:41:53.37 UTC | null | null | null | null | 1,949,163 | null | 1 | 30 | mysql|ubuntu|percona | 60,952 | <p>I was having this exact same problem. Running the <code>kill</code> command would kill the process, but in my case it would keep popping up again under a different process ID.</p>
<p>The only way I could figure out how to stop it for good was this:</p>
<pre><code>sudo stop mysql
</code></pre>
<p>Hope that helps.</p>
<p>Source: <a href="http://www.itfromscratch.com/how-to-stop-the-percona-mysql-server/" rel="noreferrer">http://www.itfromscratch.com/how-to-stop-the-percona-mysql-server/</a></p> |
14,104,865 | How can I use Debug.Write with dynamic data? | <p>I am doing some scripting of Adobe InDesign. Their COM implementation is really designed for VB, so it's not rigorous about reporting data types, occasionally necessitating the use of dynamics.</p>
<p>I'm trying to debug a chunk of code that looks like this:</p>
<pre><code>foreach (dynamic pi in current.PageItems)
{
if (pi is TextFrame)
{
var frame = pi as TextFrame;
var str = frame.Contents.ToString();
Debug.WriteLine(str);
}
}
</code></pre>
<p>This gives me a RuntimeBinderException like this:</p>
<blockquote>
<p>Additional information: Cannot dynamically invoke method 'WriteLine'
because it has a Conditional attribute</p>
</blockquote>
<p>I get that the problem is that with Conditional attributes, the version of the code that needs to handle the type the dynamic resolves to at runtime might have gotten compiled out, but I'm explicitly converting what I want to debug to a string, so I don't see why this is still happening. How can I work around this problem?</p> | 14,104,895 | 3 | 0 | null | 2012-12-31 18:17:52.917 UTC | null | 2012-12-31 18:23:58.103 UTC | null | null | null | null | 9,279 | null | 1 | 33 | c#|visual-studio-2010 | 12,058 | <p>You're being bitten by your use of <code>var</code> here, is my guess.</p>
<p>I'm assuming that <code>Contents</code> is <code>dynamic</code>.</p>
<p>Consider this example:</p>
<pre><code>dynamic d = null;
var s = d.ToString();
</code></pre>
<p><code>s</code> is <code>dynamic</code> not <code>string</code>.</p>
<p>You'll want to cast the object to <code>object</code> before calling <code>ToString</code>, or cast the result of <code>ToString</code> to a <code>string</code>. The point is that at some point, somewhere, you need a cast to get out of the <code>dynamic</code> cycle.</p>
<p>This is how I'd solve it:</p>
<pre><code>string str = ((object)frame.Contents).ToString();
Debug.WriteLine(str);
</code></pre>
<p>or </p>
<pre><code>string str = frame.Contents.ToString() as string;
Debug.WriteLine(str);
</code></pre> |
14,064,336 | ARC and CFRelease? | <p>I'm slightly confused. Everywhere I've read, suggest that when using ARC, you still need to release core foundation objects which makes sense, ARC doesn't manage them. However, I've got a method which uses some CF methods/objects which I used <code>CFRelease</code> on, but that then caused the app to crash. Uncommenting my <code>CFRelease</code>s fixes the issue but then I'm assuming I've got a memory leak?</p>
<p>Could someone please explain which things need releasing and which don't, or anything else that's wrong with this code?</p>
<pre><code>+ (NSString *) fileExtensionForMimeType:(NSString *)type
{
CFStringRef mimeType = (__bridge CFStringRef)type;
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
NSString *ext = (__bridge NSString *)extension;
// CFRelease(mimeType);
// CFRelease(uti);
// CFRelease(extension);
return ext;
}
</code></pre>
<p>The three commented out <code>CFRelease</code> calls fix the issue as mentioned, but I know it's wrong. What should I be doing?</p> | 14,064,386 | 3 | 3 | null | 2012-12-28 03:49:25.287 UTC | 9 | 2013-10-29 22:42:41.673 UTC | 2013-01-01 15:05:01.913 UTC | null | 231,684 | null | 764,195 | null | 1 | 35 | objective-c|ios|cocoa-touch|automatic-ref-counting | 12,300 | <p>You can't release <code>mimeType</code> because you don't own it. You didn't transfer ownership with the <code>__bridge</code> cast.</p>
<p>You should be releasing <code>uti</code> since you have created it.</p>
<p>You should also release <code>extension</code> since you created it as well, but that will likely cause issues with <code>ext</code>. Instead, transfer ownership to <code>ext</code>.</p>
<p>I'd suggest the following:</p>
<pre><code>+ (NSString *) fileExtensionForMimeType:(NSString *)type {
CFStringRef mimeType = (__bridge CFStringRef)type;
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
NSString *ext = (__bridge_transfer NSString *)extension;
// CFRelease(mimeType); // not owned
if (uti) CFRelease(uti);
// CFRelease(extension); // ownership was transferred
return ext;
}
</code></pre> |
14,234,917 | Django - How to get self.id when saving a new object? | <p>I have a problem in one of my models. I'm uploading an image, and I want to store the id (pk in the database table) but I need to know at which point Django will have access to <code>self.id</code>.</p>
<p><strong>models.py</strong></p>
<pre><code>class BicycleAdItemKind(MPTTModel):
def url(self, filename):
pdb.set_trace()
url = "MultimediaData/HelpAdImages/ItemKind/%s/%s" % (self.id, filename)
return url
def item_kind_image(self):
return '<img align="middle" src="/media/%s" height="60px" />' % self.image
item_kind_image.allow_tags = True
# Bicicleta completa, Componentes para bicicleta, Acessorios para ciclista
n_item_kind = models.CharField(max_length=50)
parent = TreeForeignKey('self', null=True,
blank=True, related_name='children')
description = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=url, null=True, blank=True)
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.n_item_kind
class MPTTMeta:
order_insertion_by = ['n_item_kind']
</code></pre>
<p>The problem is in the <code>url()</code> method; I can only get <code>self.id</code> when updating an object, I don't get the <code>self.id</code> when creating a new object. How can I modify this model so that I get <code>self.id</code> when creating a new object?</p>
<p>With the current code, when I'm creating a new object I will end up with a url like:</p>
<pre><code>MultimediaData/HelpAdImages/ItemKind/None/somefile.jpg
</code></pre>
<p>And I need to have something like:</p>
<pre><code>MultimediaData/HelpAdImages/ItemKind/35/somefile.jpg
</code></pre>
<p>Any clues?</p> | 14,236,472 | 6 | 2 | null | 2013-01-09 12:10:13.17 UTC | 3 | 2021-05-23 01:11:22.197 UTC | 2013-01-09 12:39:46.557 UTC | null | 1,442,342 | null | 488,735 | null | 1 | 44 | django|django-models|django-mptt | 34,955 | <p>If it's a new object, you need to save it first and then access self.id, because</p>
<pre><code>"There's no way to tell what the value of an ID will be before you call save(),
because that value is calculated by your database, not by Django."
</code></pre>
<p>Check django's document <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/">https://docs.djangoproject.com/en/dev/ref/models/instances/</a></p> |
13,989,319 | Resolved color instead of a resource id | <p>Recently I've seen appeared a lint error in my code:</p>
<blockquote>
<p>Should pass resolved color instead of resource id here:
getResources().getColor(R.color.maps_list_background_color)<br>
MyClass.java /myapp/android/maps line 107 Android Lint Problem</p>
</blockquote>
<p>I know how to resolve it the answer is in the error, the thing is I don't get why they have added this error in the linter. </p> | 18,738,955 | 7 | 2 | null | 2012-12-21 11:28:55.413 UTC | 8 | 2021-12-06 11:59:00.697 UTC | 2015-09-22 17:57:39.303 UTC | null | 165,071 | null | 1,873,110 | null | 1 | 54 | android|lint | 34,458 | <blockquote>
<p>Methods that take a color in the form of an integer should be passed an RGB triple, not the actual color resource id. You must call getResources.getColor(resource).</p>
</blockquote>
<p>The function you are calling is expecting an integer that is an RGB triple, not just the id of a color resource. The color resource id is still an integer, but would not produce the color that you are expecting if it was used as the RGB triple. In order to pass it the correct RGB triple for your color, you must resolve it with the <code>getResources().getColor(R.color.example_color)</code> call.</p> |
13,998,901 | Generating a Random Hex Color in Python | <p>For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random <code>Hex</code> colors in python/django. It's easy enough to generate RGB colors, but to store them I would either need to a) make three extra columns in my "Member" model or b) store them all in the same column and use commas to separate them, then, later, parse the colors for the HTML. Neither of these are very appealing, so, again, I'm wondering how to generate random <code>Hex</code> colors in python/django.</p> | 14,019,260 | 18 | 0 | null | 2012-12-22 00:25:45.47 UTC | 20 | 2022-07-05 18:33:08.163 UTC | null | null | null | null | 1,218,699 | null | 1 | 87 | python|django | 112,332 | <pre><code>import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
</code></pre> |
43,354,242 | How do I mock part of a python constructor just for testing? | <p>I am new to Python, so I apologize if this is a duplicate or overly simple question. I have written a coordinator class that calls two other classes that use the kafka-python library to send/read data from Kafka. I want to write a unit test for my coordinator class but I'm having trouble figuring out how to best to go about this. I was hoping that I could make an alternate constructor that I could pass my mocked objects into, but this doesn't seem to be working as I get an error that test_mycoordinator cannot be resolved. Am I going about testing this class the wrong way? Is there a pythonic way I should be testing it?</p>
<p>Here is what my test class looks like so far:</p>
<pre><code>import unittest
from mock import Mock
from mypackage import mycoordinator
class MyTest(unittest.TestCase):
def setUpModule(self):
# Create a mock producer
producer_attributes = ['__init__', 'run', 'stop']
mock_producer = Mock(name='Producer', spec=producer_attributes)
# Create a mock consumer
consumer_attributes = ['__init__', 'run', 'stop']
data_out = [{u'dataObjectID': u'test1'},
{u'dataObjectID': u'test2'},
{u'dataObjectID': u'test3'}]
mock_consumer = Mock(
name='Consumer', spec=consumer_attributes, return_value=data_out)
self.coor = mycoordinator.test_mycoordinator(mock_producer, mock_consumer)
def test_send_data(self):
# Create some data and send it to the producer
count = 0
while count < 3:
count += 1
testName = 'test' + str(count)
self.coor.sendData(testName , None)
</code></pre>
<p>And here is the class I am trying to test:</p>
<pre><code>class MyCoordinator():
def __init__(self):
# Process Command Line Arguments using argparse
...
# Initialize the producer and the consumer
self.myproducer = producer.Producer(self.servers,
self.producer_topic_name)
self.myconsumer = consumer.Consumer(self.servers,
self.consumer_topic_name)
# Constructor used for testing -- DOES NOT WORK
@classmethod
def test_mycoordinator(cls, mock_producer, mock_consumer):
cls.myproducer = mock_producer
cls.myconsumer = mock_consumer
# Send the data to the producer
def sendData(self, data, key):
self.myproducer.run(data, key)
# Receive data from the consumer
def getData(self):
data = self.myconsumer.run()
return data
</code></pre> | 43,354,425 | 1 | 2 | null | 2017-04-11 19:04:08.343 UTC | 6 | 2018-02-25 10:28:52.56 UTC | 2017-04-11 19:11:05.163 UTC | null | 5,687,992 | null | 5,687,992 | null | 1 | 28 | python|unit-testing|mocking|python-mock | 54,768 | <p>There is no need to provide a separate constructor. Mocking <em>patches your code</em> to replace objects with mocks. Just use the <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch" rel="noreferrer"><code>mock.patch()</code> decorator</a> on your test methods; it'll pass in references to the generated mock objects.</p>
<p>Both <code>producer.Producer()</code> and <code>consumer.Consumer()</code> are then mocked out <em>before</em> you create the instance:</p>
<pre><code>import mock
class MyTest(unittest.TestCase):
@mock.patch('producer.Producer', autospec=True)
@mock.patch('consumer.Consumer', autospec=True)
def test_send_data(self, mock_consumer, mock_producer):
# configure the consumer instance run method
consumer_instance = mock_consumer.return_value
consumer_instance.run.return_value = [
{u'dataObjectID': u'test1'},
{u'dataObjectID': u'test2'},
{u'dataObjectID': u'test3'}]
coor = MyCoordinator()
# Create some data and send it to the producer
for count in range(3):
coor.sendData('test{}'.format(count) , None)
# Now verify that the mocks have been called correctly
mock_producer.assert_has_calls([
mock.Call('test1', None),
mock.Call('test2', None),
mock.Call('test3', None)])
</code></pre>
<p>So the moment <code>test_send_data</code> is called, the <code>mock.patch()</code> code replaces the <code>producer.Producer</code> reference with a mock object. Your <code>MyCoordinator</code> class then uses those mock objects rather than the real code. calling <code>producer.Producer()</code> returns a new mock object (the same object that <code>mock_producer.return_value</code> references), etc.</p>
<p>I've made the assumption that <code>producer</code> and <code>consumer</code> are top-level module names. If they are not, provide the full import path. From the <code>mock.patch()</code> documentation:</p>
<blockquote>
<p><em>target</em> should be a string in the form <code>'package.module.ClassName'</code>. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling <code>patch()</code> from. The target is imported when the decorated function is executed, not at decoration time.</p>
</blockquote> |
9,133,102 | How to grab substring before a specified character in JavaScript? | <p>I am trying to extract everything before the ',' comma. How do I do this in JavaScript or jQuery? I tried this and not working..</p>
<pre class="lang-none prettyprint-override"><code>1345 albany street, Bellevue WA 42344
</code></pre>
<p>I just want to grab the street address.</p>
<pre class="lang-js prettyprint-override"><code>var streetaddress= substr(addy, 0, index(addy, '.'));
</code></pre> | 9,133,209 | 12 | 1 | null | 2012-02-03 17:49:29.317 UTC | 42 | 2022-07-31 07:31:10.787 UTC | 2022-06-29 20:53:05.247 UTC | null | 7,941,251 | null | 1,128,717 | null | 1 | 344 | javascript|substring|substr | 566,606 | <pre><code>var streetaddress = addy.substr(0, addy.indexOf(','));
</code></pre>
<p>While it's not the best place for definitive information on what each method does (<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" rel="noreferrer">mozilla developer network</a> is better for that) <a href="http://www.w3schools.com/js/default.asp" rel="noreferrer">w3schools.com</a> is good for introducing you to syntax.</p> |
44,431,212 | YQL: html table is no longer supported | <p>I use YQL to get some html-pages for reading information out of it.
Since today I get the return message "html table is no longer supported. See <a href="https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm" rel="noreferrer">https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm</a> for YQL Terms of Use"</p>
<p>Example in the console: <a href="https://developer.yahoo.com/yql/console/#h=select+" rel="noreferrer">https://developer.yahoo.com/yql/console/#h=select+</a>*+from+html+where+url%3D%22http%3A%2F%2Fwww.google.de%22</p>
<p>Did Yahoo stop this service? Does anybody know a kind of announcement from Yahoo? I am wondering whether this is simply a bug or whether they really stopped this service...</p>
<p>All documentation is still there (html scraping):
<a href="https://developer.yahoo.com/yql/guide/yql-select-xpath.html" rel="noreferrer">https://developer.yahoo.com/yql/guide/yql-select-xpath.html</a> ,
<a href="https://developer.yahoo.com/yql/" rel="noreferrer">https://developer.yahoo.com/yql/</a></p>
<p>A while ago I posted in an YQL forum from Yahoo, now this one does not exist anymore (or at least I do not find it). How can you contact Yahoo to find out whether this service really stopped?</p>
<p>Best regards,
hebr3</p> | 44,472,749 | 4 | 5 | null | 2017-06-08 09:02:09.9 UTC | 10 | 2019-03-25 03:05:26.423 UTC | 2017-06-08 16:38:33.047 UTC | null | 8,130,292 | null | 8,130,292 | null | 1 | 18 | yql | 7,931 | <p>Thank you very much for your code.</p>
<p>It helped me to create my own script to read those pages which I need. I never programmed PHP before, but with your code and the wisdom of the internet I could change your script to my needs.</p>
<p>PHP</p>
<pre><code><?
header('Access-Control-Allow-Origin: *'); //all
$url = $_GET['url'];
if (substr($url,0,25) != "https://www.xxxx.yy") {
echo "Only https://www.xxxx.yy allowed!";
return;
}
$xpathQuery = $_GET['xpath'];
//need more hard check for security, I made only basic
function check($target_url){
$check = curl_init();
//curl_setopt( $check, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
//curl_setopt($check, CURLOPT_INTERFACE, "xxx.xxx.xxx.xxx");
curl_setopt($check, CURLOPT_COOKIEJAR, 'cookiemon.txt');
curl_setopt($check, CURLOPT_COOKIEFILE, 'cookiemon.txt');
curl_setopt($check, CURLOPT_TIMEOUT, 40000);
curl_setopt($check, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($check, CURLOPT_URL, $target_url);
curl_setopt($check, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($check, CURLOPT_FOLLOWLOCATION, false);
$tmp = curl_exec ($check);
curl_close ($check);
return $tmp;
}
// get html
$html = check($url);
$dom = new DOMDocument();
@$dom->loadHTML($html);
// apply xpath filter
$xpath = new DOMXPath($dom);
$elements = $xpath->query($xpathQuery);
$temp_dom = new DOMDocument();
foreach($elements as $n) $temp_dom->appendChild($temp_dom->importNode($n,true));
$renderedHtml = $temp_dom->saveHTML();
// return html in json response
// json structure:
// {html: "xxxx"}
$post_data = array(
'html' => $renderedHtml
);
echo json_encode($post_data);
?>
</code></pre>
<p>Javascript</p>
<pre><code>$.ajax({
url: "url of service",
dataType: "json",
data: { url: url,
xpath: "//*"
},
type: 'GET',
success: function() {
},
error: function(data) {
}
});
</code></pre> |
19,593,909 | git diff sees whole file as changed when it's not | <p>The git diff engine is seeing a whole file as changed when it has not. For example, take this commit: <a href="https://github.com/etiago/phpvirtualbox/commit/626e09958384f479f94011ac3b8301bd497aec51" rel="noreferrer">https://github.com/etiago/phpvirtualbox/commit/626e09958384f479f94011ac3b8301bd497aec51</a></p>
<p>Here we see that the file <strong>lib/vboxconnector.php</strong> has 2807 additions and 2778 deletions. Additionally, from doing a manual git diff I find that indeed, the whole file is taken in as a deletion (marked with minus) and a whole new file is taken as an addition. However, the files have a lot in common which Git simply ignored.</p>
<p>I've looked at <a href="https://stackoverflow.com/questions/12876350/diff-returning-entire-file-for-identical-files">diff returning entire file for identical files</a> but it does not seem to be the case as no white space changes exist between the two commits.</p>
<p>Furthermore, taking the two commits of the file (the one in <code>626e09958384f479f94011ac3b8301bd497aec51</code> and <code>626e09958384f479f94011ac3b8301bd497aec51^1</code>) and diff'ing them using Meld, I get the right diff analysis.</p>
<p>I've uploaded the two commits of the file to my Dropbox for convenience: <a href="https://dl.dropboxusercontent.com/u/59728/disposables/vboxconnector.php_1" rel="noreferrer">commit_1</a> <a href="https://dl.dropboxusercontent.com/u/59728/disposables/vboxconnector.php_2" rel="noreferrer">commit_2</a>.</p> | 19,594,092 | 1 | 2 | null | 2013-10-25 15:29:24.083 UTC | 16 | 2013-10-26 19:44:08.077 UTC | 2017-05-23 11:54:46.753 UTC | null | -1 | null | 392,921 | null | 1 | 70 | git|git-diff | 57,254 | <p>In <code>vboxconnector.php_1</code>, every line is terminated by a <code>CR</code> <code>LF</code> sequence.</p>
<p>In <code>vboxconnector.php_2</code>, every line is terminated by just <code>LF</code>.</p>
<p>Thus every line of the file has changed.</p>
<p>Try using <code>git diff --ignore-space-at-eol</code>.</p>
<p>You may also find some useful information in <a href="https://stackoverflow.com/q/1889559/77567">the answers to this question</a>.</p> |
19,449,615 | How to extract the row with min or max values? | <p>With a dataframe like this one:</p>
<pre><code> ID Year Temp ph
1 P1 1996 11.3 6.80
2 P1 1996 9.7 6.90
3 P1 1997 9.8 7.10
...
2000 P2 1997 10.5 6.90
2001 P2 1997 9.9 7.00
2002 P2 1997 10.0 6.93
</code></pre>
<p>if I want to know where the max value is I type:</p>
<pre><code>which.max(df$Temp)
</code></pre>
<p>and R print the index of the row, for example 665.</p>
<p>So, if I want to read and extract the column with all the related values, I have to type:</p>
<pre><code>df[665, ]
</code></pre>
<p>Isn't there a simpler way to know which ID is related to the max value of a specific column of the df?</p> | 19,449,769 | 4 | 3 | null | 2013-10-18 12:25:21.61 UTC | 11 | 2022-06-14 15:43:42.137 UTC | 2019-12-03 09:25:30.953 UTC | null | 680,068 | null | 2,509,085 | null | 1 | 44 | r|max|min | 130,570 | <p>You can include your <code>which.max</code> call as the first argument to your subsetting call:</p>
<pre><code>df[which.max(df$Temp),]
</code></pre> |
52,221,805 | Any way yet to auto-update (or just clear the cache on) a PWA on iOS? | <p>I have been struggling on iOS with something that works easily on Android: Getting my PWA to auto-update when there is a new version. I am not at all sure this is even possible on iOS. I have used vue.js and Quasar to build my app, and everything works out of the box on Android. Here is the (ugly, terrible) way things stand currently on the iOS version:</p>
<ol>
<li>I can check my own server for the version and compare it against the current one stored in my app (in indexedDB) and throw up a notice that there is a new version. So far so good.</li>
<li>Other than having the user MANUALLY CLEAR THE SAFARI CACHE (!!) there is no way I can figure out how to programmatically clear the PWA cache from within the app or force an upload in another way.</li>
</ol>
<p>So at this point I guess my questions are:</p>
<ol>
<li>Has ANYONE been able to get a PWA on iOS (11.3 or later) to auto-update when a new version is available?</li>
<li>Is there a way to clear the (safari) app cache from within my PWA?</li>
</ol>
<p>Obviously it is an incredibly awful user experience to notify the user that in order to update they must perform several steps outside of the app to be able to refresh it, but it seems this is where iOS stands at the moment unless I am missing something. Has anyone anywhere made this work?</p> | 52,238,757 | 3 | 4 | null | 2018-09-07 11:38:46.547 UTC | 12 | 2022-07-20 04:02:19.32 UTC | 2018-09-07 12:36:19.79 UTC | null | 209,860 | null | 209,860 | null | 1 | 21 | ios|vue.js|progressive-web-apps|quasar-framework | 17,370 | <p>After weeks and weeks of searching, I finally found a solution:</p>
<ol>
<li><p>I add a check for versionstring on the server, and return it to the app as mentioned above.</p>
</li>
<li><p>I look for it in localtstorage (IndexedDB) and if I don’t find it, I add it. If I do find it, I compare versions and if there is a newer one on the server, I throw up a dialog.</p>
</li>
<li><p>Dismissing this dialog (my button is labeled “update”) runs <code>window.location.reload(true)</code> and then stores the new versionstring in localstorage</p>
</li>
</ol>
<p>Voila! My app is updated! I can't believe it came down to something this simple, I could not find a solution anywhere. Hope this helps someone else!</p>
<p><strong>UPDATE SEPT 2019:</strong></p>
<p>There were a few problems with the technique above, notably that it was bypassing the PWA service worker mechanisms and that sometimes reload would not immediately load new content (because the current SW would not release the page). I have now a new solution to this that seems to work on all platforms:</p>
<pre><code>function forceSWupdate() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
registration.update()
}
})
}
}
forceSWupdate()
</code></pre>
<p>And inside my serviceworker I now throw up the dialog if there is an update, and do my <code>location.reload(true)</code> from there. This always results in my app being refreshed immediately (with the important caveat that I have added <code>skipWaiting</code> and <code>clientsClaim</code> directives to my registration).</p>
<p>This works on every platform the same, and I can programatically check for the update or wait for the service worker to do it by itself (although the times it checks vary greatly by platform, device, and other unknowable factors. Usually not more than 24 hours though.)</p> |
35,005,158 | What is the difference between @ComponentScan and @EnableAutoConfiguration in Spring Boot? | <p>What is the difference between the <code>@ComponentScan</code> and <code>@EnableAutoConfiguration</code> annotations in Spring Boot? Is it necessary to add these? My application works very well without these annotations. I just want to understand why we have to add them.</p> | 35,006,877 | 3 | 3 | null | 2016-01-26 00:40:16.35 UTC | 38 | 2019-11-01 18:00:36.247 UTC | 2016-01-26 01:25:28.68 UTC | null | 2,446,208 | null | 5,258,516 | null | 1 | 88 | java|spring|spring-mvc|spring-boot | 88,325 | <blockquote>
<p>What is the difference between the @ComponentScan and
@EnableAutoConfiguration annotations in Spring Boot?</p>
</blockquote>
<p><a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html" rel="noreferrer"><code>@EnableAutoConfiguration</code></a> annotation tells Spring Boot to "guess" how you will want to configure Spring, based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring will auto-configure an in-memory database.</p>
<p><a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html" rel="noreferrer"><code>@ComponentScan</code></a> tells Spring to look for other components, configurations, and services in the specified package. Spring is able to auto scan, detect and register your beans or components from pre-defined project package. If no package is specified current class package is taken as the root package. </p>
<blockquote>
<p>Is it necessary to add these?</p>
</blockquote>
<p>If you need Spring boot to Auto configure every thing for you <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html" rel="noreferrer"><code>@EnableAutoConfiguration</code></a> is required. You don't need to add it manually, spring will add it internally for you based on the annotation you provide.</p>
<p>Actually the <a href="https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html" rel="noreferrer"><code>@SpringBootApplication</code></a> annotation is equivalent to using <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html" rel="noreferrer"><code>@Configuration</code></a>, <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html" rel="noreferrer"><code>@EnableAutoConfiguration</code></a> and <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html" rel="noreferrer"><code>@ComponentScan</code></a> with their default attributes.</p>
<p><strong>See also:</strong></p>
<ul>
<li><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html" rel="noreferrer">Using the @SpringBootApplication annotation</a></li>
<li><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html" rel="noreferrer">Auto-configuration</a></li>
</ul> |
928,918 | Python File Read + Write | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre> | 928,943 | 5 | 0 | null | 2009-05-30 03:21:24.653 UTC | null | 2009-05-30 04:34:16.407 UTC | 2009-05-30 03:32:03.633 UTC | null | 74,980 | null | 74,980 | null | 1 | 6 | python|file | 41,941 | <p>Although this is easily doable, it does become easier with the <a href="http://docs.python.org/library/csv.html" rel="noreferrer">csv</a> module.</p>
<pre><code>>>> import csv
>>> reader = csv.reader(open('C:/www/stackoverflow.txt'), delimiter='\t')
>>> for row in reader:
... print row
...
['1', 'John Smith', 'Developer', 'http://twiiter.com/johns', 'Chicago, IL']
['2', 'John Doe', 'Developer', 'http://whatever.com', 'Tallahassee, FL']
</code></pre>
<p>Also, as pointed out, semicolons are not needed in Python. Try to kick that habit :)</p> |
497,782 | How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#? | <p>I have a string object </p>
<p>"with multiple characters and even special characters"</p>
<p>I am trying to use </p>
<pre><code>UTF8Encoding utf8 = new UTF8Encoding();
ASCIIEncoding ascii = new ASCIIEncoding();
</code></pre>
<p>objects in order to convert that string to ascii. May I ask someone to bring some light to this simple task, that is hunting my afternoon.</p>
<p>EDIT 1:
What we are trying to accomplish is getting rid of special characters like some of the special windows apostrophes. The code that I posted below as an answer will not take care of that. Basically </p>
<blockquote>
<p>O'Brian will become O?Brian. where ' is one of the special apostrophes</p>
</blockquote> | 497,842 | 5 | 1 | null | 2009-01-31 00:14:26.48 UTC | 9 | 2018-01-22 18:14:43.903 UTC | 2016-07-17 19:41:02.803 UTC | Geo | 2,226,988 | Geo | 47,222 | null | 1 | 11 | c#|encoding|utf-8|ascii|transliteration | 114,191 | <p>This was in response to your other question, that looks like it's been deleted....the point still stands.</p>
<p>Looks like a <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">classic Unicode to ASCII issue</a>. The trick would be to find <em>where</em> it's happening.</p>
<p>.NET works fine with Unicode, assuming <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx" rel="noreferrer">it's told it's Unicode</a> to begin with (or left at the default). </p>
<p>My <em>guess</em> is that your receiving app can't handle it. So, I'd probably use the <a href="http://msdn.microsoft.com/en-us/library/system.text.asciiencoding.aspx" rel="noreferrer">ASCIIEncoder</a> <a href="http://msdn.microsoft.com/en-us/library/system.text.encoder.fallback.aspx" rel="noreferrer">with</a> an <a href="http://msdn.microsoft.com/en-us/library/system.text.encoderreplacementfallback.aspx" rel="noreferrer">EncoderReplacementFallback</a> with String.Empty:</p>
<pre><code>using System.Text;
string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);
byte[] bAsciiString = encoder.GetBytes(inputString);
// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString);
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));
</code></pre>
<p>Of course, in the old days, we'd just loop though and remove any chars <a href="http://asciitable.com/" rel="noreferrer">greater than 127</a>...well, those of us in the US at least. ;)</p> |
1,339,601 | warning: returning reference to temporary | <p>I have a function like this</p>
<pre><code>const string &SomeClass::Foo(int Value)
{
if (Value < 0 or Value > 10)
return "";
else
return SomeClass::StaticMember[i];
}
</code></pre>
<p>I get <code>warning: returning reference to temporary</code>. Why is that? I thought the both values the function returns (reference to const char* "" and reference to a static member) cannot be temporary.</p> | 1,339,685 | 5 | 0 | null | 2009-08-27 08:17:26.11 UTC | 8 | 2017-08-21 06:52:16.4 UTC | null | null | null | null | 48,461 | null | 1 | 28 | c++|reference | 30,643 | <p>This is an example when an unwanted implicit conversion takes place. <code>""</code> is not a <code>std::string</code>, so the compiler tries to find a way to turn it into one. And by using the <code>string( const char* str )</code> constructor it succeeds in that attempt.
Now a temporary instance of <code>std::string</code> has been created that will be deleted at the end of the method call. Thus it's obviously not a good idea to reference an instance that won't exist anymore after the method call. </p>
<p>I'd suggest you either change the return type to <code>const string</code> or store the <code>""</code> in a member or static variable of <code>SomeClass</code>.</p> |
605,325 | Where are the schemas for XML files on an Android project? | <p>Where are the schemas (DTD or XML schema) for the XML files used on Android like AndroidManifest.xml or the layouts?</p> | 617,716 | 5 | 0 | null | 2009-03-03 06:21:07.567 UTC | 7 | 2021-05-11 16:21:36.027 UTC | null | null | null | J. Pablo Fernández | 6,068 | null | 1 | 37 | xml|android|schema|dtd | 28,782 | <p>The schemas don't exist as an xml file. Schemas are dependent upon what UI classes your program uses. There's a slightly better discussion <a href="http://groups.google.com/group/android-developers/browse_frm/thread/d85b6c2d0e301126/8dbbcb11543672e5?lnk=gst&q=schema+exist#8dbbcb11543672e5" rel="noreferrer">here</a>.</p> |
1,222,581 | How get the T-SQL code to find duplicates? | <p>MS Access has a button to generate sql code for finding duplicated rows. I don't know if SQL Server 2005/2008 Managment Studio has this.</p>
<ol>
<li><p>If it has, please point where</p></li>
<li><p>If it has not, please tell me how can I have a T-SQL helper for creating code like this.</p></li>
</ol> | 1,222,599 | 5 | 0 | null | 2009-08-03 14:12:05.863 UTC | 17 | 2019-02-12 06:29:05.62 UTC | 2009-08-03 14:18:19.683 UTC | null | 56,338 | null | 48,465 | null | 1 | 62 | sql-server-2005|tsql|ssms | 95,449 | <p>Well, if you have entire rows as duplicates in your table, you've at least not got a primary key set up for that table, otherwise at least the primary key value would be different.</p>
<p>However, here's how to build a SQL to get duplicates over a set of columns:</p>
<pre><code>SELECT col1, col2, col3, col4
FROM table
GROUP BY col1, col2, col3, col4
HAVING COUNT(*) > 1
</code></pre>
<p>This will find rows which, for columns col1-col4, has the same combination of values, more than once.</p>
<p>For instance, in the following table, rows 2+3 would be duplicates:</p>
<pre><code>PK col1 col2 col3 col4 col5
1 1 2 3 4 6
2 1 3 4 7 7
3 1 3 4 7 10
4 2 3 1 4 5
</code></pre>
<p>The two rows share common values in columns col1-col4, and thus, by that SQL, is considered duplicates. Expand the list of columns to contain all the columns you wish to analyze this for.</p> |
117,006 | Prevent people from pushing a git commit with a different author name? | <p>In git, it is up to each user to specify the correct author in their local git config file. When they push to a centralized bare repository, the commit messages on the repository will have the author names that they used when committing to their own repository.</p>
<p>Is there a way enforce that a set of known authors for commits are used? The "central" repository will be accessible via ssh.</p>
<p>I know that this is complicated by the fact that some people may be pushing commits that were made by others. Of course, you should also only allow people you trust to push to your repositories, but it would be great if there was a way to prevent user error here.</p>
<p>Is there a simple solution to this problem in git? </p> | 642,182 | 6 | 2 | null | 2008-09-22 19:35:43.77 UTC | 17 | 2016-04-25 14:33:36.763 UTC | null | null | null | Tim | 4,883 | null | 1 | 26 | git | 10,460 | <p>We use the following to prevent accidental unknown-author commits (for example when doing a fast commit from a customer's server or something). It should be placed in .git/hooks/pre-receive and made executable.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from itertools import islice, izip
import sys
old, new, branch = sys.stdin.read().split()
authors = {
"John Doe": "[email protected]"
}
proc = subprocess.Popen(["git", "rev-list", "--pretty=format:%an%n%ae%n", "%s..%s" % (old, new)], stdout=subprocess.PIPE)
data = [line.strip() for line in proc.stdout.readlines() if line.strip()]
def print_error(commit, author, email, message):
print "*" * 80
print "ERROR: Unknown Author!"
print "-" * 80
proc = subprocess.Popen(["git", "rev-list", "--max-count=1", "--pretty=short", commit], stdout=subprocess.PIPE)
print proc.stdout.read().strip()
print "*" * 80
raise SystemExit(1)
for commit, author, email in izip(islice(data, 0, None, 3), islice(data, 1, None, 3), islice(data, 2, None, 3)):
_, commit_hash = commit.split()
if not author in authors:
print_error(commit_hash, author, email, "Unknown Author")
elif authors[author] != email:
print_error(commit_hash, author, email, "Unknown Email")
</code></pre> |
269,106 | Inheriting from a UserControl in WPF | <p>I am fairly new to WPF and I am having a problem with inheriting from a user control.</p>
<p>I created a User Control and now I need to inherit from that control and add some more functionality.</p>
<p>Has anyone does this sort of thing before? Any help would be greatly appreciated.</p>
<p>Thank you</p> | 271,407 | 6 | 1 | null | 2008-11-06 15:26:35.437 UTC | 4 | 2022-08-18 14:05:14.573 UTC | null | null | null | null | 35,129 | null | 1 | 34 | wpf|inheritance|user-controls | 55,934 | <p>AFAIK you cannot inherit the xaml, you can only inherit the code behind.</p>
<p>We recently encountered the same problem on our project. The way we ended up solving our problem was to create a usercontrol and adding it to the "child" usercontrol.</p>
<p>If that doesnt work/help take a look at this:
<a href="https://web.archive.org/web/20200815091447/http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx%5B1%5D" rel="nofollow noreferrer">https://web.archive.org/web/20200815091447/http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx[1]</a></p> |
676,663 | What do I return if the return type of a method is Void? (Not void!) | <p>Due to the use of Generics in Java I ended up in having to implement a function having <code>Void</code> as return type:</p>
<pre><code>public Void doSomething() {
//...
}
</code></pre>
<p>and the compiler demands that I return <em>something</em>. For now I'm just returning <code>null</code>, but I'm wondering if that is good coding practice...</p>
<p>I'm asking about <strong>V</strong>oid, not <strong>v</strong>oid. The class <code>Void</code>, <strong>not</strong> the reserved keyword <code>void</code>.</p>
<p>I've also tried <code>Void.class</code>, <code>void</code>, <code>Void.TYPE</code>, <code>new Void()</code>, no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See <a href="https://stackoverflow.com/questions/676663/what-do-i-return-if-the-return-type-of-a-method-is-void-not-void/881358#881358">this answer</a> for details)</p>
<ul>
<li>So what am I supposed to return if the return type of a function is <code>Void</code>? </li>
<li>What's the general use of the <code>Void</code> class?</li>
</ul> | 676,689 | 6 | 0 | null | 2009-03-24 09:31:54.593 UTC | 25 | 2019-03-07 10:11:59.193 UTC | 2019-03-07 10:11:59.193 UTC | DR | 1,233,251 | DR | 23,368 | null | 1 | 119 | java|generics|void | 68,279 | <blockquote>
<p>So what am I supposed to return if the return type of a function has to be <code>Void</code>? </p>
</blockquote>
<p>Use <code>return null</code>. <code>Void</code> can't be instantiated and is merely a placeholder for the <code>Class<T></code> type of <code>void</code>.</p>
<blockquote>
<p>What's the point of <code>Void</code>?</p>
</blockquote>
<p>As noted above, it's a placeholder. <code>Void</code> is what you'll get back if you, for example, use reflection to look at a method with a return type of <code>void</code>. (Technically, you'll get back <code>Class<Void></code>.) It has other assorted uses along these lines, like if you want to parameterize a <code>Callable<T></code>.</p>
<blockquote>
<p>Due to the use of generics in Java I ended up in having to implement this function</p>
</blockquote>
<p>I'd say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there's a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I'm a little suspicious, since this only came up "due to the use of generics".</p> |
454,355 | Security of REST authentication schemes | <p>Background:</p>
<p>I'm designing the authentication scheme for a REST web service. This doesn't "really" need to be secure (it's more of a personal project) but I want to make it as secure as possible as an exercise/learning experience. I don't want to use SSL since I don't want the hassle and, mostly, the expense of setting it up.</p>
<p>These SO questions were especially useful to get me started:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/319530/restful-authentication">RESTful Authentication</a></li>
<li><a href="https://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service">Best Practices for securing a REST API / web service</a></li>
<li><a href="https://stackoverflow.com/questions/409338/examples-of-the-best-soap-rest-rpc-web-apis-and-why-do-you-like-them-and-whats">Examples of the best SOAP/REST/RPC web APIs? And why do you like them? And what’s wrong with them?</a></li>
</ul>
<p>I'm thinking of using a simplified version of <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTAuthentication.html" rel="noreferrer">Amazon S3's authentication</a> (I like <a href="http://oauth.net/" rel="noreferrer">OAuth</a> but it seems too complicated for my needs). I'm adding a randomly generated <a href="http://en.wikipedia.org/wiki/Cryptographic_nonce" rel="noreferrer">nonce</a>, supplied by the server, to the request, to prevent replay attacks.</p>
<p>To get to the question: </p>
<p>Both S3 and OAuth rely on signing the request URL along with a few selected headers. <strong>Neither of them sign the request body</strong> for POST or PUT requests. Isn't this vulnerable to a man-in-the-middle attack, which keeps the url and headers and replaces the request body with any data the attacker wants?</p>
<p>It seems like I can guard against this by including a hash of the request body in the string that gets signed. Is this secure?</p> | 10,557,662 | 6 | 9 | null | 2009-01-18 00:12:10.863 UTC | 205 | 2015-01-12 11:41:10.617 UTC | 2017-05-23 11:47:16.49 UTC | Hank Gay | -1 | dF | 3,002 | null | 1 | 234 | rest|authentication|oauth|amazon-s3|rest-security | 109,982 | <p>A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.</p>
<p>You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL <em>alone</em> is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the <em>server</em>, which is irrelevant for most REST APIs because you really want to authenticate the <em>client</em>. </p>
<p>If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).</p>
<p>These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.</p>
<p>For those interested, I've expanded on an SO question about <a href="https://stackoverflow.com/questions/14043397/http-basic-authentication-instead-of-tls-client-certificaiton">HTTP Authentication Schemes and how they work</a>.</p> |
13,449,743 | VBA how to display real time clock in a userform? | <p>So I need to display a real-time clock on my form but I am not sure how. I do know that the code:</p>
<pre><code>TimeValue(Now)
</code></pre>
<p>will give me the current time, but I am not sure how to continually display this on my form.</p>
<p>I have an idea which is to put this code inside of a loop as follows:</p>
<pre><code>Dim bool As Boolean
bool = True
Do While bool = True
Label1.Caption = TimeValue(Now)
Loop
</code></pre>
<p>However I am not sure where to put this code. Any suggestions would be greatly appreciated!</p> | 13,624,358 | 3 | 0 | null | 2012-11-19 08:02:00.697 UTC | 1 | 2020-12-23 09:50:10.42 UTC | 2012-11-19 09:21:45.973 UTC | null | 641,067 | null | 1,786,196 | null | 1 | 4 | vba|excel | 46,941 | <p>I solved the issue others were having with the given code in the chosen answer. I removed the <code>latesttime</code> line and i changed <code>Label1.caption = Now()</code> to use <code>Time()</code> instead.</p>
<pre><code>Sub DisplayCurrentTime()
Dim nextSecond As Date
nextSecond = DateAdd("s", 1, Now())
Label1.Caption = Time()
Application.OnTime _
Procedure:="DisplayCurrentTime", _
EarliestTime:=nextSecond
End Sub
</code></pre>
<p>I then called this in my <code>userform_initialize</code> function. <code>Label1.caption</code> was changed to the appropriate label on my <code>userform</code>.</p> |
35,506,851 | Get everything before a certain character in SQL | <p>I got the following entries in my database:</p>
<pre><code>E01234-1-1
E01234444-1-800000000
</code></pre>
<p>I want to trim the entry so I get: </p>
<pre><code>E01234-1
E01234444-1
</code></pre>
<p>So basically, I want everything before the second '-' regardless of the length</p>
<p>How can I solve it? Im using MS SQL SERVER 2012</p>
<p>I am using this but it only bring data from before first hyphen, not second hyphen</p>
<pre><code>DECLARE @TABLE TABLE (STRING VARCHAR(100))
INSERT INTO @TABLE (STRING)
SELECT 'E01234-1-1'
UNION ALL SELECT 'E01234-1-200'
UNION ALL SELECT 'E01234-1-3000'
UNION ALL SELECT 'E01234-1-40000'
UNION ALL SELECT 'E01234-1-500000'
UNION ALL SELECT 'E01234-1-6000000'
UNION ALL SELECT 'E01234-1-70000000'
UNION ALL SELECT 'E01234444-1-800000000'
SELECT LEFT(STRING, CHARINDEX('-',STRING)-1) STRIPPED_STRING from @TABLE
</code></pre>
<p>RETURNS
<code>
E01234
E01234
E01234
E01234
E01234
E01234
E01234
E01234444</code></p> | 35,507,628 | 3 | 3 | null | 2016-02-19 13:45:54.487 UTC | 1 | 2018-02-19 18:44:36.563 UTC | 2016-02-19 15:10:26.567 UTC | null | 4,964,923 | null | 4,828,104 | null | 1 | 6 | sql|sql-server|tsql | 57,454 | <p>If you need the second <code>-</code>:</p>
<pre><code>SELECT
LEFT(STRING, CHARINDEX('-', @test, CHARINDEX('-', @test) + 1) -1) STRIPPED_STRING
FROM @TABLE
</code></pre>
<p>Explanation: <code>CHARINDEX</code> will get you the index of the <code>-</code> - doing it twice (+ 1) specifies that the outter <code>CHARINDEX</code> should start at the spot after the first <code>-</code> in the string.</p>
<p>If you want to chop off everything after the last <code>-</code> instead (regardless of whether it's second or not):</p>
<pre><code>SELECT
LEFT(STRING, LEN(STRING) - CHARINDEX('-', REVERSE(STRING))) STRIPPED_STRING
FROM @table
</code></pre>
<p>This time, you get the <code>CHARINDEX</code> of the last (reverse the string) <code>-</code>, and subtract that from the length of the whole string.</p> |
21,392,954 | How to install, verify and update all Octave packages at once? | <p>Today I have installed Octave 3.8 with GUI on my Windows 7 machine. Is there a command that will install all the available Octave packages ? Then I would also like to see a list of all the installed packages, and update them at times. So is there a command that checks for updates of all the installed packages ? Thank you.</p> | 21,411,126 | 3 | 7 | null | 2014-01-27 22:23:28.273 UTC | 3 | 2018-04-28 22:41:29.727 UTC | null | null | null | null | 3,055,594 | null | 1 | 7 | octave|package | 38,579 | <p>It looks as if <code>pkg update</code> will update all your installed packages. See the <a href="http://octave.sourceforge.net/octave/function/pkg.html" rel="noreferrer">documentation on <code>pkg</code></a> for more details.</p>
<p>I haven't found a way to install all packages, I am doing them one at a time using <code>pkg install -forge <package_name></code>, which is a bit tedious. It is also giving me errors when trying to install <code>parallel</code>.</p> |
17,733,139 | Getting the correct timezone offset in Python using local timezone | <p>Ok let me first start by saying my timezone is CET/CEST. The exact moment it changes from CEST to CET (back from DST, which is GMT+2, to normal, which GMT+1, thus) is always the last Sunday of October at 3AM. In 2010 this was 31 October 3AM.</p>
<p>Now note the following:</p>
<pre><code>>>> import datetime
>>> import pytz.reference
>>> local_tnz = pytz.reference.LocalTimezone()
>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 31, 2, 12, 30))
datetime.timedelta(0, 3600)
</code></pre>
<p>This is wrong as explained above.</p>
<pre><code>>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 30, 2, 12, 30))
datetime.timedelta(0, 7200)
>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 31, 2, 12, 30))
datetime.timedelta(0, 7200)
</code></pre>
<p>Now it is suddenly correct :/</p>
<p>I know there are several questions about this already, but the solution given is always "use localize", but my problem here is that the LocalTimezone does not provide that method.</p>
<p>In fact, I have several timestamps in milliseconds of which I need the utcoffset of the local timezone (not just mine, but of anyone using the program). One of these is 1288483950000 or Sun Oct 31 2010 02:12:30 GMT+0200 (CEST) in my timezone.</p>
<p>Currently I do the following to get the datetime object:</p>
<pre><code>datetime.datetime.fromtimestamp(int(int(millis)/1E3))
</code></pre>
<p>and this to get the utcoffset in minutes:</p>
<pre><code>-int(local_tnz.utcoffset(date).total_seconds()/60)
</code></pre>
<p>which, unfortunately, is wrong in many occasions :(.</p>
<p>Any ideas?</p>
<p>Note: I'm using python3.2.4, not that it should matter in this case.</p>
<p><strong>EDIT:</strong></p>
<p>Found the solution thanks to @JamesHolderness:</p>
<pre><code>def datetimeFromMillis(millis):
return pytz.utc.localize(datetime.datetime.utcfromtimestamp(int(int(millis)/1E3)))
def getTimezoneOffset(date):
return -int(date.astimezone(local_tz).utcoffset().total_seconds()/60)
</code></pre>
<p>With local_tz equal to tzlocal.get_localzone() from the tzlocal module.</p> | 17,775,976 | 3 | 3 | null | 2013-07-18 20:21:08.943 UTC | 15 | 2020-08-18 22:46:37.053 UTC | 2013-07-22 20:56:24.45 UTC | null | 1,047,506 | null | 1,047,506 | null | 1 | 27 | python|timezone|pytz|timezone-offset | 80,612 | <p>According to <a href="https://en.wikipedia.org/wiki/European_Summer_Time">Wikipedia</a>, the transition to and from Summer Time occurs at 01:00 UTC.</p>
<ul>
<li><p>At 00:12 UTC you are still in Central European Summer Time (i.e. UTC+02:00), so the local time is 02:12.</p></li>
<li><p>At 01:12 UTC you are back in the standard Central European Time (i.e. UTC+01:00), so the local time is again 02:12.</p></li>
</ul>
<p>When changing from Summer Time back to standard time, the local time goes from 02:59 back to 02:00 and the hour repeats itself. So when asking for the UTC offset of 02:12 (local time), the answer could truthfully be either +01:00 or +02:00 - it depends which version of 02:12 you are talking about.</p>
<p>On further investigation of the pytz library, I think your problem may be that you shouldn't be using the pytz.reference implementation, which may not deal with these ambiguities very well. Quoting from the comments in the source code:</p>
<blockquote>
<p>Reference tzinfo implementations from the Python docs.
Used for testing against as they are only correct for the years
1987 to 2006. Do not use these for real code.</p>
</blockquote>
<p><strong>Working with ambiguous times in pytz</strong></p>
<p>What you should be doing is constructing a <em>timezone</em> object for the appropriate timezone:</p>
<pre><code>import pytz
cet = pytz.timezone('CET')
</code></pre>
<p>Then you can use the <em>utcoffset</em> method to calculate the UTC offset of a date/time in that timezone.</p>
<pre><code>dt = datetime.datetime(2010, 10, 31, 2, 12, 30)
offset = cet.utcoffset(dt)
</code></pre>
<p>Note, that the above example will throw an <em>AmbiguousTimeError</em> exception, because it can't tell which of the two versions of 02:12:30 you meant. Fortunately pytz will let you specify whether you want the dst version or the standard version by setting the <em>is_dst</em> parameter. For example:</p>
<pre><code>offset = cet.utcoffset(dt, is_dst = True)
</code></pre>
<p>Note that it doesn't harm to set this parameter on all calls to <em>utcoffset</em>, even if the time wouldn't be ambiguous. According to the documentation, it is only used during DST transition ambiguous periods to resolve that ambiguity.</p>
<p><strong>How to deal with timestamps</strong></p>
<p>As for dealing with timestamps, it's best you store them as UTC values for as long as possible, otherwise you potentially end up throwing away valuable information. So first convert to a UTC datetime with the <em>datetime.utcfromtimestamp</em> method.</p>
<pre><code>dt = datetime.datetime.utcfromtimestamp(1288483950)
</code></pre>
<p>Then use pytz to localize the time as UTC, so the timezone is attached to the datetime object.</p>
<pre><code>dt = pytz.utc.localize(dt)
</code></pre>
<p>Finally you can convert that UTC datetime into your local timezone, and obtain the timezone offset like this:</p>
<pre><code>offset = dt.astimezone(cet).utcoffset()
</code></pre>
<p>Note that this set of calculations will produce the correct offsets for both 1288483950 and 1288487550, even though both timestamps are represented by 02:12:30 in the CET timezone.</p>
<p><strong>Determining the local timezone</strong></p>
<p>If you need to use the local timezone of your computer rather than a fixed timezone, you can't do that from pytz directly. You also can't just construct a <em>pytz.timezone</em> object using the timezone name from <em>time.tzname</em>, because the names won't always be recognised by pytz.</p>
<p>The solution is to use the <a href="https://pypi.python.org/pypi/tzlocal">tzlocal module</a> - its sole purpose is to provide this missing functionality in pytz. You use it like this:</p>
<pre><code>import tzlocal
local_tz = tzlocal.get_localzone()
</code></pre>
<p>The <em>get_localzone()</em> function returns a <em>pytz.timezone</em> object, so you should be able to use that value in all the places I've used the <em>cet</em> variable in the examples above.</p> |
21,367,824 | How to evalute an exponential tower modulo a prime | <p>I want to find a fast algorithm to evaluate an expression like the following, where <em>P</em> is prime.</p>
<pre><code>A ^ B ^ C ^ D ^ E mod P
</code></pre>
<p>Example:</p>
<pre><code>(9 ^ (3 ^ (15 ^ (3 ^ 15)))) mod 65537 = 16134
</code></pre>
<p>The problem is the intermediate results can grow much too large to handle.</p> | 21,368,784 | 1 | 10 | null | 2014-01-26 19:02:22.853 UTC | 10 | 2017-11-20 00:18:53.747 UTC | 2014-03-03 16:55:14.94 UTC | null | 916,657 | null | 1,971,083 | null | 1 | 9 | algorithm|math|language-agnostic | 3,214 | <p>Basically the problem reduces to computing <code>a^T mod m</code> for given <code>a</code>, <code>m</code> and a term <code>T</code> that is ridiulously huge. However, we are able to evaluate <code>T mod n</code> with a given modulus <code>n</code> much faster than <code>T</code> . So we ask: "Is there an integer <code>n</code>, such that <code>a^(T mod n) mod m = a^T mod m</code>?"</p>
<p>Now if <code>a</code> and <code>m</code> are coprime, we know that <code>n = phi(m)</code> fulfills our condition according to <a href="http://en.wikipedia.org/wiki/Euler%27s_theorem" rel="noreferrer">Euler's theorem</a>:</p>
<pre><code> a^T (mod m)
= a^((T mod phi(m)) + k * phi(m)) (mod m) (for some k)
= a^(T mod phi(m)) * a^(k * phi(m)) (mod m)
= a^(T mod phi(m)) * (a^phi(m))^k (mod m)
= a^(T mod phi(m)) * 1^k (mod m)
= a^(T mod phi(m)) (mod m)
</code></pre>
<p>If we can compute <code>phi(m)</code> (which is easy to do for example in <code>O(m^(1/2))</code> or if we know the prime factorization of <code>m</code>), we have reduced the problem to computing <code>T mod phi(m)</code> and a simple <a href="https://en.wikipedia.org/wiki/Modular_exponentiation" rel="noreferrer">modular exponentiation</a>.</p>
<p>What if <code>a</code> and <code>m</code> are not coprime? The situation is not as pleasant as before, since there might not be a valid <code>n</code> with the property <code>a^T mod m = a^(T mod n) mod m</code> for all <code>T</code>. However, we can show that the sequence <code>a^k mod m</code> for <code>k = 0, 1, 2, ...</code> enters a cycle after some point, that is there exist <code>x</code> and <code>C</code> with <code>x, C < m</code>, such that <code>a^y = a^(y + C)</code> for all <code>y >= x</code>.</p>
<p><strong>Example</strong>: For <code>a = 2, m = 12</code>, we get the sequence <code>2^0, 2^1, ... = 1, 2, 4, 8, 4, 8, ... (mod 12)</code>. We can see the cycle with parameters <code>x = 2</code> and <code>C = 2</code>.</p>
<p>We can find the cycle length via brute-force, by computing the sequence elements <code>a^0, a^1, ...</code> until we find two indices <code>X < Y</code> with <code>a^X = a^Y</code>. Now we set <code>x = X</code> and <code>C = Y - X</code>. This gives us an algorithm with <code>O(m)</code> exponentiations per recursion.</p>
<p>What if we want to do better? Thanks to <a href="https://math.stackexchange.com/users/11619/jyrki-lahtonen">Jyrki Lahtonen</a> from Math Exchange for providing <a href="https://math.stackexchange.com/a/653696/15462">the essentials for the following algorithm</a>!</p>
<p>Let's evaluate the sequence <code>d_k = gcd(a^k, m)</code> until we find an <code>x</code> with <code>d_x = d_{x+1}</code>. This will take at most <code>log(m)</code> GCD computations, because <code>x</code> is bounded by the highest exponent in the prime factorization of <code>m</code>. Let <code>C = phi(m / d_x)</code>. <a href="https://math.stackexchange.com/a/653696/15462">We can now prove that</a> <code>a^{k + C} = a^k</code> for all <code>k >= x</code>, so we have found the cycle parameters in <code>O(m^(1/2))</code> time.</p>
<p>Let's assume we have found <code>x</code> and <code>C</code> and want to compute <code>a^T mod m</code> now.
If <code>T < x</code>, the task is trivial to perform with simple modular exponentiation. Otherwise, we have <code>T >= x</code> and can thus make use of the cycle:</p>
<pre><code> a^T (mod m)
= a^(x + ((T - x) mod C)) (mod m)
= a^(x + (-x mod C) + (T mod C) + k*C) (mod m) (for some k)
= a^(x + (-x mod C) + k*C) * a^(T mod C) (mod m)
= a^(x + (-x mod C)) * a^(T mod C) (mod m)
</code></pre>
<p>Again, we have reduced the problem to a subproblem of the same form ("compute <code>T mod C</code>") and two simple modular exponentiations. </p>
<p>Since the modulus is reduced by at least 1 in every iteration, we get a pretty weak bound of <code>O(P^(1/2) * min (P, n))</code> for the runtime of this algorithm, where <code>n</code> is the height of the stack. In practice we should get a lot better, since the moduli are expected to decrease exponentially. Of course this argument is a bit hand-wavy, maybe some more mathematically-inclined person can improve on it.</p>
<p>There are a few edge cases to consider that actually make your life a bit easier: you can stop immediately if <code>m = 1</code> (the result is 0 in this case) or if <code>a</code> is a multiple of <code>m</code> (the result is 0 as well in this case).</p>
<p><strong>EDIT:</strong> It can be shown that <code>x = C = phi(m)</code> is valid, so as a quick and dirty solution we can use the formula</p>
<pre><code>a^T = a^(phi(m) + T mod phi(m)) (mod m)
</code></pre>
<p>for <code>T >= phi(m)</code> or even <code>T >= log_2(m)</code>.</p> |
23,031,754 | Declare multiple variables on one line in perl | <p>I found that I can declare two variables in one statement using:</p>
<pre><code>my ($a,$b)=(1,2);
</code></pre>
<p>But I think this syntax may be confusing, for instance, if we had five variables declarations, it would be difficult to see which value belongs to which variable. So I think it would be better if we could use this syntax:</p>
<pre><code>my $a=1, $b=2;
</code></pre>
<p>I wonder, why is this kind of declaration not possible in Perl? And are there any alternatives?</p>
<p>(I am trying to avoid repeating <code>my</code> for each declaration like: <code>my $a=1; my $b=2;</code>)</p> | 23,031,892 | 6 | 3 | null | 2014-04-12 14:35:06.52 UTC | 1 | 2021-06-16 16:02:59.053 UTC | null | null | null | null | 2,173,773 | null | 1 | 22 | perl | 50,597 | <p>No. Variables declared by <code>my</code> are only named once the next statement begins. The only way you can assign to the newly created variable is if you assign to the variable it returns. Think of <code>my</code> as <code>new</code> that also declares.</p>
<p>As for your particular code,</p>
<pre><code>my $a=1, $b=2;
</code></pre>
<p>means</p>
<pre><code>((my $a)=1), ($b=2);
</code></pre>
<p>Obviously, no good.</p>
<p>If you had used variables that weren't already declared<sup>[1]</sup>, you would have gotten a strict error.</p>
<hr>
<ol>
<li><code>$a</code> and <code>$b</code> are predeclared in every namespace to facilitate the use of <code>sort</code>.</li>
</ol> |
1,371,940 | Unit testing: Is it a good practice to have assertions in setup methods? | <p>In unit testing, the setup method is used to create the objects needed for testing.</p>
<p>In those setup methods, I like using assertions: I know what values I want to see in those
objects, and I like to document that knowledge via an assertion.</p>
<p>In a recent post on <a href="https://stackoverflow.com/questions/1368900/unit-testing-is-it-bad-form-to-have-unit-test-calling-other-unit-tests">unit tests calling other unit tests</a> here on stackoverflow, the general feeling seems to be that unit tests should <em>not</em> call other tests:
The answer to that question seems to be that you should refactor your setup, so
that test cases do not depend on each other.</p>
<p>But there isn't much difference in a "setup-with-asserts" and a
unit test calling other unit tests.</p>
<p>Hence my question: Is it good practice to have assertions in setup methods? </p>
<p>EDIT:</p>
<p>The answer turns out to be: this is not a good practice in general. If the setup results need to be tested, it is recommended to add a separate test method with the assertions (the answer I ticked); for documenting intent, consider using Java asserts.</p> | 1,372,255 | 5 | 1 | null | 2009-09-03 07:38:15.037 UTC | 6 | 2011-03-29 10:15:24.87 UTC | 2017-05-23 12:25:26.727 UTC | null | -1 | null | 165,292 | null | 1 | 36 | unit-testing|refactoring|fixtures|assertions | 11,837 | <p>Instead of assertions in the setup to check the result, <strong>I used a simple test</strong> (a test method along the others, but positionned as first test method).</p>
<p>I have seen several advantages:</p>
<ul>
<li>The <strong>setup keeps short and focused</strong>, for readability.</li>
<li>The assertions are run only once, which is more <strong>efficient</strong>.</li>
</ul>
<hr>
<p><strong>Usage and discussion</strong> :</p>
<p>For example, I name the method testSetup(). </p>
<p>To use it, when I have some test errors in that class, I know that if testSetup() has an error, I don't need to bother with the other errors, I need to fix this one first.</p>
<p>If someone is bothered by this, and wants to make this dependency explicit, the testSetup() could be called in the setup() method. But I don't think it matters. My point is that, in JUnit, you can already have something similar in the rest of your tests:</p>
<ol>
<li>some tests that test local code, </li>
<li>and some tests that is calls more global code, which indirectly calls the same code as the previous test.</li>
</ol>
<p>When you read the test result where both fail, <strong>you already have to take care of this dependency that is not in the test, but in the code being called</strong>. You have to fix the simple test first, and then rerun the global test to see if it still fails.
This is the reason why I'm not bothered by the implicit dependency I explained before.</p> |
2,280,539 | Custom model validation of dependent properties using Data Annotations | <p>Since now I've used the excellent <a href="http://fluentvalidation.codeplex.com/wikipage" rel="noreferrer">FluentValidation</a>
library to validate my model classes. In web applications I use it in conjunction with the <a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">jquery.validate</a> plugin to perform client side validation as well.
One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place.</p>
<p>For this reason I'm looking for an alternative. There are <a href="http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx" rel="noreferrer">many</a> examples out <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html" rel="noreferrer">there</a> showing the usage of data annotations to perform model validation. It looks very promising.
One thing I couldn't find out is how to validate a property that depends on another property value.</p>
<p>Let's take for example the following model:</p>
<pre><code>public class Event
{
[Required]
public DateTime? StartDate { get; set; }
[Required]
public DateTime? EndDate { get; set; }
}
</code></pre>
<p>I would like to ensure that <code>EndDate</code> is greater than <code>StartDate</code>. I could write a custom
validation attribute extending <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx" rel="noreferrer">ValidationAttribute</a> in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the
model instance:</p>
<pre><code>public class CustomValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// value represents the property value on which this attribute is applied
// but how to obtain the object instance to which this property belongs?
return true;
}
}
</code></pre>
<p>I found that the <a href="http://weblogs.asp.net/peterblum/archive/2009/12/07/the-customvalidationattribute.aspx" rel="noreferrer">CustomValidationAttribute</a> seems to do the job because it has this <code>ValidationContext</code> property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1?</p>
<hr>
<p>UPDATE:</p>
<p>It seems that <a href="http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/" rel="noreferrer">FluentValidation already supports</a> clientside validation and metadata in ASP.NET MVC 2. </p>
<p>Still it would be good to know though if data annotations could be used to validate dependent properties.</p> | 2,360,115 | 5 | 1 | null | 2010-02-17 12:30:50.71 UTC | 16 | 2015-12-09 15:23:01.45 UTC | 2010-02-17 16:08:35.587 UTC | null | 29,407 | null | 29,407 | null | 1 | 45 | validation|.net-3.5|asp.net-mvc-2|data-annotations | 41,405 | <p>MVC2 comes with a sample "PropertiesMustMatchAttribute" that shows how to get DataAnnotations to work for you and it should work in both .NET 3.5 and .NET 4.0. That sample code looks like this:</p>
<pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty
{
get;
private set;
}
public string OriginalProperty
{
get;
private set;
}
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
</code></pre>
<p>When you use that attribute, rather than put it on a property of your model class, you put it on the class itself:</p>
<pre><code>[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
public string NewPassword { get; set; }
public string ConfirmPassword { get; set; }
}
</code></pre>
<p>When "IsValid" gets called on your custom attribute, the whole model instance is passed to it so you can get the dependent property values that way. You could easily follow this pattern to create a date comparison attribute, or even a more general comparison attribute.</p>
<p><a href="http://bradwilson.typepad.com/blog/2010/01/remote-validation-with-aspnet-mvc-2.html" rel="noreferrer">Brad Wilson has a good example on his blog</a> showing how to add the client-side portion of the validation as well, though I'm not sure if that example will work in both .NET 3.5 and .NET 4.0.</p> |
2,091,830 | Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous | <p>I've used the following split function:</p>
<pre><code>CREATE FUNCTION dbo.Splitfn(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
</code></pre>
<p>and i used this function in a query and it was executed</p>
<pre><code>ALTER PROCEDURE [dbo].[Employees_Delete]
-- Add the parameters for the stored procedure here
@Id varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if exists( select Emp_Id from Employee where Emp_Id=dbo.Splitfn(@Id,','))
begin
update Employee set Is_Deleted=1 where Emp_Id=dbo.Splitfn(@Id,',')
select 'deleted' as message
end
END
</code></pre>
<p>but when i excute my store procedure giving values say (1,2) i got the error</p>
<pre><code>Cannot find either column "dbo" or the user-defined
function or aggregate "dbo.Splitfn", or the name is ambiguous.
</code></pre>
<p>I've checked my tablevalued functions the function 'splitfn' was there but I don't know what is going wrong? Any suggestions..</p> | 2,091,864 | 5 | 0 | null | 2010-01-19 07:33:06.763 UTC | 7 | 2022-06-20 08:59:57.037 UTC | 2022-06-20 08:59:57.037 UTC | null | 74,585 | null | 146,857 | null | 1 | 67 | sql-server|sql-server-2005|tsql|user-defined-functions | 148,773 | <p>It's a table-valued function, but you're using it as a scalar function.</p>
<p>Try:</p>
<pre><code>where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)
</code></pre>
<p>But... also consider changing your function into an inline TVF, as it'll perform better.</p> |
1,933,015 | Opening a File from assets folder in android | <p>I have a .gif file inside the assets folder like this assets/Files/android.gif. when I try to open the file it throws an exception at the second line </p>
<pre><code>AssetManager mngr=getAssets();
InputStream is2=mngr.open("Files/android.gif");
</code></pre>
<p>so Is it that I'm trying to open an image file despite that the same code works if I try to open a text file ?
what can be the problem here.</p> | 8,502,231 | 6 | 0 | null | 2009-12-19 14:18:44.36 UTC | 5 | 2018-10-27 23:29:52.473 UTC | 2013-05-18 08:10:57.67 UTC | null | 683,261 | null | 235,123 | null | 1 | 15 | android|android-assets | 62,406 | <p>These Lines are working perfectly--</p>
<pre><code>InputStream assetInStream=null;
try {
assetInStream=getAssets().open("icon.png");
Bitmap bit=BitmapFactory.decodeStream(assetInStream);
img.setImageBitmap(bit);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(assetInStream!=null)
assetInStream.close();
}
</code></pre>
<p>If your image is very big then you should scale your image before decoding it into Bitmap. <a href="http://androidtrainningcenter.blogspot.in/2012/04/displaying-bitmaps-efficiently-and.html" rel="nofollow noreferrer">See How to display large image efficiently</a></p> |
1,645,209 | How can I filter ListView data when typing on EditText in android | <p>I have a <code>ListView</code> and a <code>EditText</code>. How can I filter ListView data when typing on <code>EditText</code>? </p> | 1,645,686 | 6 | 3 | null | 2009-10-29 17:07:42.563 UTC | 13 | 2020-02-24 12:59:33.143 UTC | null | null | null | null | 152,286 | null | 1 | 32 | android | 53,815 | <ol>
<li>Add <code>TextWatcher</code> to <code>EditText#addTextChangedListener</code></li>
<li>In <code>onTextChanged</code> add or remove items from your <code>ListView</code>'s adapter. If you are subclassing <code>ArrayAdapter</code> it would have <code>add</code> and <code>remove</code> methods</li>
</ol> |
2,139,165 | Delete all local changesets and revert to tree | <p>I'm using Mercurial and I've got into a terrible mess locally, with three heads. I can't push, and I just want to delete all my local changes and commits and start again with totally clean code and a clean history.</p>
<p>In other words, I want to end up with (a) exactly the same code locally as exists in the tip of the remote branch and (b) no history of any local commits. </p>
<p>I know <code>hg update -C</code> overwrites any local changes. But how do I delete any local commits?</p>
<p>To be clear, I have no interest in preserving any of the work I've done locally. I just want the simplest way to revert back to a totally clean local checkout.</p> | 2,143,711 | 7 | 1 | null | 2010-01-26 11:58:06.903 UTC | 32 | 2018-12-17 19:42:48.393 UTC | 2015-02-03 13:30:22.147 UTC | null | 419,956 | null | 194,000 | null | 1 | 95 | version-control|mercurial|dvcs|head | 40,094 | <p>When the simplest way (a new <code>hg clone</code>) isn't practical, I use <code>hg strip</code>:</p>
<pre><code>% hg outgoing -l 1
% hg strip $rev # replace $rev with the revision number from outgoing
</code></pre>
<p>Repeat until <code>hg outgoing</code> stays quiet. Note that <code>hg strip $rev</code> obliterates <code>$rev</code> and all its descendants.</p>
<p>Note that you may have to <a href="https://www.mercurial-scm.org/wiki/StripExtension" rel="noreferrer">first enable <code>strip</code> in your Mercurial settings</a>.</p>
<p><strong>PS:</strong> an even smarter approach is to use the revset language, and do:</p>
<pre><code>% hg strip 'roots(outgoing())'
</code></pre> |
1,490,138 | Reading the first line of a file in Ruby | <p>I want to read <em>only</em> the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?</p>
<p>(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)</p> | 1,490,163 | 8 | 0 | null | 2009-09-29 01:28:45.897 UTC | 11 | 2019-08-12 08:42:13.58 UTC | 2009-12-05 01:12:06.45 UTC | null | 3,488 | null | 3,488 | null | 1 | 66 | ruby-on-rails|ruby|git|file-io|capistrano | 44,707 | <p>This will read exactly one line and ensure that the file is properly closed immediately after.</p>
<pre><code>strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar
</code></pre> |
1,883,414 | Why top margin of html element is ignored after floated element? | <p>I have a page with 2 divs. The first one is floated. The 2nd one has a "clear: both" CSS declaration and a big top margin. However, when I view the page in Firefox or IE8, I don't see the top margin. It looks like the 2nd div is touching the first div, instead of being separated. Is there any way to make the top margin work properly?</p>
<p>I have read the CSS spec and noticed that it says "Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn't exist.". However, I don't know what to do about that.</p>
<p>Here is an example:</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-html lang-html prettyprint-override"><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSS test</title>
</head>
<body>
<div style="float: left; border: solid red 1px">foo</div>
<div style="clear: both; margin-top: 90px; border: solid red 1px">This div should not touch the other div.</div>
</body>
</html></code></pre>
</div>
</div>
</p> | 1,883,438 | 9 | 1 | null | 2009-12-10 19:34:35.287 UTC | 14 | 2020-11-13 09:52:43.163 UTC | 2019-03-29 18:39:21.487 UTC | null | 10,139,616 | null | 28,324 | null | 1 | 53 | html|css | 41,656 | <p>You've correctly identified the problem. The floated <code><div></code> is no longer used to calculate the top margin, and therefor the 2 <code><div></code>'s just butt against each other. A simple way to solve this is just to wrap the 2nd <code><div></code>. This will allow the wrapper to (invisibly) butt up against the first <code><div></code>, and allow you to specify white space for it.</p>
<p>The trick to getting the wrapper to work right is to have the white space be internal white space. In other words, the wrapper uses padding instead of margin. This means whatever is going on outside the wrapper (like other floating elements) won't really matter.</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-html lang-html prettyprint-override"><code><div style="float: left; border: solid red 1px">foo</div>
<div class="wrapper" style="clear: both; padding-top: 90px;">
<div style="border: solid red 1px">This div should not touch the other div.</div>
</div></code></pre>
</div>
</div>
</p> |
1,353,022 | Reflection support in C | <p>I know it is not supported, but I am wondering if there are any tricks around it. Any tips?</p> | 1,353,133 | 10 | 5 | null | 2009-08-30 03:47:16.15 UTC | 16 | 2021-03-12 20:48:20.657 UTC | 2015-05-01 16:08:00.863 UTC | null | 3,453,226 | null | 129,962 | null | 1 | 36 | c|reflection | 25,809 | <p>Reflection in general is a means for a program to analyze the structure of some code.
This analysis is used to change the effective behavior of the code.</p>
<p>Reflection as analysis is generally very weak; usually it can only provide access to function and field names. This weakness comes from the language implementers essentially not wanting to make the full source code available at runtime, along with the appropriate analysis routines to extract what one wants from the source code.</p>
<p>Another approach is tackle program analysis head on, by using a strong program analysis tool, e.g., one that can parse the source text exactly the way the compiler does it.
(Often people propose to abuse the compiler itself to do this, but that usually doesn't work; the compiler machinery wants to be a compiler and it is darn hard to bend it to other purposes). </p>
<p>What is needed is a tool that:</p>
<ul>
<li>Parses language source text</li>
<li>Builds abstract syntax trees representing every detail of the program.
(It is helpful if the ASTs retain comments and other details of the source
code layout such as column numbers, literal radix values, etc.)</li>
<li>Builds symbol tables showing the scope and meaning of every identifier</li>
<li>Can extract control flows from functions</li>
<li>Can extact data flow from the code</li>
<li>Can construct a call graph for the system</li>
<li>Can determine what each pointer points-to</li>
<li>Enables the construction of custom analyzers using the above facts</li>
<li>Can transform the code according to such custom analyses
(usually by revising the ASTs that represent the parsed code)</li>
<li>Can regenerate source text (including layout and comments) from
the revised ASTs.</li>
</ul>
<p>Using such machinery, one implements analysis at whatever level of detail is needed, and then transforms the code to achieve the effect that runtime reflection would accomplish.
There are several major benefits:</p>
<ul>
<li>The detail level or amount of analysis is a matter of ambition (e.g., it isn't
limited by what runtime reflection can only do)</li>
<li>There isn't any runtime overhead to achieve the reflected change in behavior</li>
<li>The machinery involved can be general and applied across many languages, rather
than be limited to what a specific language implementation provides.</li>
<li>This is compatible with the C/C++ idea that you don't pay for what you don't use.
If you don't need reflection, you don't need this machinery. And your language
doesn't need to have the intellectual baggage of weak reflection built in.</li>
</ul>
<p>See our <a href="http://www.semdesigns.com/Products/DMS/DMSToolkit.html" rel="noreferrer">DMS Software Reengineering Toolkit</a> for a system that can do all of the above for C, Java, and COBOL, and most of it for C++.</p>
<p>[EDIT August 2017: Now handles C11 and C++2017]</p> |
2,322,953 | JAX-WS - Adding SOAP Headers | <p>I am trying to create a standalone client to consume some web services. I must add my username and password to the SOAP Header. I tried adding the credentials as follows:</p>
<pre><code>OTSWebSvcsService service = new OTSWebSvcsService();
OTSWebSvcs port = service.getOTSWebSvcs();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
...
</code></pre>
<p>When I call a method on the service I get the following exception:</p>
<pre><code>com.ibm.wsspi.wssecurity.SoapSecurityException: WSEC5048E: One of "SOAP Header" elements required.
</code></pre>
<p>What am I doing wrong? How would I add these properties to the SOAP Header? </p>
<p>Edited: I was using JAX-WS 2.1 included in JDK6. I am now using JAX-WS 2.2. I now get the following exception:</p>
<pre><code>com.ibm.wsspi.wssecurity.SoapSecurityException: WSEC5509E: A security token whose type is [http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken] is required.
</code></pre>
<p>How do I go about creating this token?</p> | 2,323,109 | 10 | 2 | null | 2010-02-24 00:57:22.333 UTC | 11 | 2020-09-17 14:55:59.483 UTC | 2010-02-24 18:26:35.673 UTC | null | 70,604 | null | 245,914 | null | 1 | 36 | java|web-services|soap|jax-ws|ws-security | 126,068 | <p>Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at <a href="https://javaee.github.io/metro/doc/user-guide/user-guide.html#adding-soap-headers-when-sending-requests" rel="noreferrer">Adding SOAP headers when sending requests</a>:</p>
<blockquote>
<p>The portable way of doing this is that
you create a <code>SOAPHandler</code> and mess
with SAAJ, but the RI provides a
better way of doing this.</p>
<p>When you create a proxy or dispatch
object, they implement
<code>BindingProvider</code> interface. When you
use the JAX-WS RI, you can downcast to
<code>WSBindingProvider</code> which defines a
few more methods provided only by the
JAX-WS RI.</p>
<p>This interface lets you set an
arbitrary number of Header object,
each representing a SOAP header. You
can implement it on your own if you
want, but most likely you'd use one of
the factory methods defined on
<code>Headers</code> class to create one. </p>
<pre><code>import com.sun.xml.ws.developer.WSBindingProvider;
HelloPort port = helloService.getHelloPort(); // or something like that...
WSBindingProvider bp = (WSBindingProvider)port;
bp.setOutboundHeader(
// simple string value as a header, like <simpleHeader>stringValue</simpleHeader>
Headers.create(new QName("simpleHeader"),"stringValue"),
// create a header from JAXB object
Headers.create(jaxbContext,myJaxbObject)
);
</code></pre>
</blockquote>
<p>Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.</p>
<p><strong>Update:</strong> It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post <a href="http://web-gmazza.rhcloud.com/blog/entry/metro-usernametoken-profile" rel="noreferrer">Implementing the WS-Security UsernameToken Profile for Metro-based web services</a> (jump to step 4). Using NetBeans for this step might ease things a lot.</p> |
2,004,135 | How to merge conflicts (file project.pbxproj) in Xcode use svn? | <p>There are two members in our team. We use Xcode's SCM (use SVN) to manger our source code files.<br>
We all add files to our Xcode project. He has committed to SVN server. When I update, Xcode find there has conflicts in <code>project.pbxproj</code> file. Then I select quit <code>Xcode</code> and manually merge the conflicts. Then I start to edit my <code>project.pbxproj</code>, merge our changes. Actually I don't know how Xcode manage files, I just add some text that my <code>project.pbxproj</code> file did't have. When I finish, my project can't open. I guess that because the <code>project.pbxproj</code> file can't be edit by manual.</p>
<p>So, I want to know, when you find this problem, the project.pbxproj file have conflicts, how to solve it?</p>
<p>Thank you! </p> | 2,004,418 | 13 | 0 | null | 2010-01-05 04:19:49.95 UTC | 26 | 2020-11-21 08:29:19.943 UTC | 2018-04-26 01:41:29.4 UTC | null | 503,099 | null | 238,028 | null | 1 | 79 | iphone|svn|xcode|conflict | 100,024 | <p>Unfortunately, there's not much you can do except to make the changes manually in one check out and then check-in the newly "merged" project.</p> |
1,940,578 | WindowsError: [Error 126] The specified module could not be found | <p>I am loading a dll in python using following code:</p>
<pre><code>if os.path.exists(dll_path):
my_dll = ctypes.cdll.LoadLibrary(dll_path)
</code></pre>
<p>But I am continuously getting the following error</p>
<p><strong>WindowsError: [Error 126] The specified module could not be found</strong></p>
<p>dll is present at the specified path, but I didn't understand why I'm getting the error.</p> | 6,087,086 | 14 | 2 | null | 2009-12-21 14:59:12.253 UTC | 6 | 2021-09-19 06:46:51.74 UTC | 2014-08-25 18:33:14.127 UTC | null | 1,172,451 | null | 216,514 | null | 1 | 46 | python|ctypes | 139,603 | <p>When I see things like this - it is usually because there are backslashes in the path which get converted.</p>
<p>For example - the following will fail - because \t in the string is converted to TAB character.</p>
<pre><code>>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\tools\depends\depends.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\tools\python271\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "c:\tools\python271\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
</code></pre>
<p>There are 3 solutions (if that is the problem)</p>
<p>a) Use double slashes...</p>
<pre><code>>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\\tools\\depends\\depends.dll")
</code></pre>
<p>b) use forward slashes</p>
<pre><code>>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:/tools/depends/depends.dll")
</code></pre>
<p>c) use RAW strings (prefacing the string with r</p>
<pre><code>>>> import ctypes
>>> ctypes.windll.LoadLibrary(r"c:\tools\depends\depends.dll")
</code></pre>
<p>While this third one works - I have gotten the impression from time to time that it is not considered 'correct' because RAW strings were meant for regular expressions. I have been using it for paths on Windows in Python for years without problem :) )</p> |
8,811,603 | How to fix PHP errors related to timezone (function.strtotime and function.date) | <p>Upgrading to a new server, I two repeated errors:</p>
<blockquote>
<p>Warning: strtotime() [function.strtotime]: It is not safe to rely on
the system's timezone settings. You are <em>required</em> to use the
date.timezone setting or the date_default_timezone_set() function. In
case you used any of those methods and you are still getting this
warning, you most likely misspelled the timezone identifier. We
selected 'America/New_York' for 'EST/-5.0/no DST' instead in...</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Warning: date() [function.date]: It is not safe to rely on the
system's timezone settings. You are <em>required</em> to use the
date.timezone setting or the date_default_timezone_set() function. In
case you used any of those methods and you are still getting this
warning, you most likely misspelled the timezone identifier. We
selected 'America/New_York' for 'EST/-5.0/no DST' instead in</p>
</blockquote>
<p>How do I go about fixing these?</p>
<p>Code in question is this:</p>
<pre><code>'date' => date("Y-M-d",strtotime($Array['_dateCreated'])),
</code></pre>
<p>I've tried putting this in an include at the top of all my pages:</p>
<pre><code><?php
date_default_timezone_set('America/New_York');
?>
</code></pre>
<p>Thanks in advance for your help.</p> | 8,811,841 | 2 | 2 | null | 2012-01-10 22:36:28.18 UTC | 6 | 2015-02-18 08:27:31.637 UTC | null | null | null | Keefer | 675,592 | null | 1 | 15 | php | 82,030 | <p><code>date.timezone</code> in <code>php.ini</code> can fix this globally.</p> |
8,495,293 | What's a clean way to stop mongod on Mac OS X? | <p>i'm running mongo 1.8.2 and trying to see how to cleanly shut it down on Mac.</p>
<p>on our ubuntu servers i can shutdown mongo cleanly from the mongo shell with:</p>
<pre><code>> use admin
> db.shutdownServer()
</code></pre>
<p>but on my Mac, it does not kill the mongod process. the output shows that it 'should be' shutdown but when i ps -ef | grep mongo it shows me an active process. also, i can still open a mongo shell and query my dbs like it was never shutdown.</p>
<p>the output from my db.shutdownServer() locally is:</p>
<pre><code>MongoDB shell version: 1.8.2
connecting to: test
> use admin
switched to db admin
> db.shutdownServer()
Tue Dec 13 11:44:21 DBClientCursor::init call() failed
Tue Dec 13 11:44:21 query failed : admin.$cmd { shutdown: 1.0 } to: 127.0.0.1
server should be down...
Tue Dec 13 11:44:21 trying reconnect to 127.0.0.1
Tue Dec 13 11:44:21 reconnect 127.0.0.1 failed couldn't connect to server 127.0.0.1
Tue Dec 13 11:44:21 Error: error doing query: unknown shell/collection.js:150
</code></pre>
<p>i know i can just kill the process but i'd like to do it more cleanly.</p> | 8,499,754 | 9 | 2 | null | 2011-12-13 19:53:04.55 UTC | 55 | 2022-07-06 01:48:21.867 UTC | 2014-01-14 17:55:15.93 UTC | null | 2,619,107 | null | 657,180 | null | 1 | 97 | macos|mongodb|launchd | 132,533 | <p>It's probably because launchctl is managing your mongod instance. If you want to start and shutdown mongod instance, unload that first:</p>
<pre><code>launchctl unload -w ~/Library/LaunchAgents/org.mongodb.mongod.plist
</code></pre>
<p>Then start mongod manually:</p>
<pre><code>mongod -f path/to/mongod.conf --fork
</code></pre>
<p>You can find your mongod.conf location from <code>~/Library/LaunchAgents/org.mongodb.mongod.plist</code>.</p>
<p>After that, <code>db.shutdownServer()</code> would work just fine.</p>
<p>Added Feb 22 2014:</p>
<p>If you have mongodb installed via homebrew, homebrew actually has a handy <code>brew services</code> command. To show current running services:</p>
<p><code>brew services list</code></p>
<p>To start mongodb:</p>
<p><code>brew services start mongodb-community</code></p>
<p>To stop mongodb if it's already running:</p>
<p><code>brew services stop mongodb-community</code></p>
<p><strong>Update</strong>*</p>
<p>As edufinn pointed out in the comment, <code>brew services</code> is now available as user-defined command and can be installed with following command: <code>brew tap gapple/services</code>.</p> |
17,879,846 | Bootstrap scrollspy offset on a fixed navbar does not work | <p>I have created and exact fiddle of my problem here for testing: <a href="http://jsfiddle.net/aVBUy/7/">http://jsfiddle.net/aVBUy/7/</a></p>
<p>The issue is, when I click on navbar items, I have a script which scrolls to the element id. And I am using scrollspy to highlight the nav elements when page is in correct position. However the scrollspy is only changing the active state when it hits the top of the browser/device. Because my navbar is fixed I need an offset applied to scrollspy to offset by 51px (navbar height).</p>
<p>I've tried everything and I can't get it to work. Please check my fiddle and see if you can find the where I'm going wrong, would help me so much.</p>
<p>Here's my minimised code...</p>
<p><strong>HTML</strong></p>
<pre><code><div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#"><img src="img/logo.gif" alt="" /></a>
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="#welcome" data-scroll="#welcome">Welcome</a></li>
<li><a href="#about" data-scroll="#about">About</a></li>
<li><a href="#route" data-scroll="#route">The Route</a></li>
<li><a href="#bike" data-scroll="#bike">The Bike</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
<div id="welcome" class="row-fluid">
<div class="span12">
<h3>Welcome</h3>
...
</div>
</div>
<hr />
<div id="about" class="row-fluid">
<div class="span12">
<h3>About the ride</h3>
...
</div>
</div>
<hr />
<div id="route" class="row-fluid">
<div class="span12">
<h3>The Route</h3>
...
</div>
</div>
<hr />
<div id="bike" class="row-fluid">
<div class="span12">
<h3>The Bike</h3>
...
</div>
</div>
<hr>
<footer>
<p class="muted"><small>© 2013 All rights reserved.</small></p>
</footer>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>body {
padding: 51px 0 0;
}
/* Override Bootstrap Responsive CSS fixed navbar */
@media (max-width: 979px) {
.navbar-fixed-top, .navbar-fixed-bottom {
position: fixed;
margin-left: 0px;
margin-right: 0px;
}
}
body > .container {
padding: 0 15px;
}
</code></pre>
<p><strong>SCRIPT</strong></p>
<pre><code>var offsetHeight = 51;
$('.nav-collapse').scrollspy({
offset: offsetHeight
});
$('.navbar li a').click(function (event) {
var scrollPos = $('body > .container').find($(this).attr('href')).offset().top - offsetHeight;
$('body,html').animate({
scrollTop: scrollPos
}, 500, function () {
$(".btn-navbar").click();
});
return false;
});
</code></pre>
<p><strong>FIDDLE</strong></p>
<p><a href="http://jsfiddle.net/aVBUy/7/">http://jsfiddle.net/aVBUy/7/</a></p> | 17,885,251 | 6 | 0 | null | 2013-07-26 11:11:49.47 UTC | 4 | 2018-11-05 12:27:02.78 UTC | 2015-12-14 16:11:05.47 UTC | null | 4,278,038 | null | 801,773 | null | 1 | 16 | jquery|twitter-bootstrap|jsfiddle|scrollspy | 51,863 | <p>You need to apply the offset to the body.</p>
<pre><code>$('body').scrollspy({
offset: offsetHeight
});
</code></pre>
<p>Also, you will need to subtract at least one from the offsetHeight in the line below, otherwise it will not work when scrolling up.</p>
<pre><code>var scrollPos = $('body > .container').find($(this).attr('href')).offset().top - (offsetHeight - 1);
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.